def create_wallet(self): """ Create a new bitcoin wallet. """ from bitcoinlib.wallets import wallet_exists, HDWallet, WalletError if wallet_exists(self.wallet_name, databasefile=self.db_path): return fail(RuntimeError("Bitcoin wallet with name %s already exists." % self.wallet_name)) self._logger.info("Creating wallet in %s", self.wallet_dir) try: self.wallet = HDWallet.create(self.wallet_name, network=self.network, databasefile=self.db_path) self.wallet.new_key('tribler_payments') self.wallet.new_key('tribler_change', change=1) self.created = True except WalletError as exc: self._logger.error("Cannot create BTC wallet!") return fail(Failure(exc)) return succeed(None)
def test_wallet_import_public_wallet(self): pubkey = 'tpubDDkyPBhSAx8DFYxx5aLjvKH6B6Eq2eDK1YN76x1WeijE8eVUswpibGbv8zJjD6yLDHzVcqWzSp2fWVFhEW9XnBssFqM' \ 'wt9SrsVeBeqfBbR3' pubwal = HDWallet.create( databasefile=DATABASEFILE_UNITTESTS, name='test_wallet_import_public_wallet', key=pubkey, network='testnet', account_id=0) newkey = pubwal.new_key() self.assertEqual(newkey.address, u'mweZrbny4fmpCmQw9hJH7EVfkuWX8te9jc')
def test_wallet_import_account(self): accountkey = 'tprv8h4wEmfC2aSckSCYa68t8MhL7F8p9xAy322B5d6ipzY5ZWGGwksJMoajMCqd73cP4EVRygPQubgJPu9duBzPn3QV' \ '8Y7KbKUnaMzx9nnsSvh' wallet_import = HDWallet.create( databasefile=DATABASEFILE_UNITTESTS, name='test_wallet_import_account', key=accountkey, network='testnet', account_id=99) self.assertEqual(wallet_import.main_key.key_wif, accountkey) self.assertEqual(wallet_import.main_key.address, u'mowRx2TNXTgRSUmepjqhx5C1TTigmHLGRh') self.assertEqual(wallet_import.main_key.path, "m/44'/1'/99'")
def create_wallet(self): """ Create a new bitcoin wallet. """ from bitcoinlib.wallets import HDWallet, WalletError self._logger.info("Creating wallet in %s", self.wallet_dir) try: if self.wallet: raise WalletError("Wallet with name '%s' already created" % self.wallet_name) self.wallet = HDWallet.create(self.wallet_name, network=self.network, databasefile=self.db_path) self.wallet.new_key('tribler_payments') self.wallet.new_key('tribler_change', change=1) self.created = True except WalletError as exc: self._logger.error("Cannot create BTC wallet!") return fail(Failure(exc)) return succeed(None)
def test_wallet_import_account_new_keys(self): accountkey = 'tprv8h4wEmfC2aSckSCYa68t8MhL7F8p9xAy322B5d6ipzY5ZWGGwksJMoajMCqd73cP4EVRygPQubgJPu9duBzPn3QV' \ '8Y7KbKUnaMzx9nnsSvh' wallet_import = HDWallet.create( databasefile=DATABASEFILE_UNITTESTS, name='test_wallet_import_account_new_key', key=accountkey, network='testnet', account_id=99) newkey = wallet_import.new_key(account_id=99) newkey_change = wallet_import.new_key_change(account_id=99, name='change') self.assertEqual(wallet_import.main_key.key_wif, accountkey) self.assertEqual(newkey.address, u'mfvFzusKPZzGBAhS69AWvziRPjamtRhYpZ') self.assertEqual(newkey.path, "m/44'/1'/99'/0/0") self.assertEqual(newkey_change.address, u'mkzpsGwaUU7rYzrDZZVXFne7dXEeo6Zpw2') self.assertEqual(newkey_change.path, "m/44'/1'/99'/1/0")
def test_wallet_litecoin(self): accountkey = 'Ltpv71G8qDifUiNet6mn25D7GPAVLZeaFRWzDABxx5xNeigVpFEviHK1ZggPS1kbtegB3U2i8w6ToNfM5sdvEQPW' \ 'tov4KWyQ5NxWUd3oDWXQb4C' wallet_import = HDWallet.create( databasefile=DATABASEFILE_UNITTESTS, name='test_wallet_litecoin', key=accountkey, network='litecoin') newkey = wallet_import.new_key() self.assertEqual(wallet_import.main_key.key_wif, accountkey) self.assertEqual(newkey.address, u'LPkJcpV1cmT8qLFmUApySBtxt7UWavoQmh') self.assertEqual(newkey.path, "m/44'/2'/0'/0/0")
def get(self, request): print('Started ' + self.__class__.__name__ + ' get method') try: wallet_id = request.GET.get('wallet_id') just_address = request.GET.get('just_address') print( 'Started ', self.__class__.__name__, ' wallet_id=%s, just_address=%s ' % (str(wallet_id), bool(str(just_address)))) if wallet_id: wallet = HDWallet(wallet_id, db_uri=db_uri) keys = wallet.keys(include_private=True) keys = [x.__dict__ for x in keys] address_list = [] if bool(just_address) == True: for key in keys: address_list.append(key['address']) else: for key in keys: address_list.append({ 'address_id': key['address'], 'private_key': key['private'], 'public_key': key['public'] }) return JsonResponse(address_list, safe=False) else: raise ValidationError( get_env_var('exception.validation.address.no_wallet')) except Exception as e: raise e
def get(self, request): print('Started ' + self.__class__.__name__ + ' get method') try: network = request.GET.get('network') wallet_id = request.GET.get('wallet_id') withsum = request.GET.get('withsum') withsum = bool(withsum) print('Started ', self.__class__.__name__, ' wallet_id=%s, withsum=%s, network=%s ' % (str(wallet_id), bool(str(withsum)),network)) address_list = [] if wallet_id and network : wallet = HDWallet(wallet_id, db_uri=db_uri) wallet_address_list = wallet.addresslist() print('Wallet=%s, with unspent value=%s' %(wallet_id,str(wallet.balance()))) address_list = '|'.join([str(a) for a in wallet_address_list]) block_service_url = get_env_var( 'blockchain.service.url') + '/multiaddr?active=' + address_list print('service_url for get balance', block_service_url) resp = requests.get(block_service_url) print('\nreceived for blcokchain multiaddr resp', resp.status_code) address_list = json.loads(resp.text) address_list = self.getunspent(wallet_address_list,address_list,withsum) return JsonResponse(address_list, safe=False) else: raise ValidationError(get_env_var('exception.validation.unspent.no_wallet_or_no_network')) except ServiceException as e: track = traceback.format_exc() print(track) raise ServiceException(e) except Exception as e: track = traceback.format_exc() print(track) raise ServiceException(get_env_var('exception.business.unspent.serviceexception'))
def test_wallet_multisig_sorted_keys(self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) key1 = HDKey() key2 = HDKey() key3 = HDKey() w1 = HDWallet.create_multisig('w1', [ key1, key2.account_multisig_key().public(), key3.account_multisig_key().public() ], sigs_required=2, sort_keys=True, databasefile=DATABASEFILE_UNITTESTS) w2 = HDWallet.create_multisig('w2', [ key1.account_multisig_key().public(), key2, key3.account_multisig_key().public() ], sigs_required=2, sort_keys=True, databasefile=DATABASEFILE_UNITTESTS) w3 = HDWallet.create_multisig('w3', [ key1.account_multisig_key().public(), key2.account_multisig_key().public(), key3 ], sigs_required=2, sort_keys=True, databasefile=DATABASEFILE_UNITTESTS) for _ in range(10): address1 = w1.new_key().address address2 = w2.new_key().address address3 = w3.new_key().address self.assertTrue((address1 == address2 == address3), 'Different addressed generated: %s %s %s' % (address1, address2, address3))
def getNewAddress(account_id,wallet_id): try: wallet = HDWallet(wallet_id, db_uri=db_uri) address = wallet.new_key(account_id=account_id) address = Address(address_id=address.address, network_name=address.network_name) return address except Exception as e: raise ServiceException(get_env_var('exception.business.newaddress.dumpkey.serviceexception'))
def test_wallet_multisig_2of2_different_database(self): """ Same unittest as before (test_wallet_multisig_sign_2_different_wallets) but now with 2 separate databases to check for database inteference. """ if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) if os.path.isfile(DATABASEFILE_UNITTESTS_2): os.remove(DATABASEFILE_UNITTESTS_2) keys = [ HDKey( 'YXscyqNJ5YK411nwB4wzazXjJn9L9iLAR1zEMFcpLipDA25rZregBGgwXmprsvQLeQAsuTvemtbCWR1AHaPv2qmvkartoiFUU6' 'qu1uafT2FETtXT', network='bitcoinlib_test'), HDKey( 'YXscyqNJ5YK411nwB4EyGbNZo9eQSUWb64vAFKHt7E2LYnbmoNz8Gyjs6xc7iYAudcnkgf127NPnaanuUgyRngAiwYBcXKGsSJ' 'wadGhxByT2MnLd', network='bitcoinlib_test') ] msw1 = HDWallet.create_multisig('msw1', [ keys[0], keys[1].subkey_for_path("m/45'/9999999'/0'").wif_public() ], network='bitcoinlib_test', sort_keys=False, sigs_required=2, databasefile=DATABASEFILE_UNITTESTS) msw2 = HDWallet.create_multisig('msw2', [ keys[0].subkey_for_path("m/45'/9999999'/0'").wif_public(), keys[1] ], network='bitcoinlib_test', sort_keys=False, sigs_required=2, databasefile=DATABASEFILE_UNITTESTS_2) msw1.new_key() msw2.new_key() msw1.utxos_update() msw2.utxos_update() utxos = msw1.utxos() output_arr = [('21KnydRNSmqAf8Py74mMiwRXYHGxW27zyDu', utxos[0]['value'] - 50000)] input_arr = [(utxos[0]['tx_hash'], utxos[0]['output_n'], utxos[0]['key_id'], utxos[0]['value'])] t = msw1.transaction_create(output_arr, input_arr, transaction_fee=50000) t = msw1.transaction_sign(t) t2 = msw2.transaction_import(t.raw()) t2 = msw2.transaction_sign(t2) self.assertEqual(msw2.transaction_send(t2), 'succesfull_test_sendrawtransaction')
def create_wallet(wallet_name, args, databasefile): 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 keys" % keys_missing) for _ in range(keys_missing): passphrase = get_passphrase(args) passphrase = ' '.join(passphrase) seed = binascii.hexlify(Mnemonic().to_seed(passphrase)) key_list.append(HDKey().from_seed(seed, network=args.network)) return HDWallet.create_multisig(name=wallet_name, keys=key_list, sigs_required=sigs_required, network=args.network, databasefile=databasefile, sort_keys=True, witness_type=args.witness_type) elif args.create_from_key: return HDWallet.create(name=wallet_name, network=args.network, keys=args.create_from_key, databasefile=databasefile, 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 = binascii.hexlify(Mnemonic().to_seed(passphrase)) hdkey = HDKey().from_seed(seed, network=args.network) return HDWallet.create(name=wallet_name, network=args.network, keys=hdkey, witness_type=args.witness_type, databasefile=databasefile)
def create_wallet(wallet_name, args, databasefile): 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) < 3: clw_exit( "Please enter multisig creation parameter in the following format: " "<number-of-signatures-required> <key-0> <key-1> [<key-2> ... <key-n>]" ) try: sigs_required = int(args.create_multisig[0]) except ValueError: clw_exit( "Number of signatures required (first argument) must be a numeric value. %s" % args.create_multisig[0]) key_list = args.create_multisig[1:] return HDWallet.create_multisig(name=wallet_name, key_list=key_list, sigs_required=sigs_required, network=args.network, databasefile=databasefile) else: passphrase = args.passphrase if passphrase is None: inp_passphrase = Mnemonic('english').generate( args.passphrase_strength) print("\nYour mnemonic private key sentence is: %s" % inp_passphrase) print( "\nPlease write down on paper and backup. With this key you can restore your wallet and all keys" ) passphrase = inp_passphrase.split(' ') inp = input( "\nType 'yes' if you understood and wrote down your key: ") if inp not in ['yes', 'Yes', 'YES']: clw_exit("Exiting...") 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 = binascii.hexlify(Mnemonic().to_seed(passphrase)) hdkey = HDKey().from_seed(seed, network=args.network) return HDWallet.create(name=wallet_name, network=args.network, key=hdkey.wif(), databasefile=databasefile)
def test_wallet_multisig_2of2(self): """ Create 2 cosigner wallets with 1 own private key a public key from other cosigner Then create and sign transaction if first wallet, import and sign it in second wallet and verify created transaction. """ if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) keys = [ HDKey( 'YXscyqNJ5YK411nwB4wzazXjJn9L9iLAR1zEMFcpLipDA25rZregBGgwXmprsvQLeQAsuTvemtbCWR1AHaPv2qmvkartoiFUU6' 'qu1uafT2FETtXT', network='bitcoinlib_test'), HDKey( 'YXscyqNJ5YK411nwB4EyGbNZo9eQSUWb64vAFKHt7E2LYnbmoNz8Gyjs6xc7iYAudcnkgf127NPnaanuUgyRngAiwYBcXKGsSJ' 'wadGhxByT2MnLd', network='bitcoinlib_test') ] msw1 = HDWallet.create_multisig('msw1', [ keys[0], keys[1].subkey_for_path("m/45'/9999999'/0'").wif_public() ], network='bitcoinlib_test', sort_keys=False, sigs_required=2, databasefile=DATABASEFILE_UNITTESTS) msw2 = HDWallet.create_multisig('msw2', [ keys[0].subkey_for_path("m/45'/9999999'/0'").wif_public(), keys[1] ], network='bitcoinlib_test', sort_keys=False, sigs_required=2, databasefile=DATABASEFILE_UNITTESTS) msw1.new_key() msw2.new_key() msw1.utxos_update() msw2.utxos_update() utxos = msw1.utxos() output_arr = [('21KnydRNSmqAf8Py74mMiwRXYHGxW27zyDu', utxos[0]['value'] - 50000)] input_arr = [(utxos[0]['tx_hash'], utxos[0]['output_n'], utxos[0]['key_id'], utxos[0]['value'])] t = msw1.transaction_create(output_arr, input_arr, transaction_fee=50000) t = msw1.transaction_sign(t) t2 = msw2.transaction_import(t.raw()) t2 = msw2.transaction_sign(t2) self.assertTrue(t2.verify())
def __init__(self, wallet_dir): super(BitcoinWallet, self).__init__() self.network = 'testnet' if self.TESTNET else 'bitcoin' self.wallet_dir = wallet_dir self.min_confirmations = 0 self.wallet = None self.unlocked = True self.db_path = os.path.join(wallet_dir, 'wallets.sqlite') self.wallet_name = 'tribler_testnet' if self.TESTNET else 'tribler' if wallet_exists(self.wallet_name, databasefile=self.db_path): self.wallet = HDWallet(self.wallet_name, databasefile=self.db_path) self.created = True
def create_wallet(wallet_name, args, databasefile): 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) < 3: clw_exit( "Please enter multisig creation parameter in the following format: " "<number-of-signatures-required> <key-0> <key-1> [<key-2> ... <key-n>]" ) try: sigs_required = int(args.create_multisig[0]) except ValueError: clw_exit( "Number of signatures required (first argument) must be a numeric value. %s" % args.create_multisig[0]) key_list = args.create_multisig[1:] return HDWallet.create_multisig(name=wallet_name, key_list=key_list, sigs_required=sigs_required, network=args.network, databasefile=databasefile, sort_keys=True) elif args.create_from_key: return HDWallet.create(name=wallet_name, network=args.network, key=args.create_from_key, databasefile=databasefile) 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 = binascii.hexlify(Mnemonic().to_seed(passphrase)) hdkey = HDKey().from_seed(seed, network=args.network) return HDWallet.create(name=wallet_name, network=args.network, key=hdkey.wif(), databasefile=databasefile)
def test_wallet_multisig_bitcoinlib_testnet_transaction_send(self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) key_list = [ 'Pdke4WfXvALPdbrKEfBU9z9BNuRNbv1gRr66BEiZHKcRXDSZQ3gV', 'PhUTR4ZkZu9Xkzn3ee3xMU1TxbNx6ENJvUjX4wBaZDyTCMrn1zuE', 'PdnZFcwpxUSAcFE6MHB78weVAguwzSTUMBqswkqie7Uxfxsd77Zs' ] # Create wallet and generate key wl = HDWallet.create_multisig('multisig_test_simple', key_list, sigs_required=2, network='bitcoinlib_test', databasefile=DATABASEFILE_UNITTESTS) wl.new_key() # Sign, verify and send transaction wl.utxos_update( ) # In bitcoinlib_test network this generates new UTXO's t = wl.transaction_create([('21DBmFUMQMP7A6KeENXgZQ4wJdSCeGc2zFo', 100000)]) t = wl.transaction_sign(t) self.assertTrue(t.verify()) self.assertEqual(wl.transaction_send(t), 'succesfull_test_sendrawtransaction')
def test_wallet_multisig_2of2_with_single_key(self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) keys = [ HDKey(network='bitcoinlib_test'), HDKey(network='bitcoinlib_test', key_type='single') ] key_list = [keys[0], keys[1].public()] wl = HDWallet.create_multisig('multisig_expk2', key_list, sigs_required=2, network='bitcoinlib_test', databasefile=DATABASEFILE_UNITTESTS) wl.new_key() wl.new_key() wl.new_key_change() wl.utxos_update() self.assertEqual(wl.keys()[0].name, 'Multisig Key 8/7') self.assertEqual(wl.keys()[1].name, 'Multisig Key 10/7') self.assertEqual(wl.keys()[2].name, 'Multisig Key 12/7') t = wl.transaction_create( [(HDKey(network='bitcoinlib_test').key.address(), 6400000)], min_confirms=0) t = wl.transaction_sign(t, keys[1]) self.assertEqual(wl.transaction_send(t), 'succesfull_test_sendrawtransaction')
def test_wallet_import_key_network_error(self): w = HDWallet.create(name='Wallet Error', databasefile=DATABASEFILE_UNITTESTS) self.assertRaisesRegexp( WalletError, "Network litecoin not available in this wallet, please create an account " "for this network first.", w.import_key, 'T43gB4F6k1Ly3YWbMuddq13xLb56hevUDP3RthKArr7FPHjQiXpp')
def setUp(self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) self.private_wif = 'xprv9s21ZrQH143K24Mfq5zL5MhWK9hUhhGbd45hLXo2Pq2oqzMMo63oStZzF9ySUHZw5qJkk5LCALAhXS' \ 'XoCmCSnStRvgwLBtcbGsg1PeKT2en' self.wallet = HDWallet.create(key=self.private_wif, name='test_wallet_keys', databasefile=DATABASEFILE_UNITTESTS) self.wallet.new_key() self.wallet.new_key_change()
def test_wallet_multisig_2_wallets_private_master_plus_account_public( self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) pk1 = 'tprv8ZgxMBicQKsPdPVdNSEeAhagkU6tUDhUQi8DcCTmJyNLUyU7svTFzXQdkYqNJDEtQ3S2wAspz3K56CMcmMsZ9eXZ2nkNq' \ 'gVxJhMHq3bGJ1X' pk1_acc_pub = 'tpubDCZUk9HLxh5gdB9eC8FUxPB1AbZtsSnbvyrAAzsC8x3tiYDgbzyxcngU99rG333jegHG5vJhs11AHcSVkbwrU' \ 'bYEsPK8vA7E6yFB9qbsTYi' w1 = self.wallet = HDWallet.create(name='test_wallet_create_1', key=pk1, databasefile=DATABASEFILE_UNITTESTS) w2 = self.wallet = HDWallet.create(name='test_wallet_create_2', key=pk1_acc_pub, databasefile=DATABASEFILE_UNITTESTS) wk1 = w1.new_key() wk2 = w2.new_key() self.assertTrue(wk1.is_private) self.assertFalse(wk2.is_private) self.assertEqual(wk1.address, wk2.address)
def test_wallet_import_public_wallet(self): pubkey = 'tpubDDkyPBhSAx8DFYxx5aLjvKH6B6Eq2eDK1YN76x1WeijE8eVUswpibGbv8zJjD6yLDHzVcqWzSp2fWVFhEW9XnBssFqMwt' \ '9SrsVeBeqfBbR3' pubwal = HDWallet.create(databasefile=DATABASEFILE_UNITTESTS, name='test_wallet_import_public_wallet', key=pubkey, network='testnet', account_id=0) newkey = pubwal.new_key() self.assertEqual(newkey.address, u'mweZrbny4fmpCmQw9hJH7EVfkuWX8te9jc')
def test_wallet_keys_single_key(self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) wk = 'xprv9s21ZrQH143K3tCgu8uhkA2fw9F9opbvoNNzh5wcuEvNHbCU6Kg3c6dam2a6cw4UYeDxAsgBorAqXp2nsoYS84DqYMwkzxZ15' \ 'ujRHzmBMxE' w = HDWallet.create('test_wallet_keys_single_key', wk, scheme='single', databasefile=DATABASEFILE_UNITTESTS) self.assertEqual(w.new_key(), w.new_key())
def test_wallet_import_litecoin(self): accountkey = 'Ltpv71G8qDifUiNet6mn25D7GPAVLZeaFRWzDABxx5xNeigVpFEviHK1ZggPS1kbtegB3U2i8w6ToNfM5sdvEQPW' \ 'tov4KWyQ5NxWUd3oDWXQb4C' wallet_import = HDWallet.create(databasefile=DATABASEFILE_UNITTESTS, name='test_wallet_litecoin', key=accountkey, network='litecoin') newkey = wallet_import.new_key() self.assertEqual(wallet_import.main_key.wif, accountkey) self.assertEqual(newkey.address, u'LPkJcpV1cmT8qLFmUApySBtxt7UWavoQmh') self.assertEqual(newkey.path, "m/44'/2'/0'/0/0")
def _multisig_test(sigs_required, number_of_sigs, sort_keys, network): # Create Keys key_dict = {} for key_id in range(number_of_sigs): key_dict[key_id] = HDKey(network=network) random_output_address = HDKey(network=network).key.address() # Create wallets with 1 private key each wallet_dict = {} wallet_keys = {} for wallet_id in range(number_of_sigs): wallet_name = 'multisig-%d' % wallet_id key_list = [] for key_id in key_dict: if key_id == wallet_id: key_list.append(key_dict[key_id]) else: key_list.append(key_dict[key_id].subkey_for_path( "m/45'/%d'/0'" % Network(network).bip44_cointype).wif_public()) wallet_dict[wallet_id] = HDWallet.create_multisig( wallet_name, key_list, sigs_required=sigs_required, network=network, sort_keys=sort_keys, databasefile=DATABASEFILE_UNITTESTS) wallet_keys[wallet_id] = wallet_dict[wallet_id].new_key() wallet_dict[wallet_id].utxos_update() # Create transaction in one random wallet wallet_ids = [i for i in range(0, number_of_sigs)] shuffle(wallet_ids) transaction_fee = 50000 wallet_id = wallet_ids.pop() wlt = wallet_dict[wallet_id] utxos = wlt.utxos() output_arr = [(random_output_address, utxos[0]['value'] - transaction_fee)] input_arr = [(utxos[0]['tx_hash'], utxos[0]['output_n'], utxos[0]['key_id'], utxos[0]['value'])] t = wlt.transaction_create(output_arr, input_arr, transaction_fee=transaction_fee) t = wlt.transaction_sign(t) n_signs = 1 # Sign transaction with other wallets until required number of signatures is reached while wallet_ids and n_signs < sigs_required: wallet_id = wallet_ids.pop() t = wallet_dict[wallet_id].transaction_import(t.raw()) t = wallet_dict[wallet_id].transaction_sign(t) n_signs += 1 return t
def test_wallet_import(self): keystr = 'tprv8ZgxMBicQKsPeWn8NtYVK5Hagad84UEPEs85EciCzf8xYWocuJovxsoNoxZAgfSrCp2xa6DdhDrzYVE8UXF75r2dKePy' \ 'A7irEvBoe4aAn52' wallet_import = HDWallet.create(databasefile=DATABASEFILE_UNITTESTS, name='test_wallet_import', network='testnet', key=keystr) wallet_import.new_account(account_id=99) self.assertEqual(wallet_import.main_key.wif, keystr) self.assertEqual(wallet_import.main_key.address, u'n3UKaXBRDhTVpkvgRH7eARZFsYE989bHjw') self.assertEqual(wallet_import.main_key.path, 'm')
def test_wallet_import_account(self): accountkey = 'tprv8h4wEmfC2aSckSCYa68t8MhL7F8p9xAy322B5d6ipzY5ZWGGwksJMoajMCqd73cP4EVRygPQubgJPu9duBzPn3QV' \ '8Y7KbKUnaMzx9nnsSvh' wallet_import = HDWallet.create(databasefile=DATABASEFILE_UNITTESTS, name='test_wallet_import_account', key=accountkey, network='testnet', account_id=99) self.assertEqual(wallet_import.main_key.wif, accountkey) self.assertEqual(wallet_import.main_key.address, u'mowRx2TNXTgRSUmepjqhx5C1TTigmHLGRh') self.assertEqual(wallet_import.main_key.path, "m/44'/1'/99'")
def test_wallet_bitcoinlib_testnet_sweep(self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) w = HDWallet.create(network='bitcoinlib_test', name='test_wallet_bitcoinlib_testnet', databasefile=DATABASEFILE_UNITTESTS) w.new_key() w.new_key() w.new_key() w.utxos_update() self.assertEqual(w.sweep('21DBmFUMQMP7A6KeENXgZQ4wJdSCeGc2zFo'), 'succesfull_test_sendrawtransaction')
def test_wallet_bitcoinlib_testnet_sendto_no_funds_txfee(self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) w = HDWallet.create(network='bitcoinlib_test', name='test_wallet_bitcoinlib_testnet', databasefile=DATABASEFILE_UNITTESTS) w.new_key() w.utxos_update() balance = w.balance() self.assertRaisesRegexp( WalletError, 'Not enough unspent transaction outputs found', w.send_to, '21DBmFUMQMP7A6KeENXgZQ4wJdSCeGc2zFo', balance),
def test_wallet_bitcoinlib_testnet_send_utxos_updated(self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) w = HDWallet.create(network='bitcoinlib_test', name='test_wallet_bitcoinlib_testnet', databasefile=DATABASEFILE_UNITTESTS) w.new_key() w.utxos_update() self.assertEqual(len(w.utxos()), 1) w.send_to('21DBmFUMQMP7A6KeENXgZQ4wJdSCeGc2zFo', 50000000) self.assertEqual(w.utxos(), [])
def test_wallet_import(self): keystr = 'tprv8ZgxMBicQKsPeWn8NtYVK5Hagad84UEPEs85EciCzf8xYWocuJovxsoNoxZAgfSrCp2xa6DdhDrzYVE8UXF75r2dKePy' \ 'A7irEvBoe4aAn52' wallet_import = HDWallet.create( databasefile=DATABASEFILE_UNITTESTS, name='test_wallet_import', network='testnet', key=keystr) wallet_import.new_account(account_id=99) self.assertEqual(wallet_import.main_key.key_wif, keystr) self.assertEqual(wallet_import.main_key.address, u'n3UKaXBRDhTVpkvgRH7eARZFsYE989bHjw') self.assertEqual(wallet_import.main_key.path, 'm') wallet_import.info(detail=3)
def __init__(self, wallet_dir, testnet, network, currency): if network not in SUPPORTED_NETWORKS: raise UnsupportedNetwork(network) super(BitcoinlibWallet, self).__init__() self.network = network self.wallet_name = f'tribler_{self.network}' self.testnet = testnet self.unlocked = True self.currency = currency self.wallet_dir = wallet_dir self.min_confirmations = 0 self.wallet = None self.db_path = os.path.join(wallet_dir, 'wallets.sqlite') if wallet_exists(self.wallet_name, db_uri=self.db_path): self.wallet = HDWallet(self.wallet_name, db_uri=self.db_path) self.created = True self.lib_init()
def create_wallet(self): if self.created: return fail(RuntimeError(f"{self.network} wallet with name {self.wallet_name} already exists.")) self._logger.info("Creating wallet in %s", self.wallet_dir) try: self.wallet = HDWallet.create(self.wallet_name, network=self.network, db_uri=self.db_path) self.wallet.new_key('tribler_payments') self.wallet.new_key('tribler_change', change=1) self.created = True except WalletError as exc: self._logger.error("Cannot create %s wallet!", self.network) return fail(exc) return succeed(None)
def create_wallet(self): """ Create a new bitcoin wallet. """ self._logger.info("Creating wallet in %s", self.wallet_dir) try: self.wallet = HDWallet.create(self.wallet_name, network=self.network, databasefile=self.db_path) self.wallet.new_key('tribler_payments') self.wallet.new_key('tribler_change', change=1) self.created = True except WalletError as exc: self._logger.error("Cannot create BTC wallet!") return fail(Failure(exc)) return succeed(None)
def test_wallet_multisig_create_2_cosigner_wallets(self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) pk_wif1 = 'tprv8ZgxMBicQKsPdvHCP6VxtFgowj2k7nBJnuRiVWE4DReDFojkLjyqdT8mtR6XJK9dRBcaa3RwvqiKFjsEQVhKfQmHZCCY' \ 'f4jRTWvJuVuK67n' pk_wif2 = 'tprv8ZgxMBicQKsPdkJVWDkqQQAMVYB2usfVs3VS2tBEsFAzjC84M3TaLMkHyJWjydnJH835KHvksS92ecuwwWFEdLAAccwZ' \ 'KjhcA63NUyvDixB' pk1 = HDKey(pk_wif1, network='testnet') pk2 = HDKey(pk_wif2, network='testnet') wl1 = HDWallet.create_multisig( 'multisig_test_wallet1', [pk_wif1, pk2.subkey_for_path("m/45'/1'/0'").wif_public()], sigs_required=2, network='testnet', databasefile=DATABASEFILE_UNITTESTS) wl2 = HDWallet.create_multisig( 'multisig_test_wallet2', [pk1.subkey_for_path("m/45'/1'/0'").wif_public(), pk_wif2], sigs_required=2, network='testnet', databasefile=DATABASEFILE_UNITTESTS) wl1_key = wl1.new_key() wl2_key = wl2.new_key() self.assertEqual(wl1_key.address, wl2_key.address)
def setUp(self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) self.pk = 'dHHM83S1ptYryy3ZeV6Q8zQBT9NvqiSjUMJPwf6xg2CdaFLiHbyzsCSeP9FG1wzbsPVY9VtC85VsWoFvU9z1S4GzqwDBh' \ 'CawMAogXrUh2KgVahL' self.wallet = HDWallet.create(key=self.pk, name='test_wallet_multicurrency', databasefile=DATABASEFILE_UNITTESTS) self.wallet.new_account(network='litecoin') self.wallet.new_account(network='bitcoin') self.wallet.new_account(network='testnet') self.wallet.new_account(network='dash') self.wallet.new_key() self.wallet.new_key() self.wallet.new_key(network='bitcoin')
def test_wallet_import_account_new_keys(self): accountkey = 'tprv8h4wEmfC2aSckSCYa68t8MhL7F8p9xAy322B5d6ipzY5ZWGGwksJMoajMCqd73cP4EVRygPQubgJPu9duBzPn3QV' \ '8Y7KbKUnaMzx9nnsSvh' wallet_import = HDWallet.create( databasefile=DATABASEFILE_UNITTESTS, name='test_wallet_import_account_new_key', key=accountkey, network='testnet', account_id=99) newkey = wallet_import.new_key(account_id=99) newkey_change = wallet_import.new_key_change(account_id=99, name='change') self.assertEqual(wallet_import.main_key.wif, accountkey) self.assertEqual(newkey.address, u'mfvFzusKPZzGBAhS69AWvziRPjamtRhYpZ') self.assertEqual(newkey.path, "m/44'/1'/99'/0/0") self.assertEqual(newkey_change.address, u'mkzpsGwaUU7rYzrDZZVXFne7dXEeo6Zpw2') self.assertEqual(newkey_change.path, "m/44'/1'/99'/1/0")
class BitcoinWallet(Wallet): """ This class is responsible for handling your wallet of bitcoins. NOTE: all imports of bitcoinlib should be local. The reason for this is that we are patching the bitcoinlib_main method in the __init__ method of the class (since we need access to the Tribler state directory) and we can only import bitcoinlib *after* patching the bitcoinlib main file. """ TESTNET = False def __init__(self, wallet_dir): super(BitcoinWallet, self).__init__() bitcoinlib_main.initialize_lib(wallet_dir) from bitcoinlib.wallets import wallet_exists, HDWallet self.network = 'testnet' if self.TESTNET else 'bitcoin' self.wallet_dir = wallet_dir self.min_confirmations = 0 self.wallet = None self.unlocked = True self.db_path = os.path.join(wallet_dir, 'wallets.sqlite') self.wallet_name = 'tribler_testnet' if self.TESTNET else 'tribler' if wallet_exists(self.wallet_name, databasefile=self.db_path): self.wallet = HDWallet(self.wallet_name, databasefile=self.db_path) self.created = True def get_name(self): return 'Bitcoin' def get_identifier(self): return 'BTC' def create_wallet(self): """ Create a new bitcoin wallet. """ from bitcoinlib.wallets import wallet_exists, HDWallet, WalletError if wallet_exists(self.wallet_name, databasefile=self.db_path): return fail(RuntimeError("Bitcoin wallet with name %s already exists." % self.wallet_name)) self._logger.info("Creating wallet in %s", self.wallet_dir) try: self.wallet = HDWallet.create(self.wallet_name, network=self.network, databasefile=self.db_path) self.wallet.new_key('tribler_payments') self.wallet.new_key('tribler_change', change=1) self.created = True except WalletError as exc: self._logger.error("Cannot create BTC wallet!") return fail(Failure(exc)) return succeed(None) def get_balance(self): """ Return the balance of the wallet. """ if self.created: self.wallet.utxos_update(networks=self.network) return succeed({ "available": self.wallet.balance(network=self.network), "pending": 0, "currency": 'BTC', "precision": self.precision() }) return succeed({"available": 0, "pending": 0, "currency": 'BTC', "precision": self.precision()}) def transfer(self, amount, address): def on_balance(balance): if balance['available'] >= int(amount): self._logger.info("Creating Bitcoin payment with amount %f to address %s", amount, address) tx = self.wallet.send_to(address, int(amount)) return str(tx.hash) else: return fail(InsufficientFunds("Insufficient funds")) return self.get_balance().addCallback(on_balance) def monitor_transaction(self, txid): """ Monitor a given transaction ID. Returns a Deferred that fires when the transaction is present. """ monitor_deferred = Deferred() @inlineCallbacks def monitor_loop(): transactions = yield self.get_transactions() for transaction in transactions: if transaction['id'] == txid: self._logger.debug("Found transaction with id %s", txid) monitor_deferred.callback(None) monitor_lc.stop() self._logger.debug("Start polling for transaction %s", txid) monitor_lc = self.register_task("btc_poll_%s" % txid, LoopingCall(monitor_loop)) monitor_lc.start(5) return monitor_deferred def get_address(self): if not self.created: return '' return self.wallet.keys(name='tribler_payments', is_active=False)[0].address def get_transactions(self): if not self.created: return succeed([]) from bitcoinlib.transactions import Transaction from bitcoinlib.wallets import DbTransaction, DbTransactionInput # Update all transactions self.wallet.transactions_update(network=self.network) txs = self.wallet._session.query(DbTransaction.raw, DbTransaction.confirmations, DbTransaction.date, DbTransaction.fee)\ .filter(DbTransaction.wallet_id == self.wallet.wallet_id)\ .all() transactions = [] for db_result in txs: transaction = Transaction.import_raw(db_result[0], network=self.network) transaction.confirmations = db_result[1] transaction.date = db_result[2] transaction.fee = db_result[3] transactions.append(transaction) # Sort them based on locktime transactions.sort(key=lambda tx: tx.locktime, reverse=True) my_keys = [key.address for key in self.wallet.keys(network=self.network, is_active=False)] transactions_list = [] for transaction in transactions: value = 0 input_addresses = [] output_addresses = [] for tx_input in transaction.inputs: input_addresses.append(tx_input.address) if tx_input.address in my_keys: # At this point, we do not have the value of the input so we should do a database query for it db_res = self.wallet._session.query(DbTransactionInput.value).filter( hexlify(tx_input.prev_hash) == DbTransactionInput.prev_hash, tx_input.output_n_int == DbTransactionInput.output_n).all() if db_res: value -= db_res[0][0] for tx_output in transaction.outputs: output_addresses.append(tx_output.address) if tx_output.address in my_keys: value += tx_output.value transactions_list.append({ 'id': transaction.hash, 'outgoing': value < 0, 'from': ','.join(input_addresses), 'to': ','.join(output_addresses), 'amount': abs(value), 'fee_amount': transaction.fee, 'currency': 'BTC', 'timestamp': time.mktime(transaction.date.timetuple()), 'description': 'Confirmations: %d' % transaction.confirmations }) return succeed(transactions_list) def min_unit(self): return 100000 # The minimum amount of BTC we can transfer in this market is 1 mBTC (100000 Satoshi) def precision(self): return 8
def setUp(self): if os.path.isfile(DATABASEFILE_UNITTESTS): os.remove(DATABASEFILE_UNITTESTS) self.wallet = HDWallet.create( name='test_wallet_create', databasefile=DATABASEFILE_UNITTESTS)
def __init__(self, wallet_dir): super(BitcoinWallet, self).__init__() bitcoinlib_main.initialize_lib(wallet_dir) from bitcoinlib.wallets import wallet_exists, HDWallet self.network = 'testnet' if self.TESTNET else 'bitcoin' self.wallet_dir = wallet_dir self.min_confirmations = 0 self.wallet = None self.unlocked = True self.db_path = os.path.join(wallet_dir, 'wallets.sqlite') self.wallet_name = 'tribler_testnet' if self.TESTNET else 'tribler' if wallet_exists(self.wallet_name, databasefile=self.db_path): self.wallet = HDWallet(self.wallet_name, databasefile=self.db_path) self.created = True