def on_master_key_button_clicked(self, widget, data=None): if self.settingsStore is not None: checkIfSure = gtk.MessageDialog( self.settingsWindow, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, "Choosing a new masterkey will result in complete loss of any keys associated with your old key. Are you sure you wish to do this?" ) if (checkIfSure.run() == gtk.RESPONSE_NO): checkIfSure.destroy() return True else: checkIfSure.destroy() seed = os.urandom(32) masterKey = bitcoin.bip32_master_key(seed) confirm = gtk.MessageDialog( self.settingsWindow, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Your new key is: ") confirm.format_secondary_markup(masterKey) confirm.run() confirm.destroy() self.settingsStore['bip32master'] = masterKey self.settingsStore['accountNumber'] = 1 self.settingsStore['accounts'] = dict() self.settingsWindow.backup_button.set_sensitive(True) self.update_widget_values()
def _generate_new_keypair(self): seed = str(random.randrange(2**256)) # Deprecated (pre-BIP32) # self.secret = hashlib.sha256(secret).hexdigest() # self.pubkey = privkey_to_pubkey(self.secret) # self.log.debug('Keys %s %s', self.secret, self.pubkey) # Move to BIP32 keys m/0/0/0 wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(seed), 0) wallet_chain = bitcoin.bip32_ckd(wallet, 0) bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, 0) identity_priv = bitcoin.bip32_extract_key(bip32_identity_priv) bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv) identity_pub = bitcoin.encode_pubkey( bitcoin.bip32_extract_key(bip32_identity_pub), 'hex') self.pubkey = identity_pub self.secret = identity_priv new_settings = { "secret": self.secret, "pubkey": self.pubkey, "bip32_seed": seed } self.db_connection.update_entries("settings", new_settings, {"market_id": self.market_id}) self.settings.update(new_settings)
def create_keychain(self): """ The guid generation can take a while. While it's doing that we will open a port to allow a UI to connect and listen for generation to complete. """ print "Generating GUID, this may take a few minutes..." d = Deferred() api = GUIDGenerationListener(d) site = Site(api, timeout=None) connector = reactor.listenTCP(18470, site, interface="127.0.0.1") start = time.time() g = GUID() d.callback((round(time.time() - start, 2), connector)) self.guid = g.guid self.guid_privkey = g.privkey self.signing_key = nacl.signing.SigningKey(self.guid_privkey) self.guid_signed_pubkey = g.signed_pubkey self.db.set_key("guid", self.guid_privkey, self.guid_signed_pubkey) self.bitcoin_master_privkey = bitcoin.bip32_master_key( bitcoin.sha256(self.guid_privkey)) self.bitcoin_master_pubkey = bitcoin.bip32_privtopub( self.bitcoin_master_privkey) self.db.set_key("bitcoin", self.bitcoin_master_privkey, self.bitcoin_master_pubkey) self.encryption_key = PrivateKey(self.guid_privkey) self.encryption_pubkey = self.encryption_key.public_key.encode()
def save(self, *args, **kwargs): if not self.xpriv: seed_words = self.from_passphrase and self.from_passphrase.encode('ascii') self.xpriv = bip32_master_key(seed=seed_words or os.urandom(100)) self.from_passphrase = '' return super(ExchangeMasterKey, self).save(*args, **kwargs)
def seed2pvkey(seed, path, bip44=True): if bip44: master_xprv = bitcoin.bip32_master_key(seed, b'\x04\x88\xAD\xE4') path_list = path2list(path) return bitcoin.bip32_descend(master_xprv, path_list) else: return seed + "00"
def mnemonic_to_address(mnemonic, passphrase, path): """Return the (compressed) bitcoin address""" masterkey = btc.bip32_master_key( seed.mnemonic_to_seed(mnemonic, passphrase)) _, addr = key_address(masterkey, path) return addr
def create_keychain(self): """ The guid generation can take a while. While it's doing that we will open a port to allow a UI to connect and listen for generation to complete. """ print "Generating GUID, this may take a few minutes..." d = Deferred() api = GUIDGenerationListener(d) site = Site(api, timeout=None) connector = reactor.listenTCP(18470, site, interface="127.0.0.1") start = time.time() g = GUID() d.callback((round(time.time() - start, 2), connector)) self.guid = g.guid self.guid_privkey = g.privkey self.signing_key = nacl.signing.SigningKey(self.guid_privkey) self.guid_signed_pubkey = g.signed_pubkey self.db.set_key("guid", self.guid_privkey, self.guid_signed_pubkey) self.bitcoin_master_privkey = bitcoin.bip32_master_key(bitcoin.sha256(self.guid_privkey)) self.bitcoin_master_pubkey = bitcoin.bip32_privtopub(self.bitcoin_master_privkey) self.db.set_key("bitcoin", self.bitcoin_master_privkey, self.bitcoin_master_pubkey) self.encryption_key = PrivateKey(self.guid_privkey) self.encryption_pubkey = self.encryption_key.public_key.encode()
def mnemonic_to_key(mnemonic, passphrase, path): """Return the (hex) private key""" masterkey = btc.bip32_master_key( seed.mnemonic_to_seed(mnemonic, passphrase)) key, _ = key_address(masterkey, path) return key
def __init__(self, seedarg, max_mix_depth=2, gaplimit=6, extend_mixdepth=False, storepassword=False, pwd=None): super(Wallet, self).__init__() self.max_mix_depth = max_mix_depth self.storepassword = storepassword # key is address, value is (mixdepth, forchange, index) if mixdepth = # -1 it's an imported key and index refers to imported_privkeys self.addr_cache = {} self.unspent = {} self.spent_utxos = [] self.imported_privkeys = {} self.decrypted = False self.seed = self.read_wallet_file_data(seedarg, pwd) if not self.seed: return if extend_mixdepth and len(self.index_cache) > max_mix_depth: self.max_mix_depth = len(self.index_cache) self.gaplimit = gaplimit master = btc.bip32_master_key(self.seed, (btc.MAINNET_PRIVATE if get_network() == 'mainnet' else btc.TESTNET_PRIVATE)) m_0 = btc.bip32_ckd(master, 0) mixing_depth_keys = [ btc.bip32_ckd(m_0, c) for c in range(self.max_mix_depth) ] self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1)) for m in mixing_depth_keys] self.init_index()
def __init__(self, seedarg, max_mix_depth=2, gaplimit=6, extend_mixdepth=False, storepassword=False): super(Wallet, self).__init__() self.max_mix_depth = max_mix_depth self.storepassword = storepassword # key is address, value is (mixdepth, forchange, index) if mixdepth = # -1 it's an imported key and index refers to imported_privkeys self.addr_cache = {} self.unspent = {} self.spent_utxos = [] self.imported_privkeys = {} self.seed = self.read_wallet_file_data(seedarg) if extend_mixdepth and len(self.index_cache) > max_mix_depth: self.max_mix_depth = len(self.index_cache) self.gaplimit = gaplimit master = btc.bip32_master_key(self.seed) m_0 = btc.bip32_ckd(master, 0) mixing_depth_keys = [btc.bip32_ckd(m_0, c) for c in range(self.max_mix_depth)] self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1)) for m in mixing_depth_keys] # self.index = [[0, 0]]*max_mix_depth self.index = [] for i in range(self.max_mix_depth): self.index.append([0, 0])
def _generate_new_keypair(self): seed = str(random.randrange(2 ** 256)) # Deprecated (pre-BIP32) # self.secret = hashlib.sha256(secret).hexdigest() # self.pubkey = privkey_to_pubkey(self.secret) # self.log.debug('Keys %s %s', self.secret, self.pubkey) # Move to BIP32 keys m/0/0/0 wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(seed), 0) wallet_chain = bitcoin.bip32_ckd(wallet, 0) bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, 0) identity_priv = bitcoin.bip32_extract_key(bip32_identity_priv) bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv) identity_pub = bitcoin.encode_pubkey(bitcoin.bip32_extract_key(bip32_identity_pub), 'hex') self.pubkey = identity_pub self.secret = identity_priv new_settings = { "secret": self.secret, "pubkey": self.pubkey, "bip32_seed": seed } self.db_connection.update_entries("settings", new_settings, {"market_id": self.market_id}) self.settings.update(new_settings)
def __init__(self, seedarg, max_mix_depth=2, gaplimit=6, extend_mixdepth=False, storepassword=False, pwd = None): super(Wallet, self).__init__() self.max_mix_depth = max_mix_depth self.storepassword = storepassword # key is address, value is (mixdepth, forchange, index) if mixdepth = # -1 it's an imported key and index refers to imported_privkeys self.addr_cache = {} self.unspent = {} self.spent_utxos = [] self.imported_privkeys = {} self.decrypted = False self.seed = self.read_wallet_file_data(seedarg, pwd) if not self.seed: return if extend_mixdepth and len(self.index_cache) > max_mix_depth: self.max_mix_depth = len(self.index_cache) self.gaplimit = gaplimit self.master_key = btc.bip32_master_key(self.seed, (btc.MAINNET_PRIVATE if get_network() == 'mainnet' else btc.TESTNET_PRIVATE)) m_0 = btc.bip32_ckd(self.master_key, 0) self.mixing_depth_keys = [btc.bip32_ckd(m_0, c) for c in range(self.max_mix_depth)] self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1)) for m in self.mixing_depth_keys] self.init_index()
def __init__(self, seedarg, max_mix_depth=2, gaplimit=6): super(Wallet, self).__init__() self.max_mix_depth = max_mix_depth self.gaplimit = gaplimit self.seed = self.get_seed(seedarg) master = btc.bip32_master_key(self.seed) m_0 = btc.bip32_ckd(master, 0) mixing_depth_keys = [ btc.bip32_ckd(m_0, c) for c in range(max_mix_depth) ] self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1)) for m in mixing_depth_keys] #self.index = [[0, 0]]*max_mix_depth self.index = [] for i in range(max_mix_depth): self.index.append([0, 0]) #example #index = self.index[mixing_depth] #key = btc.bip32_ckd(self.keys[mixing_depth][index[0]], index[1]) self.addr_cache = {} self.unspent = {} self.spent_utxos = []
def save(self, *args, **kwargs): if not self.xpriv: seed_words = self.from_passphrase and self.from_passphrase.encode( 'ascii') self.xpriv = bip32_master_key(seed=seed_words or os.urandom(100)) self.from_passphrase = '' return super(ExchangeMasterKey, self).save(*args, **kwargs)
def showDetails(mnemonic, passphrase="", i=1): myMnemonic = mnemonic passphrase = passphrase mnemo = Mnemonic('english') seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase)) print 'Seed:\t\t\t\t', seed priv = bitcoin.bip32_master_key(unhexlify(seed)) print 'Xpriv:\t\t\t\t', priv key = bitcoin.encode_privkey(bitcoin.bip32_extract_key(priv), 'wif_compressed') print 'Key:\t\t\t\t', key pub = bitcoin.bip32_privtopub(priv) print 'Derived public key:\t', pub pubHex = bitcoin.bip32_extract_key(pub) print 'public key (hex):\t', pubHex print 'Master Key address:\t', bitcoin.pubtoaddr(pubHex) print "" print "TREZOR Keys:" account = 0 derivedPrivateKey = bitcoin.bip32_ckd( bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44 + HARDENED), HARDENED), HARDENED + account) print 'Derived private key:', derivedPrivateKey privateKey = bitcoin.encode_privkey( bitcoin.bip32_extract_key(derivedPrivateKey), 'wif_compressed') print 'private key (wif):\t', privateKey derivedPublicKey = bitcoin.bip32_privtopub(derivedPrivateKey) print 'Derived public key:', derivedPublicKey publicKeyHex = bitcoin.privtopub(privateKey) print 'public key (hex):\t', publicKeyHex address = bitcoin.pubtoaddr(publicKeyHex) print 'address:\t\t\t', address print "" print "Account public keys (XPUB)" xpubs = [] for i in range(0, i): derivedPrivateKey = bitcoin.bip32_ckd( bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44 + HARDENED), HARDENED), HARDENED + i) xpub = bitcoin.bip32_privtopub(derivedPrivateKey) print 'Account', i, 'xpub:', xpub xpubs.append(xpub) return xpubs
def test_bip32_descend(): master = btc.bip32_master_key('\x07'*32) end_key = btc.bip32_descend(master, [2, 3, 10000]) assert end_key=="6856ef965940a1a7b1311dc041050ac0013e326c7ff4e2c677a7694b4f0405c901" end_key = btc.bip32_descend(master, 2, 5, 4, 5) assert end_key=="d2d816b6485103c0d7ff95482788f0e8e73fa11817079e006d47979d8196c4b101"
def mnemonic_to_hdkey(mnemonic): # if we wanted to avoid the mnemonic dep we could just do: # pbkdf2_hmac('sha512', mnemonic, 'mnemonic', 2048).encode('hex') # to get the seed if not Mnemonic('english').check(mnemonic): raise Exception('invalid mnemonic') seed = Mnemonic('english').to_seed(mnemonic) hd_root = bip32_master_key(seed) # path is m/0'/0'/0' return bip32_ckd(bip32_ckd(bip32_ckd(hd_root, 2**31), 2**31), 2**31)
def _print_master_key_and_derived(vbytes: bytes, magicbyte: int): seed = _mnemonic_to_seed(b'This is a very funny mnemonic') master_key = bitcoin.bip32_master_key(seed, vbytes=vbytes) bitprint('Master key:', master_key) _derive_and_print(master_key, 1, 2, 3, magicbyte=magicbyte) _derive_and_print(master_key, 1 + 2**31, 2, 3, derive_pub_key=False, magicbyte=magicbyte)
def showDetails(mnemonic, passphrase="", i=1): myMnemonic = mnemonic passphrase = passphrase mnemo = Mnemonic('english') seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase)) print 'Seed:\t\t\t\t', seed priv = bitcoin.bip32_master_key(unhexlify(seed)) print 'Xpriv:\t\t\t\t', priv key = bitcoin.encode_privkey(bitcoin.bip32_extract_key(priv), 'wif_compressed') print 'Key:\t\t\t\t', key pub = bitcoin.bip32_privtopub(priv) print 'Derived public key:\t', pub pubHex = bitcoin.bip32_extract_key(pub) print 'public key (hex):\t', pubHex print 'Master Key address:\t', bitcoin.pubtoaddr(pubHex) print "" print "TREZOR Keys:" account = 0 derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+account) print 'Derived private key:', derivedPrivateKey privateKey = bitcoin.encode_privkey(bitcoin.bip32_extract_key(derivedPrivateKey), 'wif_compressed') print 'private key (wif):\t', privateKey derivedPublicKey = bitcoin.bip32_privtopub(derivedPrivateKey) print 'Derived public key:', derivedPublicKey publicKeyHex = bitcoin.privtopub(privateKey) print 'public key (hex):\t', publicKeyHex address = bitcoin.pubtoaddr(publicKeyHex) print 'address:\t\t\t', address print "" print "Account public keys (XPUB)" xpubs = [] for i in range(0, i): derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+i) xpub = bitcoin.bip32_privtopub(derivedPrivateKey) print 'Account', i, 'xpub:', xpub xpubs.append(xpub) return xpubs
def create_keychain(self): print "Generating GUID, stand by..." g = GUID() self.guid = g.guid self.guid_privkey = g.privkey self.signing_key = nacl.signing.SigningKey(self.guid_privkey) self.guid_signed_pubkey = g.signed_pubkey self.db.set_key("guid", self.guid_privkey, self.guid_signed_pubkey) self.bitcoin_master_privkey = bitcoin.bip32_master_key(bitcoin.sha256(self.guid_privkey)) self.bitcoin_master_pubkey = bitcoin.bip32_privtopub(self.bitcoin_master_privkey) self.db.set_key("bitcoin", self.bitcoin_master_privkey, self.bitcoin_master_pubkey) self.encryption_key = PrivateKey(self.guid_privkey) self.encryption_pubkey = self.encryption_key.public_key.encode()
def get_master_key(): words = ' '.join(get_password().split()) try: a = bitcoin.words_verify(words) except Exception as e: print(e) a = False if (not a): q = user_input( "Warning! Mnemonic does not verify as a string of bip39 english space-seperated words! continue? [y/N]", 'y') seed = bitcoin.mnemonic_to_seed(words) master_key = bitcoin.bip32_master_key(seed) return master_key
def get_master_key(): words=' '.join(get_password().split()) try: a = bitcoin.words_verify(words) except Exception as e: print(e) a = False if not a: q = user_input( "Warning! Mnemonic does not verify as a string of bip39 english " + "space-seperated words! continue? [y/N]", 'y') seed = bitcoin.mnemonic_to_seed(words) master_key = bitcoin.bip32_master_key(seed) return master_key
def test_bip32_vector(vector): master = btc.bip32_master_key(vector['seed']) assert master == vector['keys'][0][0], 'failed: master xpriv' masterpub = btc.bip32_privtopub(master) assert masterpub == vector['keys'][0][1], 'failed: master xpub' currentkey = master for i in range(1, len(vector['depths'])): currentkey = btc.bip32_ckd(currentkey, vector['depths'][i]) print currentkey print vector['keys'][i][0] assert currentkey == vector['keys'][i][ 0], 'failed: child priv key, should be: ' + vector['keys'][i][0] pub = btc.bip32_privtopub(currentkey) print pub print vector['keys'][i][1] assert pub == vector['keys'][i][ 1], 'failed: child pub key, should be: ' + vector['keys'][i][1]
def create_keychain(self): print "Generating GUID, stand by..." g = GUID() self.guid = g.guid self.guid_privkey = g.privkey self.signing_key = nacl.signing.SigningKey(self.guid_privkey) self.guid_signed_pubkey = g.signed_pubkey self.db.set_key("guid", self.guid_privkey, self.guid_signed_pubkey) self.bitcoin_master_privkey = bitcoin.bip32_master_key( bitcoin.sha256(self.guid_privkey)) self.bitcoin_master_pubkey = bitcoin.bip32_privtopub( self.bitcoin_master_privkey) self.db.set_key("bitcoin", self.bitcoin_master_privkey, self.bitcoin_master_pubkey) self.encryption_key = PrivateKey(self.guid_privkey) self.encryption_pubkey = self.encryption_key.public_key.encode()
def getTrezorXPRIVKeys(mnemonic, passphrase="", i=1): myMnemonic = mnemonic passphrase = passphrase mnemo = Mnemonic('english') seed = hexlify(mnemo.to_seed(myMnemonic, passphrase=passphrase)) priv = bitcoin.bip32_master_key(unhexlify(seed)) account = 0 derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+account) xprivs = [] for i in range(0, i): derivedPrivateKey = bitcoin.bip32_ckd(bitcoin.bip32_ckd(bitcoin.bip32_ckd(priv, 44+HARDENED), HARDENED), HARDENED+i) xprivs.append(derivedPrivateKey) return xprivs
def get_signing_key(self, contract_id): # Get BIP32 child signing key for this order id rows = self.db_connection.select_entries("keystore", { 'contract_id': contract_id }) if len(rows): key_id = rows[0]['id'] settings = self.get_settings() wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(settings.get('bip32_seed')), 1) wallet_chain = bitcoin.bip32_ckd(wallet, 0) bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, key_id) # bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv) return bitcoin.encode_privkey(bitcoin.bip32_extract_key(bip32_identity_priv), 'wif') else: self.log.error('No keys found for that contract id: #%s', contract_id) return
def __init__(self, seedarg, max_mix_depth=2): self.max_mix_depth = max_mix_depth self.seed = self.get_seed(seedarg) master = btc.bip32_master_key(self.seed) m_0 = btc.bip32_ckd(master, 0) mixing_depth_keys = [btc.bip32_ckd(m_0, c) for c in range(max_mix_depth)] self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1)) for m in mixing_depth_keys] #self.index = [[0, 0]]*max_mix_depth self.index = [] for i in range(max_mix_depth): self.index.append([0, 0]) #example #index = self.index[mixing_depth] #key = btc.bip32_ckd(self.keys[mixing_depth][index[0]], index[1]) self.addr_cache = {} self.unspent = {} self.spent_utxos = []
def on_master_key_button_clicked( self, widget, data=None ): if self.settingsStore is not None: checkIfSure = gtk.MessageDialog( self.settingsWindow, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, "Choosing a new masterkey will result in complete loss of any keys associated with your old key. Are you sure you wish to do this?" ) if( checkIfSure.run() == gtk.RESPONSE_NO ): checkIfSure.destroy() return True else: checkIfSure.destroy() seed = os.urandom( 32 ) masterKey = bitcoin.bip32_master_key( seed ) confirm = gtk.MessageDialog( self.settingsWindow, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, gtk.MESSAGE_INFO, gtk.BUTTONS_OK, "Your new key is: " ) confirm.format_secondary_markup( masterKey ) confirm.run() confirm.destroy() self.settingsStore['bip32master'] = masterKey self.settingsStore['accountNumber'] = 1 self.settingsStore['accounts'] = dict() self.settingsWindow.backup_button.set_sensitive( True ) self.update_widget_values()
def _generate_new_keypair(self): seed = str(random.randrange(2**256)) # Deprecated (pre-BIP32) # self.secret = hashlib.sha256(secret).hexdigest() # self.pubkey = privkey_to_pubkey(self.secret) # self.log.debug('Keys %s %s', self.secret, self.pubkey) # Move to BIP32 keys m/0/0/0 wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(seed), 0) wallet_chain = bitcoin.bip32_ckd(wallet, 0) bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, 0) identity_priv = bitcoin.bip32_extract_key(bip32_identity_priv) bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv) identity_pub = bitcoin.encode_pubkey( bitcoin.bip32_extract_key(bip32_identity_pub), 'hex') self.pubkey = identity_pub self.secret = identity_priv # Generate SIN sha_hash = hashlib.sha256() sha_hash.update(self.pubkey) ripe_hash = hashlib.new('ripemd160') ripe_hash.update(sha_hash.digest()) self.guid = ripe_hash.hexdigest() self.sin = obelisk.EncodeBase58Check('\x0F\x02%s' % ripe_hash.digest()) newsettings = { "secret": self.secret, "pubkey": self.pubkey, "guid": self.guid, "sin": self.sin, "bip32_seed": seed } self.db_connection.update_entries("settings", newsettings, {"market_id": self.market_id}) self.settings.update(newsettings)
def generate_new_pubkey(self, contract_id): self.log.debug('Generating new pubkey for contract') # Retrieve next key id from DB next_key_id = len( self.db_connection.select_entries("keystore", select_fields="id")) + 1 # Store updated key in DB self.db_connection.insert_entry("keystore", {'contract_id': contract_id}) # Generate new child key (m/1/0/n) wallet = bitcoin.bip32_ckd( bitcoin.bip32_master_key(self.settings.get('bip32_seed')), 1) wallet_chain = bitcoin.bip32_ckd(wallet, 0) bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, next_key_id) bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv) pubkey = bitcoin.encode_pubkey( bitcoin.bip32_extract_key(bip32_identity_pub), 'hex') return pubkey
def generate_new_pubkey(self, contract_id): self.log.debug('Generating new pubkey for contract') # Retrieve next key id from DB next_key_id = len(self.db_connection.select_entries("keystore", select_fields="id")) + 1 # Store updated key in DB self.db_connection.insert_entry( "keystore", { 'contract_id': contract_id } ) # Generate new child key (m/1/0/n) wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(self.settings.get('bip32_seed')), 1) wallet_chain = bitcoin.bip32_ckd(wallet, 0) bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, next_key_id) bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv) pubkey = bitcoin.encode_pubkey(bitcoin.bip32_extract_key(bip32_identity_pub), 'hex') return pubkey
def _generate_new_keypair(self): seed = str(random.randrange(2 ** 256)) # Deprecated (pre-BIP32) # self.secret = hashlib.sha256(secret).hexdigest() # self.pubkey = privkey_to_pubkey(self.secret) # self.log.debug('Keys %s %s', self.secret, self.pubkey) # Move to BIP32 keys m/0/0/0 wallet = bitcoin.bip32_ckd(bitcoin.bip32_master_key(seed), 0) wallet_chain = bitcoin.bip32_ckd(wallet, 0) bip32_identity_priv = bitcoin.bip32_ckd(wallet_chain, 0) identity_priv = bitcoin.bip32_extract_key(bip32_identity_priv) bip32_identity_pub = bitcoin.bip32_privtopub(bip32_identity_priv) identity_pub = bitcoin.encode_pubkey(bitcoin.bip32_extract_key(bip32_identity_pub), 'hex') self.pubkey = identity_pub self.secret = identity_priv # Generate SIN sha_hash = hashlib.sha256() sha_hash.update(self.pubkey) ripe_hash = hashlib.new('ripemd160') ripe_hash.update(sha_hash.digest()) self.guid = ripe_hash.hexdigest() self.sin = obelisk.EncodeBase58Check('\x0F\x02%s' % ripe_hash.digest()) newsettings = { "secret": self.secret, "pubkey": self.pubkey, "guid": self.guid, "sin": self.sin, "bip32_seed": seed } self.db_connection.update_entries("settings", newsettings, {"market_id": self.market_id}) self.settings.update(newsettings)
def refresh_adresses_preview(self): if self.mnemonic: bip32_path = self.edtHwOptionsBip32Path.text() passphrase = self.edtHwOptionsPassphrase.text() passphrase = self.mnemonic.normalize_string(passphrase) mnem_str = ' '.join(self.get_cur_mnemonic_words()) bip32_seed = self.mnemonic.to_seed(mnem_str, passphrase) bip32_master_key = bitcoin.bip32_master_key(bip32_seed) bip32_path_n = bip32_path_string_to_n(bip32_path) if len(bip32_path_n) > 0: last_idx = bip32_path_n[-1] addresses = [] for idx in range(10): bip32_path_n[-1] = last_idx + idx pk = self.get_bip32_private_key(bip32_path_n, bip32_master_key) pubkey = bitcoin.privkey_to_pubkey(pk) addr = pubkey_to_address(pubkey) path_str = bip32_path_n_to_string(bip32_path_n) addresses.append((path_str, addr)) self.address_preview_model.apply_addresses(addresses) self.address_preview_model.refresh_view() self.viewAddresses.resizeColumnsToContents()
def __init__(self, seedarg, max_mix_depth, gaplimit=6, extend_mixdepth=False): super(Wallet, self).__init__() self.max_mix_depth = max_mix_depth self.seed = self.get_seed(seedarg) if extend_mixdepth and len(self.index_cache) > max_mix_depth: self.max_mix_depth = len(self.index_cache) self.gaplimit = gaplimit master = btc.bip32_master_key(self.seed) m_0 = btc.bip32_ckd(master, 0) mixing_depth_keys = [btc.bip32_ckd(m_0, c) for c in range(self.max_mix_depth)] self.keys = [(btc.bip32_ckd(m, 0), btc.bip32_ckd(m, 1)) for m in mixing_depth_keys] #self.index = [[0, 0]]*max_mix_depth self.index = [] for i in range(self.max_mix_depth): self.index.append([0, 0]) #example #index = self.index[mixing_depth] #key = btc.bip32_ckd(self.keys[mixing_depth][index[0]], index[1]) self.addr_cache = {} self.unspent = {} self.spent_utxos = []
def as_HD_root(self): # BIP39 compatible derivation from seed mnemonic without passphrase master_seed = seedlib.mnemonic.to_seed(self.as_mnemonic()) # Master key pair for BIP32 master_xpriv = bitcoin.bip32_master_key(master_seed) return master_xpriv
import bitcoin from bitcoin.deterministic import bip32_harden as h mnemonic='saddle observe obtain scare burger nerve electric alone minute east walnut motor omit coyote time' seed=bitcoin.mnemonic_to_seed(mnemonic) mpriv=bitcoin.bip32_master_key(seed) accountroot=mpriv accountroot=bitcoin.bip32_ckd(accountroot,h(44)) accountroot=bitcoin.bip32_ckd(accountroot,h(0)) accountroot=bitcoin.bip32_ckd(accountroot,h(0)) for i in range(19): dkey=bitcoin.bip32_descend(accountroot,0,i) print(bitcoin.privtoaddr(dkey))
def nextWord(currSeed, nextPos): global seedCount global f if nextPos < len(sys.argv) - 1: if len(seedStruct[nextPos]) > 1: for x in range(seedStruct[nextPos]['min'], seedStruct[nextPos]['max'] + 1): #print("WordLength: " + str(x) + "------------------------------") for theWord in words[x]: currSeed += theWord + " " nextWord(currSeed, nextPos + 1) currSeed = currSeed.strip().rsplit(' ', 1)[0] + " " else: currSeed += seedStruct[nextPos]['word'] + " " nextWord(currSeed, nextPos + 1) currSeed = currSeed.strip().rsplit(' ', 1)[0] + " " else: if len(seedStruct[nextPos]) > 1: for x in range(seedStruct[nextPos]['min'], seedStruct[nextPos]['max'] + 1): #print("WordLength: " + str(x) + "------------------------------") for theWord in words[x]: currSeed += theWord else: currSeed += seedStruct[nextPos]['word'] seedCount += 1 #print("Seed:" + currSeed) try: entropy = binascii.hexlify(m.to_entropy(currSeed)) hexSeed = binascii.hexlify(m.to_seed(currSeed)) print("Found valid seed!") #print(hexSeed) print("Seed: " + currSeed) output = open('keys_' + str(seedCount) + '.txt', 'w') output.write('Seed: ' + currSeed + '\n') xprv = bitcoin.bip32_master_key(binascii.unhexlify(hexSeed)) #xprvReceive = bitcoin.bip32_ckd(bitcoin.bip32_ckd(xprv, 2**31),0) #m/0'/0 #xprvChange = bitcoin.bip32_ckd(bitcoin.bip32_ckd(xprv, 2**31),1) #m/0'/1 #m/44'/0'/0'/0 - Receive xprvReceive = bitcoin.bip32_ckd( bitcoin.bip32_ckd( bitcoin.bip32_ckd(bitcoin.bip32_ckd(xprv, 44 + 2**31), 2**31), 2**31), 0) #m/44'/0'/0'/1 - Change xprvChange = bitcoin.bip32_ckd( bitcoin.bip32_ckd( bitcoin.bip32_ckd(bitcoin.bip32_ckd(xprv, 44 + 2**31), 2**31), 2**31), 1) rcvAddr = [] chgAddr = [] rcvPrivKey = [] chgPrivKey = [] sys.stdout.write("Generating Seed Keys/Addresses.") for x in range(0, 100): if x % 10 == 0: sys.stdout.write(".") childprivReceive = bitcoin.bip32_ckd(xprvReceive, x) childprivChange = bitcoin.bip32_ckd(xprvChange, x) pkeyReceive = bitcoin.bip32_extract_key(childprivReceive) pkeyChange = bitcoin.bip32_extract_key(childprivChange) rcvAddr.append(bitcoin.privtoaddr(pkeyReceive)) chgAddr.append(bitcoin.privtoaddr(pkeyChange)) rcvPrivKey.append( bitcoin.encode_privkey(pkeyReceive, 'wif_compressed')) chgPrivKey.append( bitcoin.encode_privkey(pkeyChange, 'wif_compressed')) for x in range(0, 100): output.write(rcvPrivKey[x] + '\n') output.write(chgPrivKey[x] + '\n') output.write( '------ END KEYS ------------------------------------\n') for x in range(0, 100): output.write(rcvAddr[x] + '\n') output.write(chgAddr[x] + '\n') output.write( '------ END ADDRESSES -------------------------------\n') output.close() print("Dumped!") except ValueError: sys.stdout.write('.') if seedCount % 1000000 == 0: print(str(seedCount) + ' Seeds ' + str(datetime.now())) f.write((str(seedCount) + ' Seeds ' + str(datetime.now())) + '\n') currSeed = currSeed.strip().rsplit(' ', 1)[0] + " "
import bitcoin from bitcoin.deterministic import bip32_harden as h mnemonic = 'saddle observe obtain scare burger nerve electric alone minute east walnut motor omit coyote time' seed = bitcoin.mnemonic_to_seed(mnemonic) mpriv = bitcoin.bip32_master_key(seed) accountroot = mpriv accountroot = bitcoin.bip32_ckd(accountroot, h(44)) accountroot = bitcoin.bip32_ckd(accountroot, h(0)) accountroot = bitcoin.bip32_ckd(accountroot, h(0)) for i in range(19): dkey = bitcoin.bip32_descend(accountroot, 0, i) print(bitcoin.privtoaddr(dkey))
from pycoin.block import Block as CharmBlock m = mnemonic.Mnemonic('english') # words = m.generate(256) # A sample 24 word mnemonic words = 'december tobacco prize tunnel mammal mixture attend clap jeans inch hybrid apple suspect tube library soap trick scatter wise accident obvious wash alarm fire' print('Words: ', words) entropy = m.to_entropy(words) print('Entropy: ', hexlify(entropy)) seed = m.to_seed(words) print('Bip39 Seed: ', hexlify(seed)) bip32_root_key = bitcoin.bip32_master_key(seed, b'\x04\x88\xAD\xE4') print('BIP32 Root Key (bitcoin lib): ', bip32_root_key) # TODO pycoin allows us to register our own network instead of using BTC. wallet = BIP32Node.from_master_secret(seed, 'BTC') print('BIP32 Root Key (pycoin lib): ', wallet.as_text(as_private=True)) # derivation path semantics are purpose/coin/account/external-or-internal/address-index (H for hardened) # - purpose: 44 indicates BIP44 derivation # - coin: 0 is bitcoin, 1 is testnent (all coins). # We should register here: # https://github.com/satoshilabs/slips/blob/master/slip-0044.md # - account: 0 is the first account # - external-or-internal: 0 for external 1 for internal change addresses # - address-index: 0 first address in derivation path print('Fist (main) address: ', wallet.subkey_for_path('44H/0H/0H/0/0').address())
def load_wallet(wallet_file, get_password_fn): """load and if necessary decrypt a bitcoinj wallet file :param wallet_file: an open bitcoinj wallet file :type wallet_file: file :param get_password_fn: a callback returning a password that's called iff one is required :type get_password_fn: function :return: the Wallet protobuf message or None if no password was entered when required :rtype: wallet_pb2.Wallet """ wallet_file.seek(0) magic_bytes = wallet_file.read(12) wallet_file.seek(0, os.SEEK_END) wallet_size = wallet_file.tell() wallet_file.seek(0) if magic_bytes[2:6] != b"org." and wallet_size % 16 == 0: import pylibscrypt takes_long = not pylibscrypt._done # if a binary library wasn't found, this'll take a while ciphertext = wallet_file.read() assert len(ciphertext) % 16 == 0 password = get_password_fn(takes_long) if not password: return None # Derive the encryption key salt = '\x35\x51\x03\x80\x75\xa3\xb0\xc5' key = pylibscrypt.scrypt(password.encode('utf_16_be'), salt, olen=32) # Decrypt the wallet ( v0.5.0+ ) try: plaintext = aes256_cbc_decrypt(ciphertext[16:], key, ciphertext[:16]) if plaintext[2:6] != b"org.": raise ValueError('incorrect password') except ValueError as e: if e.args[0] == 'incorrect password': # Decrypt the wallet ( < v0.5.0 ) iv = '\xa3\x44\x39\x1f\x53\x83\x11\xb3\x29\x54\x86\x16\xc4\x89\x72\x3e' plaintext = aes256_cbc_decrypt(ciphertext, key, iv) global multibit_hd_password multibit_hd_password = password # Else it's not whole-file encrypted else: password = None plaintext = wallet_file.read() # Parse the wallet protobuf pb_wallet = wallet_pb2.Wallet() try: pb_wallet.ParseFromString(plaintext) except Exception as e: msg = 'not a wallet file: ' + str(e) if password: msg = "incorrect password (or " + msg + ")" raise ValueError(msg) f = open('parsed_wallet.txt','w') f.write(pb_wallet.__str__()) f.close() foundAddr = [] for trans in pb_wallet.transaction: if trans.pool == 4: print("--------------------------------------------------------------------------------") print("TXID: " + binascii.hexlify(trans.hash)) for out in trans.transaction_output: print("") faddr = bitcoin.bin_to_b58check(bitcoin.deserialize_script(out.script_bytes)[2]) print("Addr: " + faddr) foundAddr.append(faddr) print("Amt: " + str(out.value * 0.00000001) + " BTC") print("") print("--------------------------------------------------------------------------------") seed = None sys.stdout.write('Finding Seed....') salt = pb_wallet.encryption_parameters.salt dkey = pylibscrypt.scrypt(password.encode('utf_16_be'), salt, olen=32) for wkey in pb_wallet.key: if wkey.type == 3: seed = aes256_cbc_decrypt(wkey.encrypted_deterministic_seed.encrypted_private_key, dkey, wkey.encrypted_deterministic_seed.initialisation_vector) break if not seed: print("No DETERMINISTIC_MNEMONIC seed found!") return None else: print("Done!") xprv = bitcoin.bip32_master_key(seed) xprvReceive = bitcoin.bip32_ckd(bitcoin.bip32_ckd(xprv, 2**31),0) #m/0'/0 xprvChange = bitcoin.bip32_ckd(bitcoin.bip32_ckd(xprv, 2**31),1) #m/0'/1 rcvAddr = [] chgAddr = [] rcvPrivKey = [] chgPrivKey = [] sys.stdout.write("Generating Addresses/Keys.") for x in range(0,1000): if x % 10 == 0: sys.stdout.write(".") childprivReceive = bitcoin.bip32_ckd(xprvReceive, x) childprivChange = bitcoin.bip32_ckd(xprvChange, x) pkeyReceive = bitcoin.bip32_extract_key(childprivReceive) pkeyChange = bitcoin.bip32_extract_key(childprivChange) #addressReceive = privtoaddr(pkeyReceive) #addressChange = privtoaddr(pkeyChange) rcvAddr.append(bitcoin.privtoaddr(pkeyReceive)) chgAddr.append(bitcoin.privtoaddr(pkeyChange)) rcvPrivKey.append(bitcoin.encode_privkey(pkeyReceive, 'wif_compressed')) chgPrivKey.append(bitcoin.encode_privkey(pkeyChange, 'wif_compressed')) print("Done!") print("--------------------------------------------------------------------------------") for addy in foundAddr: if addy in rcvAddr: print("") print("Found Address: " + addy) print("PrivateKey: " + rcvPrivKey[rcvAddr.index(addy)]) elif addy in chgAddr: print("") print("Found Change Address: " + addy) print("PrivateKey: " + chgPrivKey[chgAddr.index(addy)]) else: print("") print("Address not found: " + addy) print("") print("--------------------------------------------------------------------------------") return pb_wallet
import bitcoin from os import urandom user = '******' email = '*****@*****.**' SECRET_KEY = urandom(32) master_key = bitcoin.bip32_master_key((user + email).encode() + SECRET_KEY) print(master_key) for i in range(10): child = bitcoin.bip32_ckd(master_key, i) addr = bitcoin.bip32_extract_key(child) print(bitcoin.privtoaddr(addr, 0x58))