def get_wallet_balance_from_seed(bip39_mnemonic, bip39_password, derivation_path, last_child_index_to_search, network=Network.MAINNET): bip39_mnemonic = bip39_mnemonic.strip() mnemonic_words = bip39_mnemonic.split() with open('words.txt') as file: lines = file.read().splitlines() validate_mnemonic(mnemonic_words, lines) entropy_and_checksum = mnemonic_to_entropy_and_checksum(bip39_mnemonic, lines) verify_checksum(entropy_and_checksum, int(len(mnemonic_words) / 3)) salt = "mnemonic" + bip39_password seed = hashlib.pbkdf2_hmac('sha512', bytearray(bip39_mnemonic, 'utf-8'), bytearray(salt, 'utf-8'), 2048) debug_print("seed: " + print_hex(seed)) (master_private_key, master_chain_code) = hmac_digest_and_split(bytearray("Bitcoin seed", 'utf-8'), seed, 'sha512') debug_print("Master Private Key: " + print_hex(master_private_key)) debug_print("Master Chain Code: " + print_hex(master_chain_code)) master_public_key = bitcoin.privkey_to_pubkey(master_private_key) compressed_master_public_key = bitcoin.compress(master_public_key) debug_print("Master Public Key: " + print_hex(master_public_key)) debug_print("Master Public Key (Compressed) : " + print_hex(compressed_master_public_key)) print_extended_keys(master_chain_code, master_private_key, compressed_master_public_key, 0, 0, True, None) total_balance = 0 magic_byte = public_magic_byte if network == Network.MAINNET else testnet_magic_byte for i in range(0, last_child_index_to_search): child_key, child_chain_code, child_pub_key = derive_child_from_path( derivation_path=derivation_path + str(i), parent_key=master_private_key, key_type=KeyType.PRIVATE, parent_chain_code=master_chain_code, network=network) address = bitcoin.pubkey_to_address(bitcoin.compress(child_pub_key), magic_byte) print("\nAddress: " + address + "\n") total_balance += query_address_info(address, network) print("Total Balance for this Wallet: " + pretty_format_account_balance(total_balance))
def main(): from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument( '-k', '--key', default= '48f0ba87db8c803933caad92756647f753f07f5a1cd5735a62349b640e81bf94', type=str, help='BTC Private Key') args = parser.parse_args() inputprivatekey = args.key print("inputprivatekey=", inputprivatekey) public_key = private_key_to_public_key(inputprivatekey) #print("Public key (x,y) coordinates:", public_key) compressed_public_key = bitcoin.compress(public_key) #print("Public key (hex compressed):", compressed_public_key) address = pubkey_to_address(compressed_public_key) #print("Compressed Bitcoin address (base58check):", address) print("address=", bitcoin.pubkey_to_address(public_key))
def carlisle_method(data, compress=False): """ Use the Carlisle method to generate a bitcoin address the hash of data. Args: data: bytes, data to hash compress: bool, whether to compress the public key Returns: dictionary with address generation information """ # Compute the sha256 hash of the data sha256_hash = hashlib.sha256(data) private_key = sha256_hash.hexdigest() # Generate public key public_key = bitcoin.privkey_to_pubkey(private_key) if compress: public_key = bitcoin.compress(public_key) # Generate bitcoin address address = bitcoin.pubkey_to_address(public_key) return { 'private_key': private_key, 'public_key': public_key, 'compressed': compress, 'address': address, 'url ': 'https://blockchain.info/address/{}'.format(address), }
def address(self): if self._type == PubkeyType.compressed: bin_hash160 = get_bin_hash160(compress(self.to_bin())) return bin_hash160_to_address(bin_hash160, version_byte=self._version_byte) return bin_hash160_to_address(self.bin_hash160(), version_byte=self._version_byte)
def controller_recover_key(recovery_phrase): #function to recover a public and private key pair from a mnemonic phrase mnemonic_base = Mnemonic(language='english') seed = Mnemonic.to_seed(recovery_phrase) privkey = bc.sha256(seed) pubkey = bc.privkey_to_pubkey(privkey) cpubkey = bc.compress(pubkey) return privkey, cpubkey
def address(self): if self._type == PubkeyType.compressed: bin_hash160 = get_bin_hash160(compress(self.to_bin())) return bin_hash160_to_address( bin_hash160, version_byte=self._version_byte) return bin_hash160_to_address(self.bin_hash160(), version_byte=self._version_byte)
def get_hex_from_public_key(key): """ Get hexadecimal representation of public key. Args: key (ecdsa.VerifyingKey): The public key. Returns: str: The hexadecimal string. """ return bitcoin.compress('04' + binascii.hexlify(key.to_string()).decode())
def controller_keygen(): #function to generate a random mnemonic recovery phrase #and in turn a private a public keys decode_hex = codecs.getdecoder("hex_codec") entropy_hex = bc.random_key() entropy_bytes = decode_hex(entropy_hex)[0] mnemonic_base = Mnemonic(language='english') recovery_phrase = mnemonic_base.to_mnemonic(entropy_bytes) seed = Mnemonic.to_seed(recovery_phrase) privkey = bc.sha256(seed) pubkey = bc.privkey_to_pubkey(privkey) cpubkey = bc.compress(pubkey) return privkey, cpubkey, recovery_phrase
def derive_child_key(parent_key, parent_chain_code, index, key_type, hardened=False): if hardened: if key_type == KeyType.PUBLIC: exit_with_error("Can not derive a hardened public child key from parent public key") input_data = bytearray(b'\x00') + parent_key else: if key_type == KeyType.PUBLIC: input_data = bitcoin.compress(parent_key) else: public_key = bitcoin.privkey_to_pubkey(parent_key) input_data = bitcoin.compress(public_key) input_data += int(index).to_bytes(4, byteorder='big') key = parent_chain_code (key_offset, chain_code) = hmac_digest_and_split(key, input_data) if key_type == KeyType.PUBLIC: point = bitcoin.decompress(bitcoin.privkey_to_pubkey(key_offset)) parent_point = bitcoin.decompress(parent_key) return bitcoin.add_pubkeys(point, parent_point), chain_code else: key = (int.from_bytes(parent_key, byteorder='big', signed=False) + int.from_bytes(key_offset, byteorder='big', signed=False)) % bitcoin.N return key.to_bytes(32, byteorder='big', signed=False), chain_code
def get_xpub(client, bip32_path): bip32_path = clean_bip32_path(bip32_path) bip32_path.strip() if bip32_path.lower().find('m/') >= 0: bip32_path = bip32_path[2:] path_n = bip32_path_string_to_n(bip32_path) parent_bip32_path = bip32_path_n_to_string(path_n[:-1]) depth = len(path_n) index = path_n[-1] nodedata = client.getWalletPublicKey(bip32_path) pubkey = compress(nodedata.get('publicKey')) chaincode = nodedata.get('chainCode') parent_nodedata = client.getWalletPublicKey(parent_bip32_path) parent_pubkey = compress(parent_nodedata['publicKey']) parent_fingerprint = bin_hash160(parent_pubkey)[:4] xpub_raw = bytes.fromhex('0488b21e') + depth.to_bytes(1, 'big') + parent_fingerprint + index.to_bytes(4, 'big') + \ chaincode + pubkey xpub = Base58.check_encode(xpub_raw) return xpub
def create_address(private_key, pkhv, cv, compressed=True): """Create Address from ECDSA private key. Implementation of http://bit.ly/2hH1UUY :param str private_key: ECDSA private key :param str pkhv: address-pubkeyhash-version of chain :param str cv: address-checksum-value of chain :param bool compressed: build address with compressed pubkey :return str: address """ # Derive public key pubkey = privtopub(private_key) if compressed: pubkey = compress(pubkey) return public_key_to_address(pubkey, pkhv, cv)
def public_key(self): # lazily calculate and set the public key if not hasattr(self, '_public_key'): ecdsa_public_key = self._ecdsa_private_key.get_verifying_key() bin_public_key_string = PUBKEY_MAGIC_BYTE + \ ecdsa_public_key.to_string() if self._compressed: bin_public_key_string = compress(bin_public_key_string) # create the public key object from the public key string self._public_key = BitcoinPublicKey( bin_public_key_string, version_byte=self._pubkeyhash_version_byte) # return the public key object return self._public_key
def public_key(self): # lazily calculate and set the public key if not hasattr(self, '_public_key'): ecdsa_public_key = self._ecdsa_private_key.get_verifying_key() bin_public_key_string = PUBKEY_MAGIC_BYTE + \ ecdsa_public_key.to_string() if self._compressed: bin_public_key_string = compress(bin_public_key_string) # create the public key object from the public key string self._public_key = BitcoinPublicKey( bin_public_key_string, version_byte=self._pubkeyhash_version_byte) # return the public key object return self._public_key
def public_key(self): # lazily calculate and set the public key if not hasattr(self, '_public_key'): ecdsa_public_key = self._ecdsa_private_key.get_verifying_key() bin_public_key_string = PUBKEY_MAGIC_BYTE + \ ecdsa_public_key.to_string().hex() #remove extra unknown character that was causing 129 characters vs 128 bin_public_key_string = bin_public_key_string[1:] if self._compressed: bin_public_key_string = compress(bin_public_key_string) # create the public key object from the public key string self._public_key = BitcoinPublicKey( bin_public_key_string, version_byte=self._pubkeyhash_version_byte) # return the public key object return self._public_key
def bech32_sign(tx, i, priv, amount, script=None, hashcode=SIGHASH_ALL): from bitcoin import deserialize, segwit_signature_form, ecdsa_raw_sign, der_encode_sig, serialize, compress i = int(i) txobj = tx if isinstance(tx, dict) else deserialize(tx) if len(priv) <= 33: priv = binascii.hexlify(priv) pub = compress(privkey_to_pubkey(priv)) script = script or ('76a914' + hash160(binascii.unhexlify(pub)) + '88ac') signing_tx = segwit_signature_form(tx, i, script, amount, hashcode=hashcode) rawsig = ecdsa_raw_sign( hashlib.sha256( hashlib.sha256( binascii.unhexlify(signing_tx)).digest()).hexdigest(), priv) sig = der_encode_sig(*rawsig) + encode(hashcode, 16, 2) txobj['ins'][i]['txinwitness'] = [sig, pub] return serialize(txobj)
def print_extended_keys(child_chain_code, child_key, compressed_child_pub_key, depth, index, master, parent_private_key): if master: parent_key_fingerprint = b'\x00\x00\x00\x00' else: pubkey = bitcoin.compress(bitcoin.privkey_to_pubkey(parent_private_key)) sha_ = bitcoin.bin_sha256(pubkey) ripemd_ = bitcoin.bin_ripemd160(sha_) parent_key_fingerprint = ripemd_[0:4] debug_print("Parent Fingerprint: " + print_hex(parent_key_fingerprint)) child_extended_public_key = serialize_extended_key(extended_public_key_version_bytes, depth, parent_key_fingerprint, index, extend_key(child_chain_code, compressed_child_pub_key)) child_extended_private_key = serialize_extended_key(extended_private_key_version_bytes, depth, parent_key_fingerprint, index, extend_key(child_chain_code, b'\x00' + child_key)) debug_print("Extended Public Key for (depth,index): (" + str(depth) + "," + str(index) + ") " + child_extended_public_key) debug_print("Extended Private Key for (depth,index): (" + str(depth) + "," + str(index) + ") " + child_extended_private_key)
def get_wallet_balance_from_extended_public_key(extended_public_key, derivation_path, last_child_index_to_search, network=Network.MAINNET): (versionBytes, depth, parentKeyFingerprint, index, chainCode, pubKey) = deserialize_extended_key( extended_public_key) index = int.from_bytes(index, 'big') hardened = index >= 2 ** 31 if hardened: index -= 2 ** 31 debug_print("XPUB Info: Depth: " + str(ord(depth)) + " index: " + str(index) + " hardened: " + str(hardened)) total_balance = 0 magic_byte = public_magic_byte if network == Network.MAINNET else testnet_magic_byte for i in range(0, last_child_index_to_search): child_key, child_chain_code, child_pub_key = derive_child_from_path( derivation_path=derivation_path + str(i), parent_key=pubKey, key_type=KeyType.PUBLIC, parent_chain_code=chainCode, network=network) address = bitcoin.pubkey_to_address(bitcoin.compress(child_pub_key), magic_byte) total_balance += query_address_info(address) print("Total Balance for this Wallet: " + pretty_format_account_balance(total_balance))
def derive_child(parent_key, parent_chain_code, index, depth, key_type, hardened=False, master=False,network=Network.MAINNET): if hardened: index += hardened_index_offset (childKey, childChainCode) = derive_child_key(parent_key, parent_chain_code, index, key_type, hardened) debug_print("Derived Child key: " + print_hex(childKey)) debug_print("Derived Child chain code: " + print_hex(childChainCode)) wif = generate_wif_from_key(childKey, Network.MAINNET,False) debug_print("wif: " + wif) wif_compressed = generate_wif_from_key(childKey,Network.MAINNET,True) debug_print("wif (compressed): " + wif_compressed) if key_type == KeyType.PRIVATE: child_pub_key = bitcoin.privkey_to_pubkey(childKey) compressed_child_pub_key = bitcoin.compress(child_pub_key) debug_print("Child Pub Key: " + print_hex(child_pub_key)) debug_print("Child Pub Key (Compressed) : " + print_hex(compressed_child_pub_key)) print_extended_keys(childChainCode, childKey, compressed_child_pub_key, depth, index, master, parent_key) else: child_pub_key = childKey return childKey, childChainCode, child_pub_key
inmbr = 0 found_nmbr = 0 #The file 'bitsybitsy.txt' would contain all the found bitcoin addresses that have been bruteforced and have been found in the 'Bits.txt' file filex2 = open('bitsybitsy.txt', 'a') while True: inmbr += 1 if inmbr % 50000 == 0: #Every 50000 iterations that's been done print a notice so we know how far we have come print(inmbr) private_key_hex = Generate_Private_key_hex() if bitcoin.pubkey_to_address( bitcoin.compress( bitcoin.privkey_to_pubkey(private_key_hex))) in bit_addresses: #Every bitcoin private key has two types of addresses either a compressed address or an uncompressed one, here we search the compressed version found_nmbr += 1 print(private_key_hex) filex2.write(private_key_hex + "\n") filex2.flush() print("* * * C O M P R E S S E D * * *") filex2.write("* * * C O M P R E S S E D * * *" + "\n") print("Found " + str(found_nmbr) + " number of address(es) so far. After " + str(inmbr) + " tries.") filex2.write("Found " + str(found_nmbr) + " number of address(es) so far. After " + str(inmbr) + " tries." + "\n") print("Private key HEX value is: " + private_key_hex) filex2.write("Private key HEX value is: " + private_key_hex + "\n") print(
pubKeyBytes = binascii.unhexlify(pubKey) sha256val = hashlib.sha256(pubKeyBytes).digest() ripemd160val = hashlib.new('ripemd160', sha256val).digest() return bitcoin.bin_to_b58check(ripemd160val, magic_byte) priv_key = base58.b58decode('5HueCGU8rMjxEXxiPuD5BDku4MkFqeZyd4dZ1jvhTVqvbTLvyTJ') private_key = binascii.hexlify(priv_key) prKey = private_key[2:-8] print("Private Key (hex): ", prKey) public_key = private_key_to_public_key(prKey) print("Public key (x,y) coordinates: ", public_key) compressed_public_key = bitcoin.compress(public_key) print("Public key (hex compressed): ", compressed_public_key) print() address = bitcoin.pubkey_to_address(public_key) print("Address: ", address) address1 = pubkey_to_address(compressed_public_key) print("Compressed Bitcoin Address (bas58check): ", address1) addressDEC = base58.b58decode(address1) print(addressDEC)
# decoded_private_key = bitcoin.decode_privkey(private_key,'hex') # valid_private_key = 0 < decoded_private_key < bitcoin.N #testnetAddress = bitcoin.privkey_to_address(private_key,111) #print "My private key is: ", private_key #print "My decoded private key is: ", decoded_private_key #print "My testnetAddress is: ", testnetAddress #pubkey1 = bitcoin.privkey_to_pubkey('139cb0d1038dccc8b5e7e224216670b76647c9f8df8a8ec29069cbb3d59aed2b') #pubkey2 = bitcoin.privkey_to_pubkey('36b4fbdf43365191d3aea9361467b234f58a7244ae8d05f696e634726a162d01') #pubkey = bitcoin.privkey_to_pubkey('15e9a5e2097c9a40eb4bd0aea4e334dd2f799c7e1f6173cb59505d470816fe9e') #print "pubkey 1: ", pubkey1 #print "pubkey 2: ", pubkey2 #print "intial pubkey: ", pubkey #num = bitcoin.is_privkey('15e9a5e2097c9a40eb4bd0aea4e334dd2f799c7e1f6173cb59505d470816fe9e') pub = bitcoin.privkey_to_pubkey( '15e9a5e2097c9a40eb4bd0aea4e334dd2f799c7e1f6173cb59505d470816fe9e') compPub = bitcoin.compress(pub) add = bitcoin.pubkey_to_address(compPub, 111) print compPub print add #if num: # print "OK" #else: # print "damn" #print add transaction_info = '01000000018fd99010bf216c4aeece38bebcc94a740b853d64a4ee5d7d8217bf61b77abb1a010000006b483045022100f2353403f2f6aeb981b0870f35c0441e58a15786dd4c76307b8129d786031fcc022039c1861433a28d71026ba5860078cd8aa61951faee73af916fcb7d3301ac6ffc0121035ec6f5e117a67b3164f388105bf23b3d2af9fb39f939e24df53cf303b27e1bf7ffffffff01e01fec22000000001976a91464e6df2dbc78c34a8fffe908c223bd05683c479688ac00000000' txinfo_hex = transaction_info.decode("hex") transaction_i = hashlib.sha256(txinfo_hex).digest() transaction_id = hashlib.sha256(transaction_i).digest() transaction_id = transaction_id[::-1].encode('hex_codec') print transaction_id
#version byte is 111 for testnet, 0 for mainnet if testnet: version_byte = 111 addr_byte = 235 else: version_byte = 52 addr_byte = 38 print("burnlist control wallet") print(" ") privkey = open('brnlist_privkey.dat', 'r').read() brnlistprivkey = bc.encode_privkey(privkey, 'wif_compressed', version_byte) brnpubkey_uc = bc.privkey_to_pubkey(privkey) brnpubkey = bc.compress(brnpubkey_uc) brnaddress = bc.pubkey_to_address(brnpubkey, addr_byte) print("Connecting to Ocean client") print(" ") rpcport = 8332 rpcuser = '******' rpcpassword = '******' url = 'http://' + rpcuser + ':' + rpcpassword + '@localhost:' + str(rpcport) ocean = rpc.RPCHost(url) print("Add address to burnlist:") inpt = input("Enter address: ") addresstoburn = str(inpt) #the client wallet we connect to via RPC is expected to have the private keys to the policy asset outputs
#version byte is 111 for testnet, 0 for mainnet if testnet: version_byte = 111 addr_byte = 235 else: version_byte = 52 addr_byte = 38 print("Freezelist control wallet") print(" ") privkey = open('frzlist_privkey.dat', 'r').read() frzlistprivkey = bc.encode_privkey(privkey, 'wif_compressed', version_byte) frzpubkey_uc = bc.privkey_to_pubkey(privkey) frzpubkey = bc.compress(frzpubkey_uc) frzaddress = bc.pubkey_to_address(frzpubkey, addr_byte) print("Connecting to Ocean client") print(" ") rpcport = 8332 rpcuser = '******' rpcpassword = '******' url = 'http://' + rpcuser + ':' + rpcpassword + '@localhost:' + str(rpcport) ocean = rpc.RPCHost(url) inpto = input("Add address to freezelist or remove from freezelist? (A/R)") if inpto == 'A': inpt = input("Enter address: ")
def not_simple_spend(from_privkey, to_addresses, to_satoshis, change_address=None, privkey_is_compressed=True, min_confirmations=0, api_key=None, coin_symbol='btc'): ''' Simple method to spend from one single-key address to another. Signature takes place locally (client-side) after unsigned transaction is verified. Returns the tx_hash of the newly broadcast tx. If no change_address specified, change will be sent back to sender address. Note that this violates the best practice. To sweep, set to_satoshis=-1 Compressed public keys (and their corresponding addresses) have been the standard since v0.6, set privkey_is_compressed=False if using uncompressed addresses. Note that this currently only supports spending from single key addresses. ''' assert is_valid_coin_symbol(coin_symbol), coin_symbol assert api_key, 'api_key required' assert type(to_addresses) and type(to_satoshis) is list assert len(to_addresses) == len(to_satoshis) for i in to_satoshis: assert type(i) is int, i if privkey_is_compressed: from_pubkey = compress(privkey_to_pubkey(from_privkey)) else: from_pubkey = privkey_to_pubkey(from_privkey) from_address = pubkey_to_address( pubkey=from_pubkey, # this method only supports paying from pubkey anyway magicbyte=COIN_SYMBOL_MAPPINGS[coin_symbol]['vbyte_pubkey'], ) inputs = [ { 'address': from_address }, ] logger.info('inputs: %s' % inputs) outputs = [] for i in range(len(to_addresses)): outputs.append({'address': to_addresses[i], 'value': to_satoshis[i]}) #outputs = [{'address': to_address, 'value': to_satoshis}, ] logger.info('outputs: %s' % outputs) # will fail loudly if tx doesn't verify client-side unsigned_tx = create_unsigned_tx( inputs=inputs, outputs=outputs, # may build with no change address, but if so will verify # change in next step # done for extra security in case of client-side bug in change # address generation change_address=change_address, coin_symbol=coin_symbol, min_confirmations=min_confirmations, verify_tosigntx=False, # will verify in next step include_tosigntx=True, api_key=api_key, ) logger.info('unsigned_tx: %s' % unsigned_tx) if 'errors' in unsigned_tx: print('TX Error(s): Tx NOT Signed or Broadcast') for error in unsigned_tx['errors']: print(error['error']) # Abandon raise Exception('Build Unsigned TX Error') if change_address: change_address_to_use = change_address else: change_address_to_use = from_address tx_is_correct, err_msg = verify_unsigned_tx( unsigned_tx=unsigned_tx, inputs=inputs, outputs=outputs, sweep_funds=bool(to_satoshis == -1), change_address=change_address_to_use, coin_symbol=coin_symbol, ) if not tx_is_correct: print(unsigned_tx) # for debug raise Exception('TX Verification Error: %s' % err_msg) privkey_list, pubkey_list = [], [] for proposed_input in unsigned_tx['tx']['inputs']: privkey_list.append(from_privkey) pubkey_list.append(from_pubkey) # paying from a single key should only mean one address per input: assert len( proposed_input['addresses']) == 1, proposed_input['addresses'] # logger.info('privkey_list: %s' % privkey_list) logger.info('pubkey_list: %s' % pubkey_list) # sign locally tx_signatures = make_tx_signatures( txs_to_sign=unsigned_tx['tosign'], privkey_list=privkey_list, pubkey_list=pubkey_list, ) logger.info('tx_signatures: %s' % tx_signatures) # broadcast TX broadcasted_tx = broadcast_signed_transaction( unsigned_tx=unsigned_tx, signatures=tx_signatures, pubkeys=pubkey_list, coin_symbol=coin_symbol, api_key=api_key, ) logger.info('broadcasted_tx: %s' % broadcasted_tx) if 'errors' in broadcasted_tx: print('TX Error(s): Tx May NOT Have Been Broadcast') for error in broadcasted_tx['errors']: print(error['error']) print(broadcasted_tx) return return broadcasted_tx['tx']['hash']
def pubkey_to_bitcoin_address(pk, prefix): return bitcoin.pubtoaddr(bitcoin.compress((pk.x, pk.y)), magicbyte=prefix)
import bitcoin, hashlib, binascii # Returns public key from given private key in hex format def private_key_to_public_key(privateKeyHex: str) -> (int, int): privateKey = int(privateKeyHex, 16) return bitcoin.fast_multiply(bitcoin.G, privateKey) # Returns address from given public key using Bitcoin hash algorithms def public_key_to_address(publicKey: str, magic_byte=0) -> str: publicKeyBytes = binascii.unhexlify(publicKey) sha256hash = hashlib.sha256(publicKeyBytes).digest() ripemd160hash = hashlib.new('ripemd160', sha256hash).digest() return bitcoin.bin_to_b58check(ripemd160hash, magic_byte) # Get random private key privateKey = bitcoin.random_key() # Calculate the public key coordinates publicKey = private_key_to_public_key(privateKey) # Compress the public key compressedPublicKey = bitcoin.compress(publicKey) # Generate the Bitcoin address - Base58CheckEncode(RIPEMD160(SHA256(P_compressed))) address = public_key_to_address(compressedPublicKey) print(address)
ADDRESS_CHECKSUM_VALUE = '953ABC69' def hexxor(a, b): result = bytearray() for b1, b2 in zip(a, b): result.append(b1 ^ b2) return bytes(result).hex() chain_checksum = unhexlify('953ABC69') address = '1Yu2BuptuZSiBWfr2Qy4aic6qEVnwPWrdkHPEc' decoded = base58.b58decode(address) checksum = decoded[-4:] uncompressed_public_key = privtopub(ECDSA_PRIVATE_KEY) compressed_public_key = compress(uncompressed_public_key) pub_key_sha256 = sha256(unhexlify(compressed_public_key)).hexdigest() ripemd160 = new('ripemd160') ripemd160.update(unhexlify(pub_key_sha256)) pub_key_rip = ripemd160.hexdigest() def extend_ripmed(pub_key_rip, ap_version=ADDRESS_PUBKEYHASH_VERSION): pkr_data = unhexlify(pub_key_rip) ap_version = unhexlify(ap_version) steps = math.floor(20 / len(ap_version)) print(steps) chunks = [pkr_data[i:i+steps] for i in range(0, len(pkr_data), steps)] merged = b'' for idx, b in enumerate(unhexlify(ADDRESS_PUBKEYHASH_VERSION), start=0): merged += b.to_bytes(1, 'big') + chunks[idx]
bipp44_path = ("8000002C" + "80000378" + "80000000" + "00000000" + "00000000") b = bytes.fromhex( "037edf1d72c29e6de321e95d1d0c2736223fe895009bf448e520c1333b05d6d6fd") p = SEC1Encoder.decode_public_key(b, curve=curve.P256) p2 = SEC1Encoder.encode_public_key(p, compressed=False).hex() payload = bytes.fromhex(p2 + bipp44_path) ecdhPayloadArray = [payload] dongle = getDongle(True) publicKey = dongle.exchange(bytes.fromhex("80040000FF" + bipp44_path)) print("got publicKey " + publicKey.hex()) print("compressed: " + bitcoin.compress(publicKey).hex()) print("requesting ecdh with: " + p2) for ecdhPayload in ecdhPayloadArray: try: offset = 0 while offset < len(ecdhPayload): if (len(ecdhPayload) - offset) > 255: chunk = ecdhPayload[offset:offset + 255] else: chunk = ecdhPayload[offset:] if (offset + len(chunk)) == len(ecdhPayload): p1 = b'\x80' else: p1 = b'\x00' apdu = bytes.fromhex("800a") + p1 + b'\x00' + struct.pack(