def get_balance_network_usd(request, network, usd_price): wallet = Wallet(request.user.wallet_id) balance_in_satoshi = wallet.balance(network=network) balance_in_bitcoin = balance_in_satoshi / 1000000 price_in_usd = float(balance_in_bitcoin) * float(usd_price) return { "priceUSD": price_in_usd, "balanceBTC": print_value(balance_in_bitcoin, network=network.lower()) }
def test_database_create_drop(self): dbtmp = Db(DATABASEFILE_TMP) Wallet.create("tmpwallet", db_uri=DATABASEFILE_TMP) self.assertRaisesRegexp(WalletError, "Wallet with name 'tmpwallet' already exists", Wallet.create, 'tmpwallet', db_uri=DATABASEFILE_TMP) dbtmp.drop_db(yes_i_am_sure=True) Wallet.create("tmpwallet", db_uri=DATABASEFILE_TMP)
def total_balance(request, infos): wallet = Wallet(request.user.wallet_id) networks = NetworkDefinition.objects.all() balance = 0 for info in infos: for network in networks: if info["symbol"] == network.symbol: balance += float(info["priceUsd"]) * float( wallet.balance(network=network.network)) return balance
def get_networks_info(request, networks): network_infos = [] wallet = Wallet(request.user.wallet_id) for network in networks: network_info.append({ "network": network["network"], "balance": wallet.balance(network=network["network"]) }) return network_infos
def __init__(self, *args, **kwargs): self.project_name = os.environ.get('PROJECT_NAME') self.deployment_name = os.environ.get('DEPLOYMENT_NAME') # Initialize bitcoin wallet xpub_wif = os.environ.get('HDKEY_XPUB_WIF', None) if xpub_wif is None: raise NoXPUBFoud try: xpub = HDKey(xpub_wif) self.wallet = Wallet.create("Wallet", keys=xpub, network='bitcoin', witness_type='segwit') except Exception as e: raise e # Initialize Ubiops Client ubiops_api_token = os.environ.get('UBIOPS_API_TOKEN', None) internal_ubiops_api_host = os.environ.get('INT_API_URL') ubiops_conf = ubiops.Configuration( host=internal_ubiops_api_host, api_key={'Authorization': 'Token {}'.format(ubiops_api_token)}, ) client = ubiops.ApiClient(ubiops_conf) self.ubiops_api = ubiops.api.CoreApi(client) environment_variables = self.ubiops_api.deployment_environment_variables_list(self.project_name, self.deployment_name) self.last_used_path_index = os.environ.get('LAST_USED_PATH_INDEX', '0/0') self.last_used_path_index_env = None for env in environment_variables: if env.name == 'LAST_USED_PATH_INDEX': self.last_used_path_index_env = env print("Wallet initialized successfuly.")
def new_wallet(self): self.wallet = Wallet.create(self.wallet_name.get()) self.wallet_key = self.wallet.get_key() self.acc.destroy() create_tkinter_label("wallet_addr", self.root, f"Your address:\n{self.wallet_key.address}", "#00FF00", 11) create_tkinter_button("pay", self.root, "Pay", "#00FF00", 20, self.send_bitcoin)
def get_transaction_fee(self, request): wallet = Wallet(request.user.wallet_id) try: tx_object = self.wallet.send_to(self.address, self.amount, network=self.network, offline=True) tx_fee = float(tx_object.fee) return {"status":True, "data":{"fee":print_value(tx_fee, network=self.network).replace(self.symbol, "")}} except Exception as e: if e.args[0] == "Not enough unspent transaction outputs found": return {"status":False, "data":{"error": "Balance to low for transaction �."}} else: return {"status":False, "data":{"error": "An error occurs�."}}
def set_wallet(self, phrase): """Set/update the current wallet :param phrase: A new phrase :type phrase: str :returns: the wallet """ wallet_delete_if_exists('Wallet', force=True) self.wallet = Wallet.create("Wallet", keys=self.phrase, witness_type='segwit', network=utils.network_to_bitcoinlib_format( self.get_network())) self.get_address() return self.wallet
current_mnemonic = mnemonics.copy() mnemonics = [] for opt in options: mnemonics.extend([s + " {}".format(opt) for s in current_mnemonic]) mnemonics = [s[1:] for s in mnemonics] warnings = set() value_errors = set() i = 0 for mnemonic in mnemonics: for passphrase in passphrases: try: w = Wallet.create("Wallet_{}".format(i), keys=mnemonic, network='bitcoin', account_id=i, scheme="bip32", password=passphrase) account_btc = w.new_account('Account BTC') w.get_key() w.get_key(account_btc.account_id) w.info() print(w.transactions_full()) except Warning as w: warnings.add(w) except ValueError as v: value_errors.add(v) i += 1 print("Warnings:") for w in warnings:
def main(): print("Command Line Wallet - BitcoinLib %s\n" % BITCOINLIB_VERSION) # --- Parse commandline arguments --- args = parse_args() db_uri = args.database if args.generate_key: passphrase = get_passphrase(args) passphrase = ' '.join(passphrase) seed = Mnemonic().to_seed(passphrase).hex() hdkey = HDKey.from_seed(seed, network=args.network) print( "Private Master key, to create multisig wallet on this machine:\n%s" % hdkey.wif_private()) print( "Public Master key, to share with other cosigner multisig wallets:\n%s" % hdkey.public_master(witness_type=args.witness_type, multisig=True).wif()) print("Network: %s" % hdkey.network.name) clw_exit() # List wallets, then exit if args.list_wallets: print("BitcoinLib wallets:") for w in wallets_list(db_uri=db_uri): if 'parent_id' in w and w['parent_id']: continue print("[%d] %s (%s) %s" % (w['id'], w['name'], w['network'], w['owner'])) clw_exit() # Delete specified wallet, then exit if args.wallet_remove: if not wallet_exists(args.wallet_name, db_uri=db_uri): clw_exit("Wallet '%s' not found" % args.wallet_name) inp = input( "\nWallet '%s' with all keys and will be removed, without private key it cannot be restored." "\nPlease retype exact name of wallet to proceed: " % args.wallet_name) if inp == args.wallet_name: if wallet_delete(args.wallet_name, force=True, db_uri=db_uri): clw_exit("\nWallet %s has been removed" % args.wallet_name) else: clw_exit("\nError when deleting wallet") else: clw_exit("\nSpecified wallet name incorrect") wlt = None if args.wallet_name and not args.wallet_name.isdigit( ) and not wallet_exists(args.wallet_name, db_uri=db_uri): if not args.create_from_key and input( "Wallet %s does not exist, create new wallet [yN]? " % args.wallet_name).lower() != 'y': clw_exit('Aborted') wlt = create_wallet(args.wallet_name, args, db_uri) args.wallet_info = True else: try: wlt = Wallet(args.wallet_name, db_uri=db_uri) if args.passphrase is not None: print( "WARNING: Using passphrase option for existing wallet ignored" ) if args.create_from_key is not None: print( "WARNING: Using create_from_key option for existing wallet ignored" ) except WalletError as e: clw_exit("Error: %s" % e.msg) if wlt is None: clw_exit("Could not open wallet %s" % args.wallet_name) if args.import_private: if wlt.import_key(args.import_private): clw_exit("Private key imported") else: clw_exit("Failed to import key") if args.wallet_recreate: wallet_empty(args.wallet_name) print("Removed transactions and generated keys from this wallet") if args.update_utxos: wlt.utxos_update() if args.update_transactions: wlt.scan(scan_gap_limit=5) if args.export_private: if wlt.scheme == 'multisig': for w in wlt.cosigner: if w.main_key and w.main_key.is_private: print(w.main_key.wif) elif not wlt.main_key or not wlt.main_key.is_private: print("No private key available for this wallet") else: print(wlt.main_key.wif) clw_exit() if args.network is None: args.network = wlt.network.name tx_import = None if args.import_tx_file: try: fn = args.import_tx_file f = open(fn, "r") except FileNotFoundError: clw_exit("File %s not found" % args.import_tx_file) try: tx_import = ast.literal_eval(f.read()) except (ValueError, SyntaxError): tx_import = f.read() if args.import_tx: try: tx_import = ast.literal_eval(args.import_tx) except (ValueError, SyntaxError): tx_import = args.import_tx if tx_import: if isinstance(tx_import, dict): wt = wlt.transaction_import(tx_import) else: wt = wlt.transaction_import_raw(tx_import, network=args.network) wt.sign() if args.push: res = wt.send() if res: print("Transaction pushed to network. Transaction ID: %s" % wt.txid) else: print("Error creating transaction: %s" % wt.error) wt.info() print("Signed transaction:") print_transaction(wt) clw_exit() if args.receive: cosigner_id = args.receive if args.receive == -1: cosigner_id = None key = wlt.get_key(network=args.network, cosigner_id=cosigner_id) print("Receive address: %s" % key.address) if QRCODES_AVAILABLE: qrcode = pyqrcode.create(key.address) print(qrcode.terminal()) else: print( "Install qr code module to show QR codes: pip install pyqrcode" ) clw_exit() if args.create_transaction == []: clw_exit("Missing arguments for --create-transaction/-t option") if args.create_transaction: if args.fee_per_kb: clw_exit("Fee-per-kb option not allowed with --create-transaction") try: wt = create_transaction(wlt, args.create_transaction, args) except WalletError as e: clw_exit("Cannot create transaction: %s" % e.msg) wt.sign() print("Transaction created") wt.info() if args.push: wt.send() if wt.pushed: print("Transaction pushed to network. Transaction ID: %s" % wt.txid) else: print("Error creating transaction: %s" % wt.error) else: print( "\nTransaction created but not send yet. Transaction dictionary for export: " ) print_transaction(wt) clw_exit() if args.sweep: if args.fee: clw_exit("Fee option not allowed with --sweep") offline = True print("Sweep wallet. Send all funds to %s" % args.sweep) if args.push: offline = False wt = wlt.sweep(args.sweep, offline=offline, network=args.network, fee_per_kb=args.fee_per_kb) if not wt: clw_exit( "Error occurred when sweeping wallet: %s. Are UTXO's available and updated?" % wt) wt.info() if args.push: if wt.pushed: print("Transaction pushed to network. Transaction ID: %s" % wt.txid) elif not wt: print("Cannot sweep wallet, are UTXO's updated and available?") else: print("Error sweeping wallet: %s" % wt.error) else: print( "\nTransaction created but not send yet. Transaction dictionary for export: " ) print_transaction(wt) clw_exit() # print("Updating wallet") if args.network == 'bitcoinlib_test': wlt.utxos_update() print("Wallet info for %s" % wlt.name) wlt.info()
print("Share this public key below with other cosigner") print("Public key: %s" % public_account.wif_public()) for w in cosigners: if cosigner[0] == w[0]: addkey = hdkey else: addkey = public_account.public() if w[0] not in key_lists: key_lists[w[0]] = [] if addkey not in key_lists[w[0]]: key_lists[w[0]].append(addkey) offline_wallet = Wallet.create(WALLET_NAME, key_lists['Offline PC'], sigs_required=SIGNATURES_REQUIRED, witness_type=WITNESS_TYPE, network=NETWORK) offline_wallet.new_key() print("\n\nA multisig wallet has been created on this system") offline_wallet.info() print("\n---> Please create a wallet on your Online PC like this:") print("from bitcoinlib.wallets import Wallet") print("from bitcoinlib.keys import HDKey") print("") print("key_list = [") for key in key_lists['Online PC']: if key.key_type == 'single': print(" HDKey('%s', key_type='single', witness_type='%s')" %
def create_wallet(self, create_wallet_id): wallet = Wallet.create(create_wallet_id, network=self.networks[0]) for network in self.networks: if network != self.networks[0]: wallet.new_account("%s wallet"%network, network=network) return create_wallet_id
def get_balance(request, network): return Wallet(request.user.wallet_id).balance(network=network)
network=NETWORK) if cosigner['name'] != COSIGNER_NAME_THIS_WALLET: if hdkey.key_type == 'single': hdkey = hdkey.public() else: hdkey = hdkey.public_master_multisig() cosigner['hdkey'] = hdkey key_list.append(hdkey) if len(key_list) != SIGS_N: raise ValueError( "Number of cosigners (%d) is different then expected. SIG_N=%d" % (len(key_list), SIGS_N)) wallet3o5 = Wallet.create(WALLET_NAME, key_list, sigs_required=SIGS_REQUIRED, witness_type=WITNESS_TYPE, network=NETWORK) wallet3o5.new_key() print("\n\nA multisig wallet with 1 key has been created on this system") else: wallet3o5 = Wallet(WALLET_NAME) print("\nUpdating UTXO's...") wallet3o5.utxos_update() wallet3o5.info() utxos = wallet3o5.utxos() wallet3o5.info() # Creating transactions just like in a normal wallet, then send raw transaction to other cosigners. They # can sign the transaction with there on key and pass it on to the next signer or broadcast it to the network.
from pprint import pprint from bitcoinlib.wallets import Wallet, BCL_DATABASE_DIR # # Create Wallets # # First recreate database to avoid already exist errors test_databasefile = os.path.join(BCL_DATABASE_DIR, 'bitcoinlib.test.sqlite') test_database = 'sqlite:///' + test_databasefile if os.path.isfile(test_databasefile): os.remove(test_databasefile) print("\n=== Create a wallet and a simple transaction ===") wlt = Wallet.create('wlttest1', network='bitcoinlib_test', db_uri=test_database) wlt.get_key() wlt.utxos_update() # Create some test UTXOs wlt.info() to_key = wlt.get_key() print("\n- Create transaction (send to own wallet)") t = wlt.send_to(to_key.address, 50000000) t.info() print("\n- Successfully send, updated wallet info:") wlt.info() print("\n=== Create a wallet, generate 6 UTXOs and create a sweep transaction ===") wlt = Wallet.create('wlttest2', network='bitcoinlib_test', db_uri=test_database) wlt.get_keys(number_of_keys=3)
def get_wallet(self): wallet_id = self.user.wallet_id if wallet_exists(wallet_id): return Wallet(wallet_id)
# # Create Wallets # # First recreate database to avoid already exist errors test_databasefile = os.path.join(BCL_DATABASE_DIR, 'bitcoinlib.test.sqlite') test_database = 'sqlite:///' + test_databasefile if os.path.isfile(test_databasefile): os.remove(test_databasefile) print("\n=== Create a simple Mnemonic wallet ===") passphrase = Mnemonic().generate() print("Your private key passphrase is:", passphrase) password = input("Enter password to protect passphrase: ") wlt = Wallet.create('mnwlttest1', keys=passphrase, password=password, network='bitcoinlib_test', db_uri=test_database) wlt.get_key() wlt.utxos_update() # Create some test UTXOs wlt.info() to_key = wlt.get_key() print("\n- Create transaction (send to own wallet)") t = wlt.send_to(to_key.address, 50000000) t.info() print("\n- Successfully send, updated wallet info:") wlt.info()
def create_wallet(wallet_name, args, db_uri): if args.network is None: args.network = DEFAULT_NETWORK print("\nCREATE wallet '%s' (%s network)" % (wallet_name, args.network)) if args.create_multisig: if not isinstance(args.create_multisig, list) or len(args.create_multisig) < 2: clw_exit( "Please enter multisig creation parameter in the following format: " "<number-of-signatures> <number-of-signatures-required> " "<key-0> <key-1> [<key-2> ... <key-n>]") try: sigs_total = int(args.create_multisig[0]) except ValueError: clw_exit( "Number of total signatures (first argument) must be a numeric value. %s" % args.create_multisig[0]) try: sigs_required = int(args.create_multisig[1]) except ValueError: clw_exit( "Number of signatures required (second argument) must be a numeric value. %s" % args.create_multisig[1]) key_list = args.create_multisig[2:] keys_missing = sigs_total - len(key_list) assert (keys_missing >= 0) if keys_missing: print("Not all keys provided, creating %d additional key(s)" % keys_missing) for _ in range(keys_missing): passphrase = get_passphrase(args) passphrase = ' '.join(passphrase) seed = Mnemonic().to_seed(passphrase).hex() key_list.append(HDKey.from_seed(seed, network=args.network)) return Wallet.create(wallet_name, key_list, sigs_required=sigs_required, network=args.network, cosigner_id=args.cosigner_id, db_uri=db_uri, witness_type=args.witness_type) elif args.create_from_key: return Wallet.create(wallet_name, args.create_from_key, network=args.network, db_uri=db_uri, witness_type=args.witness_type) else: passphrase = args.passphrase if passphrase is None: passphrase = get_passphrase(args) elif not passphrase: passphrase = input("Enter Passphrase: ") if not isinstance(passphrase, list): passphrase = passphrase.split(' ') elif len(passphrase) == 1: passphrase = passphrase[0].split(' ') if len(passphrase) < 12: clw_exit("Please specify passphrase with 12 words or more") passphrase = ' '.join(passphrase) seed = Mnemonic().to_seed(passphrase).hex() hdkey = HDKey.from_seed(seed, network=args.network) return Wallet.create(wallet_name, hdkey, network=args.network, witness_type=args.witness_type, db_uri=db_uri)
from bitcoinlib.wallets import Wallet, wallet_delete from bitcoinlib.mnemonic import Mnemonic passphrase = Mnemonic().generate() with open('passphrase.txt', 'w+') as f: f.write(passphrase) wallet = Wallet.create("mWallet1", keys=passphrase, network='bitcoin') key1 = wallet.new_key() print(key1.address)