def _test_deserialize(self, child, *vector): self._test_vector( Wallet.deserialize(child.serialize(private=True)), *vector) self._test_vector( Wallet.deserialize(child.serialize(private=False)), *vector, include_private=False)
def test_serialize_public(self): pub = self.wallet.serialize(private=False) w = Wallet.deserialize(pub, network=self.network) self.assertFalse(w.private_key) pub = self.wallet.serialize_b58(private=False) w = Wallet.deserialize(pub, network=self.network) self.assertFalse(w.private_key)
def create(self, id): if TESTNET : child_pubkey = Wallet.deserialize(PUBLIC_KEYCHAIN, BitcoinTestNet).get_child(0).get_child(id) else : child_pubkey = Wallet.deserialize(PUBLIC_KEYCHAIN, BitcoinMainNet).get_child(0).get_child(id) address = child_pubkey.to_address() blocktrailAPI.subscribe_address_event(address) return self(address=address)
def _test_deserialize(self, child, *vector): self._test( Wallet.deserialize( child.serialize(private=True), network=self.network), *vector) self._test( Wallet.deserialize( child.serialize(private=False), network=self.network), *vector, include_private=False)
def test_serialize_private(self): prv = self.wallet.serialize(private=True) w = Wallet.deserialize(prv, network=self.network) self.assertTrue(w.private_key) self.assertEqual(w, self.wallet) prv = self.wallet.serialize_b58(private=True) w = Wallet.deserialize(prv, network=self.network) self.assertTrue(w.private_key) self.assertEqual(w, self.wallet)
def create(self, id): if TESTNET: child_pubkey = Wallet.deserialize( PUBLIC_KEYCHAIN, BitcoinTestNet).get_child(0).get_child(id) else: child_pubkey = Wallet.deserialize( PUBLIC_KEYCHAIN, BitcoinMainNet).get_child(0).get_child(id) address = child_pubkey.to_address() blocktrailAPI.subscribe_address_event(address) return self(address=address)
def __init__(self, private_keychain=None): if private_keychain: if isinstance(private_keychain, HDWallet): self.hdkeychain = private_keychain elif isinstance(private_keychain, (str, unicode)): self.hdkeychain = HDWallet.deserialize(private_keychain) else: raise ValueError('private keychain must be a string') else: self.hdkeychain = HDWallet.new_random_wallet()
async def get_master_wallet(self, private=False): bc_config = self.config['blockcypher'] if bc_config['coin_symbol'] == 'bcy': pubkey = bc_config['testnet_wallet_pubkey'] network = BlockCypherTestNet # todo BitcoinMainNet privkey = bc_config['testnet_private_key'] else: pubkey = bc_config['public_key'] network = BitcoinMainNet privkey = bc_config['private_key'] if not private: master_wallet = Wallet.deserialize(pubkey, network=network) else: master_wallet = Wallet.deserialize(privkey, network=network) return master_wallet
def __init__(self, public_keychain): if isinstance(public_keychain, HDWallet): self.hdkeychain = public_keychain elif isinstance(public_keychain, (str, unicode)): self.hdkeychain = HDWallet.deserialize(public_keychain) else: raise ValueError('public keychain must be a string')
def priv_key(self): if not self.has_private_keys: raise ValueError( 'This Account object does not contain private keys') return Wallet.deserialize(self._priv_key, network=self._network).export_to_wif()
def test_mismatch_public_private(self): w = Wallet.new_random_wallet() self.assertRaises( KeyMismatchError, Wallet, chain_code=b'0' * 64, private_key=self.master_key.private_key, public_key=w.public_key)
def test_invalid_network_prefix(self): key = self.expected_key key = (long_to_hex(BitcoinTestNet.EXT_SECRET_KEY, 8) + self.expected_key[8:]) self.assertRaises(IncompatibleNetworkException, Wallet.deserialize, key, BitcoinMainNet) self.assertTrue(Wallet.deserialize(key, BitcoinTestNet))
def CreateWallet(self, WavesAddress): newWallet = Wallet.new_random_wallet() # private_key_hex = newWallet.get_private_key_hex() # public_key_hex = newWallet.get_public_key_hex() serializedWallet = newWallet.serialize() newAddress = newWallet.to_address() BTCWallet = create_wallet_from_address(wallet_name=WavesAddress, address=newAddress, api_key=self.APIKEY) #TODO SAVE WAVESAddress , serializeWlt in DB print(BTCWallet) con = lite.connect('test.db') with con: cur = con.cursor() cur.execute( "CREATE TABLE IF NOT EXISTS addresses(WavesAddress TEXT , serializedWallet TEXT , BTCaddress TEXT)" ) cur.execute( """INSERT INTO addresses VALUES(?,?,?)""", (WavesAddress, serializedWallet, BTCWallet['addresses'][0])) con.commit() # con.close() return {'addresses': BTCWallet['addresses'][0]}
def address(self): if not self._address: wallet = Wallet.deserialize(self._priv_key or self._pub_key, network=self._network) self._address = wallet.to_address() return self._address
def test_public_export(self): """Export a node as public.""" child = self.master_key.get_child(0, as_private=False) self.assertEqual(child.private_key, None) key = child.serialize(private=False) self.assertTrue( long_to_hex(BitcoinMainNet.EXT_PUBLIC_KEY, 8) in key) self.assertEqual(Wallet.deserialize(key), child)
def test_public_child_restore(self): pub_child = self.wallet.get_child_for_path("M/0") self.assert_public(pub_child) loaded = Wallet.deserialize(pub_child.serialize(False)) self.assertEqual(pub_child, loaded) n1 = pub_child.get_child_for_path("m/1") n2 = loaded.get_child_for_path("m/1") self.assertEqual(n1, n2)
def test_bip32(self): with open("tests/bip32_test_vector.json", "r") as f: vectors = json.loads(f.read()) for wallet_data in vectors: wallet = Wallet.deserialize(wallet_data["private_key"], network=BitcoinMainNet) self._test_wallet(wallet, wallet_data) for child_data in wallet_data["children"]: child = wallet.get_child_for_path(child_data["path"]) self._test_wallet(child, child_data["child"])
def test_bip32(self): with open("tests/bip32_test_vector.json", 'r') as f: vectors = json.loads(f.read()) for wallet_data in vectors: wallet = Wallet.deserialize( wallet_data['private_key'], network=BitcoinMainNet) self._test_wallet(wallet, wallet_data) for child_data in wallet_data['children']: child = wallet.get_child_for_path(child_data['path']) self._test_wallet(child, child_data['child'])
def generate(cls, extra_entropy=None, testnet=False): network = BitcoinMainNet if not testnet else BitcoinTestNet wallet = Wallet.new_random_wallet(extra_entropy, network=network) child_account = wallet.get_child(0, is_prime=True) return cls( pub_key=child_account.serialize_b58(private=False), priv_key=child_account.serialize_b58(private=True), network=network, )
def setUpClass(cls): """ This particular key was found by accident to cause the public deserialized wallet to have a bad public key point! There was a bug that did not properly handle restoring a key from a compressed point that had an odd beta parameter. (see PublicKey.from_hex_key) """ cls.wallet = Wallet.deserialize( u'xprv9s21ZrQH143K319oTMcEt2n2g51StkEnXq23t52ajHM4zFX7cyPqaHShDod' 'cHAqorNQuDW82jUhXJLomy5A8kM36y8HntnosgCvc1szPJ6x')
def setUpClass(cls): cls.expected_key = ensure_bytes( "0488ade4" # BitcoinMainNet version "00" # depth "00000000" # parent fingerprint "00000000" # child_number # chain_code "873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508" "00" # key identifier # private exponent "e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35") cls.master_key = Wallet.deserialize(cls.expected_key)
def verify_and_fill_address_paths_from_bip32key(address_paths, master_key, network): ''' Take address paths and verifies their accuracy client-side. Also fills in all the available metadata (WIF, public key, etc) ''' assert network, network wallet_obj = Wallet.deserialize(master_key, network=network) address_paths_cleaned = [] for address_path in address_paths: path = address_path['path'] input_address = address_path['address'] child_wallet = wallet_obj.get_child_for_path(path) if child_wallet.to_address() != input_address: err_msg = 'Client Side Verification Fail for %s on %s:\n%s != %s' % ( path, master_key, child_wallet.to_address(), input_address, ) raise Exception(err_msg) pubkeyhex = child_wallet.get_public_key_hex(compressed=True) server_pubkeyhex = address_path.get('public') if server_pubkeyhex and server_pubkeyhex != pubkeyhex: err_msg = 'Client Side Verification Fail for %s on %s:\n%s != %s' % ( path, master_key, pubkeyhex, server_pubkeyhex, ) raise Exception(err_msg) address_path_cleaned = { 'pub_address': input_address, 'path': path, 'pubkeyhex': pubkeyhex, } if child_wallet.private_key: privkeyhex = child_wallet.get_private_key_hex() address_path_cleaned['wif'] = child_wallet.export_to_wif() address_path_cleaned['privkeyhex'] = privkeyhex address_paths_cleaned.append(address_path_cleaned) return address_paths_cleaned
def do_master_and_child_keys_match(public_keychain, child_public_key, chain_path): public_child = Wallet.deserialize(public_keychain) chain_step_bytes = 4 max_bits_per_step = 2**31 chain_steps = [ int(chain_path[i:i+chain_step_bytes*2], 16) % max_bits_per_step for i in range(0, len(chain_path), chain_step_bytes*2) ] for step in chain_steps: public_child = public_child.get_child(step) public_child_hex = public_child.get_public_key_hex(compressed=True) if public_child_hex == child_public_key: return True return False
def test_file(): for filename, network in [("tests/bip32_test_vector.json", BitcoinMainNet), ("tests/bip32_blockcypher_test_vector.json", BlockCypherTestNet)]: with open(filename, 'r') as f: vectors = json.loads(f.read()) for wallet_data in vectors: wallet = Wallet.deserialize(wallet_data['private_key'], network=network) # use yield for nose test generation yield _test_wallet, wallet, wallet_data for child_data in wallet_data['children']: child = wallet.get_child_for_path(child_data['path']) yield _test_wallet, child, child_data['child']
def __init__(self, item_index, address, adress_salt, item_amount, order_price): database = app.db.Database() from bitmerchant.wallet import Wallet if configuration.Configuration.btc_net == "Test": from bitmerchant.network import BitcoinTestNet wallet = Wallet.from_master_secret( configuration.Configuration.btc_master_key, network=BitcoinTestNet) else: from bitmerchant.network import BitcoinMainNet wallet = Wallet.from_master_secret( configuration.Configuration.btc_master_key, network=BitcoinMainNet) self.order_index = database.make_order(item_index, address, adress_salt, item_amount, order_price) child_wallet = wallet.get_child(self.order_index, is_prime=False) self.wif_key = child_wallet.export_to_wif() self.btc_address = child_wallet.to_address() self.private_key = child_wallet.get_private_key_hex() database.update_order(self.order_index, self.wif_key, self.btc_address, self.private_key)
def SettleTransaction(self,WavesAddress): #check transaction WavesAddress and WAVES : attchment BTCaddress and verify assetID # trnc = ModuleHandler.wrapper("/transactions/address/" + WavesAddress + "/limit/1") pywaves.setNode(node = pywaves.getNode() , chain = self.CHAIN) print("getNode(): ",pywaves.getNode()) trnc = pywaves.wrapper("/transactions/address/" + WavesAddress + "/limit/1" , host = self.TESTNET_NODE ) print('trnc',trnc) BTCaddress = trnc[0][0]['attachment'] if BTCaddress == '' : return {"result" : "there is not any transaction!" } assetDetail = ModuleHandler.wrapper("/assets/details/" + trnc[0][0]['assetId'] , host = self.TESTNET_NODE) print('assetDetail : ',assetDetail) decimals = assetDetail['decimals'] con = lite.connect('test.db') with con: cur = con.cursor() # cur.execute("SELECT MIN(cnt) FROM (SELECT COUNT(*) cnt FROM voting GROUP BY candidate) t;") # minimumMigdar = cur.fetchone() cur.execute("""SELECT * FROM addresses ORDER BY Inventory DESC """) #TODO change query for get min count con.commit() rows = cur.fetchall() cnt = 0 remind = amount*(10**((-1)*decimals)) #### Decimals Decimals Decimals while remind > 0: serializedWallet = rows[cnt][1] #ref to DB structure wallet = Wallet.deserialize(serializedWallet , network=BitcoinTestNet) inv = rows[cnt][3] if inv >= remind : blockcypher.simple_spend(from_privkey=ModuleHandler.encode( wallet.get_private_key_hex() ) , to_address = BTCaddress , to_satoshis = remind) cur.execute(""" UPDATE addresses SET Inventory = ? WHERE WavesAddress = ? """, ( inv - remind , WavesAddress )) else : blockcypher.simple_spend(from_privkey=ModuleHandler.encode( wallet.get_private_key_hex() ) , to_address = BTCaddress , to_satoshis = inv) remind = remind - inv cur.execute(""" UPDATE addresses SET Inventory = ? WHERE WavesAddress = ? """, ( 0 , WavesAddress )) con.commit() return res
def do_master_and_child_keys_match(public_keychain, child_public_key, chain_path): public_child = Wallet.deserialize(public_keychain) chain_step_bytes = 4 max_bits_per_step = 2**31 chain_steps = [ int(chain_path[i:i + chain_step_bytes * 2], 16) % max_bits_per_step for i in range(0, len(chain_path), chain_step_bytes * 2) ] for step in chain_steps: public_child = public_child.get_child(step) public_child_hex = public_child.get_public_key_hex(compressed=True) if public_child_hex == child_public_key: return True return False
def get_payment_adress_for_user(user): user_id = user.id # assert isinstance(user_id, (int,long)) wallet = Wallet.deserialize(settings.WALLET_PRIVKEY, network=BlockCypherTestNet) wallet_for_user = wallet.get_child(user.id, is_prime=True) my_wallet = { 'address': wallet_for_user.to_address(), 'priv': get_encripted_priv(wallet_for_user), # 'reg_priv': wallet_for_user.serialize_b58(private=True) 'reg_priv': wallet_for_user.get_private_key_hex().decode('UTF-8') } return my_wallet
def test_from_master_secret_slow(self): """Verified against bip32.org""" password = "******" w = Wallet.from_master_secret_slow(password) self.assertEqual( w.serialize_b58(private=True), "xprv9s21ZrQH143K3JDqHk5kEb6o2w8pEwm3cmt8qaSw9coaHCYJFtaybzUob6d4" "WyJDf8uspZkBAt7DcEVhvCDRBHZEavVJg51HZEGdVH2uXLK") self.assertEqual(w.depth, 0) self.assertEqual(w.parent_fingerprint, b"0x00000000") self.assertEqual(w.child_number, 0) self.assertEqual( w.chain_code, (b'7c73c15c623128246dcf37d439be2a9d' b'da5fb33b2aec18e66a806d10a236b5c9')) self.assertEqual( w.export_to_wif(), 'KxTFZmNVYgAupo2w8QUNpfDjSEMhGN7RaQ6rhNRvsSHBggASpEr1') child = w.get_child(0, is_prime=False) self.assertEqual( child.serialize_b58(private=True), "xprv9vExvbix4MQgazj3vovZ4UEwmLSEQrktY8yZAVhFAB7W7xzqS9RXH8ZaNEdw" "KoQzbPixY3YSVjK58S3K5h4ktjVEpHrfjUarsiUfKDe6A4i") self.assertEqual( child.export_to_wif(), 'L3LA3KxJELbwCyVjFaSrvvUsnfKcZ9TPmGXbq4s6zmK5kaBVja29') self.assertEqual( child.serialize_b58(private=False), "xpub69EKL7FqtixyoUoX2qTZRcBgKNGipKUjuMu9xt6riWeUzmKyygjmpvt4DXaL" "U2vyoVqYtpqyuDYDHsxbzzReQmou1PtwVthP3SJkjcHEEg4") self.assertEqual( child.get_public_key_hex(), (b"03b18ba94530690859a3f6ebb2b866d1" b"51f8499b3164d027ba5b464e4ed71329aa")) self.assertEqual( child.to_address(), "1MfJvR28iULUb8AwtY7hp7xpc1A8Wg1ojX")
def test_random_wallet(self): w = Wallet.new_random_wallet() self.assertTrue(Wallet.deserialize(w.serialize()), w) self.assertEqual(w.depth, 0) self.assertEqual(w.parent_fingerprint, b'0x' + long_to_hex(0, 8)) self.assertEqual(w.child_number, 0)
def cli(): parser = argparse.ArgumentParser( description='''Simple BIP32 HD cryptocurrecy command line wallet, with several unique features. ''' + ' '.join([x[1] for x in EXPLAINER_COPY])) parser.add_argument('-w', '--wallet', dest='wallet', default='', help='Master private or public key (starts with xprv and xpub for BTC). Can also be UNIX piped in (-w/--w not needed).', ) parser.add_argument("-v", "--verbose", dest='verbose', default=False, action='store_true', help="Show detailed logging info", ) parser.add_argument('-b', '--bc-api-key', dest='bc_api_key', # For all bcwallet users: default='9c339f92713518492a4504c273d1d9f9', help='BlockCypher API Key to use. If not supplied the default will be used.', ) parser.add_argument('-u', '--units', dest='units', default='bit', choices=UNIT_CHOICES, help='Units to represent the currency in user display.', ) parser.add_argument('--version', dest='version', default=False, action='store_true', help="Show version and quit", ) args = parser.parse_args() if args.verbose: global VERBOSE_MODE VERBOSE_MODE = True verbose_print('args: %s' % args) global UNIT_CHOICE UNIT_CHOICE = args.units if args.version: import pkg_resources puts(colored.green(str(pkg_resources.get_distribution("bcwallet")))) sys.exit() if sys.stdin.isatty(): wallet = args.wallet verbose_print('Wallet imported from args') else: wallet = sys.stdin.readline().strip() sys.stdin = open('/dev/tty') verbose_print('Wallet imported from pipe') verbose_print('wallet %s' % wallet) if args.bc_api_key: global BLOCKCYPHER_API_KEY BLOCKCYPHER_API_KEY = args.bc_api_key verbose_print('API Key: %s' % BLOCKCYPHER_API_KEY) # Crude check if set(BLOCKCYPHER_API_KEY) - set('0123456789abcdef'): puts(colored.red('Invalid API Key: %s' % BLOCKCYPHER_API_KEY)) sys.exit() # Check if blockcypher is up (basically if the user's machine is online) global USER_ONLINE if is_connected_to_blockcypher(): USER_ONLINE = True puts("\nWelcome to bcwallet!") puts("\nHere's what makes bcwallet unique:") with indent(2): for bullet_point, description in EXPLAINER_COPY: puts('-%s: %s' % (bullet_point, description)) puts() if wallet: network = guess_network_from_mkey(wallet) if network: # check if valid mkey try: wallet_obj = Wallet.deserialize(wallet, network=network) mpub = wallet_obj.serialize_b58(private=False) if wallet_obj.private_key is None: # input was mpub if mpub != wallet: # safety check puts(colored.red("Invalid entry: %s" % wallet)) except IndexError: puts(colored.red("Invalid entry: %s" % wallet)) # Run the program: return wallet_home(wallet_obj) else: puts(colored.red("Invalid wallet entry: %s" % wallet)) else: puts("You've opened your HD wallet without specifying a master public or master private key, which you can do like this:\n") print_bcwallet_basic_priv_opening(priv_to_display='xpriv123...') puts("Let's generate a new master private key (locally) for you to use.\n") puts('Which currency do you want to create a wallet for?') coin_symbol = coin_symbol_chooser(user_prompt=DEFAULT_PROMPT) verbose_print(coin_symbol) if not coin_symbol: puts('Quitting without generating a new wallet!') sys.exit() network = COIN_SYMBOL_TO_BMERCHANT_NETWORK[coin_symbol] puts("\nLet's add some extra entropy in case you're on a fresh boot of a virtual machine, or your random number generator has been compromised by an unnamed three letter agency.") puts("Please bang on the keyboard for as long as you like and then hit enter.") puts("There's no reason to record this value, it cannot be used to recover your keys.") extra_entropy = get_user_entropy(user_prompt='฿ (optional)') verbose_print(extra_entropy) # worst-case assumption (attacker knows keyspace and length) entropy_space = len(extra_entropy) ** len(set(extra_entropy)) bits_entropy = len(bin(entropy_space)) - 2 verbose_print('bits of extra_entropy: %s' % bits_entropy) user_wallet_obj = Wallet.new_random_wallet(network=network, user_entropy=extra_entropy) mpriv = user_wallet_obj.serialize_b58(private=True) mpub = user_wallet_obj.serialize_b58(private=False) puts(colored.green('\nYour master PRIVATE key is: %s (guard this CAREFULLY as it can be used to steal your funds)' % mpriv)) puts(colored.green('Your master PUBLIC key is: %s\n' % mpub)) puts('bcwallet will now quit. Open your new wallet anytime like this:\n') print_bcwallet_basic_priv_opening(priv_to_display=mpriv) puts(BCWALLET_PRIVPIPE_EXPLANATION) print_bcwallet_piped_priv_opening(priv_to_display=mpriv) sys.exit()
def setUp(self): self.w = Wallet.new_random_wallet()
def cli(): parser = argparse.ArgumentParser( description='''Simple BIP32 HD cryptocurrecy command line wallet, with several unique features. ''' + ' '.join([x[1] for x in EXPLAINER_COPY])) parser.add_argument('-w', '--wallet', dest='wallet', default='', help='Master private or public key (starts with xprv and xpub for BTC). Can also be UNIX piped in (-w/--w not needed).', ) parser.add_argument("-v", "--verbose", dest='verbose', default=False, action='store_true', help="Show detailed logging info", ) parser.add_argument('-b', '--bc-api-key', dest='bc_api_key', # For all bcwallet users: default='9c339f92713518492a4504c273d1d9f9', help='BlockCypher API Key to use. If not supplied the default will be used.', ) parser.add_argument('-u', '--units', dest='units', default='bit', choices=UNIT_CHOICES, help='Units to represent the currency in user display.', ) parser.add_argument('--version', dest='version', default=False, action='store_true', help="Show version and quit", ) args = parser.parse_args() if args.verbose: global VERBOSE_MODE VERBOSE_MODE = True verbose_print('args: %s' % args) global UNIT_CHOICE UNIT_CHOICE = args.units if args.version: import pkg_resources puts(colored.green(str(pkg_resources.get_distribution("bcwallet")))) puts() sys.exit() if sys.stdin.isatty(): wallet = args.wallet verbose_print('Wallet imported from args') else: wallet = sys.stdin.readline().strip() sys.stdin = open('/dev/tty') verbose_print('Wallet imported from pipe') verbose_print('wallet %s' % wallet) if args.bc_api_key: global BLOCKCYPHER_API_KEY BLOCKCYPHER_API_KEY = args.bc_api_key verbose_print('API Key: %s' % BLOCKCYPHER_API_KEY) # Crude check if set(BLOCKCYPHER_API_KEY) - set('0123456789abcdef'): puts(colored.red('Invalid API Key: %s\n' % BLOCKCYPHER_API_KEY)) sys.exit() # Check if blockcypher is up (basically if the user's machine is online) global USER_ONLINE if is_connected_to_blockcypher(): USER_ONLINE = True puts("\nWelcome to bcwallet!") puts("\nHere's what makes bcwallet unique:") with indent(2): for bullet_point, description in EXPLAINER_COPY: puts('-%s: %s' % (bullet_point, description)) puts() if wallet: network = guess_network_from_mkey(wallet) if network: # check if valid mkey try: wallet_obj = Wallet.deserialize(wallet, network=network) mpub = wallet_obj.serialize_b58(private=False) if wallet_obj.private_key is None: # input was mpub if mpub != wallet: # safety check puts(colored.red("Invalid entry: %s" % wallet)) except IndexError: puts(colored.red("Invalid entry: %s" % wallet)) # Run the program: return wallet_home(wallet_obj) else: puts(colored.red("Invalid wallet entry: %s" % wallet)) else: puts("You've opened your HD wallet without specifying a master public or master private key, which you can do like this:\n") print_bcwallet_basic_priv_opening(priv_to_display='xpriv123...') puts("Let's generate a new master private key (locally) for you to use.\n") puts('Which currency do you want to create a wallet for?') coin_symbol = coin_symbol_chooser(user_prompt=DEFAULT_PROMPT) verbose_print(coin_symbol) if not coin_symbol: puts('\nQuitting without generating a new wallet!\n') sys.exit() network = COIN_SYMBOL_TO_BMERCHANT_NETWORK[coin_symbol] puts("\nLet's add some extra entropy in case you're on a fresh boot of a virtual machine, or your random number generator has been compromised by an unnamed three letter agency.") puts("Please bang on the keyboard for as long as you like and then hit enter.") puts("There's no reason to record this value, it cannot be used to recover your keys.") extra_entropy = get_user_entropy(user_prompt='฿ (optional)') verbose_print(extra_entropy) # worst-case assumption (attacker knows keyspace and length) entropy_space = len(extra_entropy) ** len(set(extra_entropy)) bits_entropy = len(bin(entropy_space)) - 2 verbose_print('bits of extra_entropy: %s' % bits_entropy) user_wallet_obj = Wallet.new_random_wallet(network=network, user_entropy=extra_entropy) mpriv = user_wallet_obj.serialize_b58(private=True) mpub = user_wallet_obj.serialize_b58(private=False) puts(colored.green('\nYour master PRIVATE key is: %s (guard this CAREFULLY as it can be used to steal your funds)' % mpriv)) puts(colored.green('Your master PUBLIC key is: %s\n' % mpub)) puts('bcwallet will now quit. Open your new wallet anytime like this:\n') print_bcwallet_basic_priv_opening(priv_to_display=mpriv) puts(BCWALLET_PRIVPIPE_EXPLANATION) print_bcwallet_piped_priv_opening(priv_to_display=mpriv) puts(BCWALLET_PRIVPIPE_CAT_EXPLANATION) print_bcwallet_piped_priv_cat_opening() puts(BCWALLET_PIPE_ENCRYPTION_EXPLANATION) print_keys_not_saved() sys.exit()
def recover(): shards = [] user_index = _get_input( "Enter the index of the user who's key should be regenerated: ", input_type=int) - 1 number_of_accounts = _get_input( 'Enter number of accounts to be created per user [1]: ', input_type=int, default=1) _print(term.clear) key_progress = 0 finished = False while not finished: _print(term.clear) if key_progress == 0: _print( 'Starting on the next screen, each user will be asked to input their piece of the master key.' ) else: _print('The next screen is for the next user.') _get_input('Press enter to continue') _print(term.clear) _print('Attempting to recover keys for user {}'.format(user_index + 1)) _print('Key progress: {}'.format(key_progress)) _print() piece = decrypt_shard() threshold, shard = piece.split('-', 1) shards.append(shard) threshold = int(threshold) if key_progress == 0: initial_threshold = threshold else: if initial_threshold != threshold: raise ValueError( 'Shard thresholds do not match. An invalid shard has been provided.' ) _print() _print('Shard has been accepted', formatters=term.blue) _get_input('Press enter to continue') key_progress += 1 if key_progress == threshold: finished = True _print('The next screen is meant for user {}'.format(user_index + 1), formatters=term.clear) _get_input('Press enter to continue') master_key = BitcoinToB58SecretSharer.recover_secret(shards) master_wallet = Wallet.deserialize(master_key) user_share = BitcoinToB58SecretSharer.recover_share(shards, user_index + 1) data = { 'child': 'user {}'.format(user_index + 1), 'master_shard': '{}-{}'.format(threshold, user_share), } _generateKeys(master_wallet, user_index, number_of_accounts, extra_data=data)
def generate(number_of_users=None, number_of_accounts=None, key_threshold=None, extra_entropy=None): _print(term.clear) if number_of_users is None: number_of_users = _get_input( 'Enter number of users participating [1]: ', input_type=int, default=1) if number_of_users > 1 and not key_threshold: key_threshold = _get_input('Enter key threshold [2]: ', input_type=int, default=2) if number_of_accounts is None: number_of_accounts = _get_input( 'Enter number of accounts to be created per user [1]: ', input_type=int, default=1) if not extra_entropy: extra_entropy = _get_input('Enter additional entropy [None]: ') _validate_generate_values(number_of_users, number_of_accounts, key_threshold, extra_entropy) _print( 'The system will now attempt to generate a master key and split it amongst the users\n' 'This process may take awhile...') master_wallet = Wallet.new_random_wallet(extra_entropy) serialized_wallet = master_wallet.serialize_b58() if number_of_users > 1: shares = BitcoinToB58SecretSharer.split_secret( serialized_wallet.encode(), key_threshold, number_of_users) else: shares = None for user_index in range(number_of_users): _print(('The following screen is meant for user {index} (of {total})\n' 'Do not press continue if you are not user {index}').format( index=user_index + 1, total=number_of_users), formatters=[term.clear, term.red]) _get_input('Press enter to continue when ready') _print(term.clear) if number_of_users > 1: data = { 'child': '{index} of {total}'.format(index=user_index + 1, total=number_of_users), 'master_shard': '{}-{}'.format(key_threshold, shares[user_index]), } else: data = {} _generateKeys(master_wallet, user_index, number_of_accounts, extra_data=data) _print('All done')
def CreateWallet(self,WavesAddress): con = lite.connect('test.db') with con: cur = con.cursor() cur.execute("""SELECT id FROM addressid WHERE WavesAddress=:adr""", {"adr": WavesAddress}) row = cur.fetchone() if len(row)>0 : BTCWallet = get_wallet_addresses(wallet_name='Noay'+ str(row[0]), api_key=self.APIKEY, coin_symbol=self.coin_symbol) cur.execute("""SELECT * FROM addresses WHERE WavesAddress=:adr""", {"adr": WavesAddress}) row = cur.fetchone() wallet = Wallet.deserialize(row[1] , network=BitcoinTestNet) ModuleHandler.encode(wallet.get_public_key_hex()) con.commit() return { 'addresses' : BTCWallet['addresses'][0] , 'public_key' : ModuleHandler.encode( wallet.get_public_key_hex() ) } con.commit() newWallet = Wallet.new_random_wallet(network=BitcoinTestNet) # private_key_hex = newWallet.get_private_key_hex() # public_key_hex = newWallet.get_public_key_hex() serializedWallet = newWallet.serialize() newAddress = newWallet.to_address() # print('newAddress : ',newAddress) con = lite.connect('test.db') with con: cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS addressid(id INTEGER PRIMARY KEY AUTOINCREMENT, WavesAddress TEXT NOT NULL )") cur.execute("""INSERT INTO addressid (WavesAddress) VALUES(?)""",(WavesAddress,)) cur.execute("""SELECT id FROM addressid WHERE WavesAddress=:adr""", {"adr": WavesAddress}) con.commit() row = cur.fetchone() # print("row[0] : ",row[0]) #TODO handle {'error': 'Error: wallet exists'} BTCWallet = get_wallet_addresses(wallet_name='Noay'+ str(row[0]), api_key=self.APIKEY, coin_symbol=self.coin_symbol) try: s = BTCWallet['error'] print('BTCWallet' , 0) BTCWallet = create_wallet_from_address(wallet_name= 'Noay'+ str(row[0]), address=newAddress, api_key=self.APIKEY , coin_symbol=self.coin_symbol) #TODO SAVE WAVESAddress , serializeWlt in DB except Exception as e: con = lite.connect('test.db') print('BTCWallet' , 1) with con: cur = con.cursor() cur.execute("CREATE TABLE IF NOT EXISTS addresses(WavesAddress TEXT , serializedWallet TEXT , BTCaddress TEXT , Inventory REAL)") cur.execute("""INSERT INTO addresses VALUES(?,?,?,0)""",(WavesAddress,serializedWallet,BTCWallet['addresses'][0])) con.commit() # con.close() # print('BTCWallet' , BTCWallet) return { 'addresses' : BTCWallet['addresses'][0] , 'public_key' : ModuleHandler.encode( newWallet.get_public_key_hex() ) } # public key btc
def setUpClass(cls): cls.master_key = Wallet.deserialize( 'dgpv51eADS3spNJh8qd8KgFeT3V2QZBDSkYUqbaKDwZpDN4jd3uLcR7i6CruVDsb' 'acyx3NL2puToxM9MQYhZSsD8tBkXeQkm5btsKxpZawwPQND', cls.network )
from bitmerchant.wallet import Wallet from mnemonic import Mnemonic # put in whatever Trezor generates for you here (or backup from this empty/insecure one as a test) mnemonic = 'clean health food open blood network differ female lion eagle rough upon update zone antique defense venture uncover mobile charge actress film vocal enough' passphrase = '' # empty string or whatever you actually choose path = "m/44'/0'/0'/0/0" # whatever shows up on the UI for that account (everything will start with m/44'/0' since it's bip44) child = Wallet.from_master_secret( Mnemonic('english').to_seed(mnemonic, passphrase)).get_child_for_path(path) child.to_address( ) # '18K9axbPpwqZgngB58nuwsYevL2z6ey4YG' (confirm this matches what Trezor is showing you) child.export_to_wif( ) # 'L4orhKxb9YSGRHZvv8th3KeUqRz6x3PPmdqLThajUgSesTovfKPG' (what you can use to spend the funds for the previous address)
def setUpClass(cls): cls.master_key = Wallet.from_master_secret(binascii.unhexlify( 'fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a2' '9f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542' ))
def create(self, id): child_pubkey = Wallet.deserialize(PUBLIC_KEYCHAIN_TESTNET, BitcoinTestNet).get_child(id) address = child_pubkey.to_address() return self(address=address)
def from_seed(cls, seed): return cls(Wallet.from_master_secret(seed))
def sign(tosign, priv_key): proc = subprocess.run("~/go/bin/signer " + str(tosign) + " " + str(priv_key), shell=True, stdout=PIPE, stderr=PIPE, text=True) signature = proc.stdout return signature """ config """ fee = int(os.environ.get('FEE')) output_address = os.environ.get('OUTPUT_ADDRESS') token = os.environ.get('BC_TOKEN') master = Wallet.from_master_secret(seed=os.environ.get('SEED')) crypto_url = os.environ.get('CRYPTO_URL') """ ======= """ print(fee) print(output_address) print(token) print(master.get_child(1, is_prime=False)) baseurl = 'https://api.blockcypher.com/v1/btc/main/' childs = requests.get(crypto_url).json() wallet_base = master.get_child(0, is_prime=True) total_amount = 0 request_json = {
def setUpClass(cls): cls.master_key = Wallet.deserialize( 'Ltpv71G8qDifUiNetGsQje8NP1KYECbgKwSP2kugo4qN9GPfJ1KB8XMXxqBTYsA5' 'PgwQaFV9u5PhKxosbjcnKKCPpPvaYVSUz24KMctXYig39Te', cls.network )
def pub_key(self): if not self._pub_key: wallet = Wallet.deserialize(self._priv_key, network=self._network) self._pub_key = wallet.serialize_b58(private=False) return self._pub_key
def setUpClass(cls): cls.wallet = Wallet.new_random_wallet(network=cls.network)
def setUp(self): self.w = Wallet.new_random_wallet() self.pub_derived_private_child = self.w.get_child(100) self.wpub = self.w.public_copy() self.assertTrue(self.wpub.private_key is None)
def test_deserialize_byte_array(self): key = binascii.unhexlify(self.wallet.serialize()) w = Wallet.deserialize(key, network=self.network) self.assertEqual(w, self.wallet)
def test_from_master_secret(self): secret = binascii.unhexlify(b'000102030405060708090a0b0c0d0e0f') self.assertEqual(Wallet.from_master_secret(secret), self.master_key)
def setUpClass(cls): cls.master_key = Wallet.from_master_secret( binascii.unhexlify('000102030405060708090a0b0c0d0e0f'))