def CKDpriv(self, i): """ Create a child key of index 'i'. If the most significant bit of 'i' is set, then select from the hardened key set, otherwise, select a regular child key. Returns a BIP32Key constructed with the child key parameters, or None if i index would result in an invalid key. """ # Index as bytes, BE i_str = struct.pack(">L", i) # Data to HMAC if i & BIP32_HARDEN: data = b'\0' + self.k.to_string() + i_str else: data = self.PublicKey() + i_str # Get HMAC of data (Il, Ir) = self.hmac(data) # Construct new key material from Il and current private key Il_int = string_to_int(Il) if Il_int > CURVE_ORDER: return None pvt_int = string_to_int(self.k.to_string()) k_int = (Il_int + pvt_int) % CURVE_ORDER if (k_int == 0): return None secret = (b'\0'*32 + int_to_string(k_int))[-32:] # Construct and return a new BIP32Key return BIP32Key(secret=secret, chain=Ir, depth=self.depth+1, index=i, fpr=self.Fingerprint(), public=False, testnet=self.testnet)
def _derive_key_by_index(self, index) -> Optional["Wallet"]: i_str = struct.pack(">L", index) if index & config["hardened"]: data = b"\0" + self._key.to_string() + i_str else: data = unhexlify(self.public_key()) + i_str if not self._chain_code: raise PermissionError( "You can't drive xprivate_key and private_key.") i = hmac.new(self._chain_code, data, hashlib.sha512).digest() il, ir = i[:32], i[32:] il_int = string_to_int(il) if il_int > CURVE_ORDER: return None pvt_int = string_to_int(self._key.to_string()) k_int = (il_int + pvt_int) % CURVE_ORDER if k_int == 0: return None secret = (b"\0" * 32 + int_to_string(k_int))[-32:] self._private_key, self._chain_code, self._depth, self._index, self._parent_fingerprint = ( secret, ir, (self._depth + 1), index, unhexlify(self.finger_print())) self._key = ecdsa.SigningKey.from_string(self._private_key, curve=SECP256k1) self._verified_key = self._key.get_verifying_key() return self
def CKDpriv(self, i): """ Create a child key of index 'i'. If the most significant bit of 'i' is set, then select from the hardened key set, otherwise, select a regular child key. Returns a BIP32Key constructed with the child key parameters, or None if i index would result in an invalid key. """ # Index as bytes, BE i_str = struct.pack(">L", i) # Data to HMAC if i & BIP32_HARDEN: data = b'\0' + self.k.to_string() + i_str else: data = self.PublicKey() + i_str # Get HMAC of data (Il, Ir) = self.hmac(data) # Construct new key material from Il and current private key Il_int = string_to_int(Il) if Il_int > CURVE_ORDER: return None pvt_int = string_to_int(self.k.to_string()) k_int = (Il_int + pvt_int) % CURVE_ORDER if (k_int == 0): return None secret = (b'\0'*32 + int_to_string(k_int))[-32:] # Construct and return a new BIP32Key return BIP32Key(secret=secret, chain=Ir, depth=self.depth+1, index=i, fpr=self.Fingerprint(), public=False)
def child_priv(self, index): if index >= 0x80000000: data = b'\0' + self.k.to_string() + index.to_bytes(4, 'big') else: k_int = string_to_int(self.k.to_string()) point = k_int * generator_secp256k1 compressed = self.sec(point) data = compressed + index.to_bytes(4, 'big') left, right = self.hmac(data) left_int = string_to_int(left) k_int = string_to_int(self.k.to_string()) child_k_int = (left_int + k_int) % generator_secp256k1.order() if (child_k_int == 0) or left_int >= generator_secp256k1.order(): return None child_key = int_to_string(child_k_int) child_key = zero_padding(32, child_key) assert (len(child_key) == 32) key = Key(secret=child_key, chain=right, level=self.level + 1, index=index.to_bytes(4, 'big'), fingerprint=self.fingerprint(), public=False) self.children.append(key) return key
def CKDpriv(self): if self.hardened: i= 2147483648+self.index i_str=struct.pack('>L',i) child_L_MPK=b'\x00'+self.priv_key+i_str else: i= self.index i_str=struct.pack('>L',i) child_L_MPK=self.pub_key+i_str child_L_MPKhmac=hmac.new(key=self.chaincode, msg=child_L_MPK , digestmod=hashlib.sha512).digest() child_LPhml, output_chaincode = child_L_MPKhmac[:32], child_L_MPKhmac[32:] child_LPhml_int=(string_to_int(child_LPhml)) master_pk_int=(string_to_int(self.priv_key)) presecret=child_LPhml_int+master_pk_int return (b'\x00'*32 + int_to_string(presecret% CURVE_ORDER))[-32:]
def CKDpub(self, i): """ Create a publicly derived child key of index 'i'. If the most significant bit of 'i' is set, this is an error. Returns a BIP32Key constructed with the child key parameters, or None if index would result in invalid key. """ if i & BIP32_HARDEN: raise Exception("Cannot create a hardened child key using public child derivation") # Data to HMAC. Same as CKDpriv() for public child key. data = self.PublicKey() + struct.pack(">L", i) # Get HMAC of data (Il, Ir) = self.hmac(data) # Construct curve point Il*G+K Il_int = string_to_int(Il) if Il_int >= CURVE_ORDER: return None point = Il_int*CURVE_GEN + self.K.pubkey.point if point == INFINITY: return None # Retrieve public key based on curve point K_i = ecdsa.VerifyingKey.from_public_point(point, curve=SECP256k1) # Construct and return a new BIP32Key return BIP32Key(secret=K_i, chain=Ir, depth=self.depth+1, index=i, fpr=self.Fingerprint(), public=True, testnet=self.testnet)
def CKDpub(self, i): """ Create a publicly derived child key of index 'i'. If the most significant bit of 'i' is set, this is an error. Returns a BIP32Key constructed with the child key parameters, or None if index would result in invalid key. """ if i & BIP32_HARDEN: raise Exception("Cannot create a hardened child key using public child derivation") # Data to HMAC. Same as CKDpriv() for public child key. data = self.PublicKey() + struct.pack(">L", i) # Get HMAC of data (Il, Ir) = self.hmac(data) # Construct curve point Il*G+K Il_int = string_to_int(Il) if Il_int >= CURVE_ORDER: return None point = Il_int*CURVE_GEN + self.K.pubkey.point if point == INFINITY: return None # Retrieve public key based on curve point K_i = ecdsa.VerifyingKey.from_public_point(point, curve=SECP256k1) # Construct and return a new BIP32Key return BIP32Key(secret=K_i, chain=Ir, depth=self.depth, index=i, fpr=self.Fingerprint(), public=True)
def fromExtendedKey(xkey, public=False): """ Create a BIP32Key by importing from extended private or public key string If public is True, return a public-only key regardless of input type. """ # Sanity checks raw = Base58.check_decode(xkey) if len(raw) != 78: raise ValueError("extended key format wrong length") # Verify address version/type version = raw[:4] known_version = False for (testnet_header, public_header, d) in [ (False, False, XPRV_HEADERS_MAIN), (True, False, XPRV_HEADERS_TEST), (False, True, XPUB_HEADERS_MAIN), (True, True, XPUB_HEADERS_TEST), ]: for key, header in d.items(): if version == header: script_type = key is_testnet = testnet_header is_pubkey = public_header known_version = True break if not known_version: raise ValueError("unknown extended key version") # Extract remaining fields # Python 2.x compatibility if type(raw[4]) == int: depth = raw[4] else: depth = ord(raw[4]) fpr = raw[5:9] child = struct.unpack(">L", raw[9:13])[0] chain = raw[13:45] secret = raw[45:78] # Extract private key or public key point if not is_pubkey: secret = secret[1:] else: # Recover public curve point from compressed key # Python3 FIX lsb = secret[0] & 1 if type(secret[0]) == int else ord(secret[0]) & 1 x = string_to_int(secret[1:]) ys = (x**3+7) % FIELD_ORDER # y^2 = x^3 + 7 mod p y = sqrt_mod(ys, FIELD_ORDER) if y & 1 != lsb: y = FIELD_ORDER-y point = ecdsa.ellipticcurve.Point(SECP256k1.curve, x, y) secret = ecdsa.VerifyingKey.from_public_point(point, curve=SECP256k1) key = BIP32Key(secret=secret, chain=chain, depth=depth, index=child, fpr=fpr, public=is_pubkey, testnet=is_testnet, script_type=script_type) if not is_pubkey and public: key = key.SetPublic() return key
def test_generate(self): from ecdsa import SigningKey, NIST521p sk = SigningKey.generate(curve=NIST521p) pri = sk.privkey pub = pri.public_key param = dict( crv=sk.curve, x=pub.point.x(), y=pub.point.y(), d=pri.secret_multiplier) # Curve from ecdsa.ellipticcurve import Point, CurveFp from ecdsa.ecdsa import curve_521 self.assertTrue(isinstance(curve_521, CurveFp)) self.assertTrue(isinstance(param['crv'].curve, CurveFp)) self.assertEqual(curve_521, param['crv'].curve) self.assertEqual(pub.point.curve(), curve_521) # Point p_new = Point(curve_521, param['x'], param['y']) self.assertEqual(p_new, pub.point) self.assertTrue(isinstance(pub.point, Point)) # Public Key from ecdsa.ecdsa import Public_key, generator_521 self.assertEqual(generator_521, pub.generator) pub_new = Public_key(generator_521, p_new) # Private Key from ecdsa.ecdsa import Private_key pri_new = Private_key(pub_new, param['d']) # Signature from ecdsa.ecdsa import string_to_int, Signature from hashlib import sha512 from uuid import uuid1 rnd = uuid1().int msg = "hello, it's me.".encode('utf8') digest = string_to_int(sha512(msg).digest()) signature_new = pri_new.sign(digest, rnd) signature_old = pri.sign(digest, rnd) self.assertTrue(isinstance(signature_new, Signature)) self.assertEqual(signature_new.r, signature_old.r) self.assertEqual(signature_new.s, signature_old.s) import six # python3 no long self.assertTrue(type(signature_new.r) in six.integer_types) self.assertTrue(type(signature_new.s) in six.integer_types) # Verify print(pub.verifies(digest, signature_new)) print(pub_new.verifies(digest, signature_old)) # print(dir(pri_new)) print(dir(pub_new)) print(dir(pub_new.curve))
def fromExtendedKey(xkey, public=False): """ Create a BIP32Key by importing from extended private or public key string If public is True, return a public-only key regardless of input type. """ # Sanity checks raw = Base58.check_decode(xkey) if len(raw) != 78: raise ValueError("extended key format wrong length") # Verify address version/type version = raw[:4] tversion = codecs.encode(version,"hex") if tversion in query_lsit(testnet=False): is_testnet = False is_pubkey = False elif tversion in query_lsit(testnet=True): is_testnet = True is_pubkey = False elif tversion in query_lsit(public=True): is_testnet = False is_pubkey = True elif tversion in query_lsit(public=True,testnet=True): is_testnet = True is_pubkey = True else: raise ValueError("unknown extended key version") # Extract remaining fields # Python 2.x compatibility if type(raw[4]) == int: depth = raw[4] else: depth = ord(raw[4]) fpr = raw[5:9] child = struct.unpack(">L", raw[9:13])[0] chain = raw[13:45] secret = raw[45:78] # Extract private key or public key point if not is_pubkey: secret = secret[1:] else: # Recover public curve point from compressed key # Python3 FIX lsb = secret[0] & 1 if type(secret[0]) == int else ord(secret[0]) & 1 x = string_to_int(secret[1:]) ys = (x**3+7) % FIELD_ORDER # y^2 = x^3 + 7 mod p y = sqrt_mod(ys, FIELD_ORDER) if y & 1 != lsb: y = FIELD_ORDER-y point = ecdsa.ellipticcurve.Point(SECP256k1.curve, x, y) secret = ecdsa.VerifyingKey.from_public_point(point, curve=SECP256k1) key = BIP32Key(secret=secret, chain=chain, depth=depth, index=child, fpr=fpr, public=is_pubkey, testnet=is_testnet) if not is_pubkey and public: key = key.SetPublic() return key
def seed_to_master(seed, passphrase, derivation_path, hardened_items, total_addresses, address_type, testnet): pbkdf2_result=PBKDF2.hexread(PBKDF2(seed, 'mnemonic'+passphrase, iterations=2048, macmodule=hmac, digestmodule=hashlib.sha512), 64) hmac_hash= hmac.new(key=b"Bitcoin seed", msg=codecs.decode(pbkdf2_result, 'hex'), digestmod=hashlib.sha512).digest() master_pk, master_cc = hmac_hash[:32], hmac_hash[32:] master_pubkey=S256Point.sec((string_to_int(master_pk))*G) return path_gen_keylist(master_cc,master_pk, master_pubkey, derivation_path, hardened_items,total_addresses, address_type, testnet)
def fromExtendedKey(xkey, public=False): """ Create a BIP32Key by importing from extended private or public key string If public is True, return a public-only key regardless of input type. """ # Sanity checks raw = Base58.check_decode(xkey) if len(raw) != 78: raise ValueError("extended key format wrong length") # Verify address version/type version = raw[:4] if version == EX_MAIN_PRIVATE: is_testnet = False is_pubkey = False elif version == EX_TEST_PRIVATE: is_testnet = True is_pubkey = False elif version == EX_MAIN_PUBLIC: is_testnet = False is_pubkey = True elif version == EX_TEST_PUBLIC: is_testnet = True is_pubkey = True else: raise ValueError("unknown extended key version") # Extract remaining fields # Python 2.x compatibility if type(raw[4]) == int: depth = raw[4] else: depth = ord(raw[4]) fpr = raw[5:9] child = struct.unpack(">L", raw[9:13])[0] chain = raw[13:45] secret = raw[45:78] # Extract private key or public key point if not is_pubkey: secret = secret[1:] else: # Recover public curve point from compressed key lsb = ord(secret[0]) & 1 x = string_to_int(secret[1:]) ys = (x**3+7) % FIELD_ORDER # y^2 = x^3 + 7 mod p y = sqrt_mod(ys, FIELD_ORDER) if y & 1 != lsb: y = FIELD_ORDER-y point = ecdsa.ellipticcurve.Point(SECP256k1.curve, x, y) secret = ecdsa.VerifyingKey.from_public_point(point, curve=SECP256k1) key = BIP32Key(secret=secret, chain=chain, depth=depth, index=child, fpr=fpr, public=is_pubkey, testnet=is_testnet) if not is_pubkey and public: key = key.SetPublic() return key
def __CkdPriv(self, index): """ Create a child key of the specified index. Args: index (int): Index Returns: Bip32 object: Bip32 object constructed with the child parameters Raises: Bip32KeyError: If the index results in an invalid key """ # Index as bytes index_bytes = index.to_bytes(4, "big") # Data for HMAC if Bip32Utils.IsHardenedIndex(index): data = b"\x00" + self.m_key.to_string() + index_bytes else: data = self.PublicKey().RawCompressed().ToBytes() + index_bytes # Compute HMAC halves i_l, i_r = self.__HmacHalves(data) # Construct new key secret from i_l and current private key i_l_int = string_to_int(i_l) key_int = string_to_int(self.m_key.to_string()) new_key_int = (i_l_int + key_int) % Bip32Const.CURVE_ORDER # Convert to string and left pad with zeros secret = int_to_string(new_key_int) secret = b"\x00" * (32 - len(secret)) + secret # Construct and return a new Bip32 object return Bip32(secret=secret, chain=i_r, depth=self.m_depth + 1, index=index, fprint=self.FingerPrint(), is_public=False, key_net_ver=self.m_key_net_ver)
def fromExtendedKey(xkey, public=False): """ Create a BIP32Key by importing from extended private or public key string If public is True, return a public-only key regardless of input type. """ # Sanity checks raw = Base58.check_decode(xkey) if len(raw) != 78: raise ValueError("extended key format wrong length") # Verify address version/type version = raw[:4] if version == EX_MAIN_PRIVATE: keytype = 'xprv' elif version == EX_MAIN_PUBLIC: keytype = 'xpub' else: raise ValueError("unknown extended key version") # Extract remaining fields depth = ord(raw[4]) fpr = raw[5:9] child = struct.unpack(">L", raw[9:13])[0] chain = raw[13:45] secret = raw[45:78] # Extract private key or public key point if keytype == 'xprv': secret = secret[1:] else: # Recover public curve point from compressed key lsb = ord(secret[0]) & 1 x = string_to_int(secret[1:]) ys = (x**3 + 7) % FIELD_ORDER # y^2 = x^3 + 7 mod p y = sqrt_mod(ys, FIELD_ORDER) if y & 1 != lsb: y = FIELD_ORDER - y point = ecdsa.ellipticcurve.Point(SECP256k1.curve, x, y) secret = ecdsa.VerifyingKey.from_public_point(point, curve=SECP256k1) is_pubkey = (keytype == 'xpub') key = BIP32Key(secret=secret, chain=chain, depth=depth, index=child, fpr=fpr, public=is_pubkey) if not is_pubkey and public: key = key.SetPublic() return key
def test_xpub_bytes_to_field_bytes(self): root = "xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw" child1 = "xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ" root_b, child1_b = map(Base58.check_decode, [root, child1]) as_int = lambda x, f: string_to_int(xpub_bytes_to_field_bytes(x, f)) # Check the depth self.assertEqual(as_int(root_b, 'depth'), 1) self.assertEqual(as_int(child1_b, 'depth'), 2) # Check the child number self.assertEqual(as_int(child1_b, 'child_number'), 1)
def DerivePrivateKey(self, index): i_str = struct.pack(">L", index) if index & BIP32_HARDEN: data = b'\0' + self.key.to_string() + i_str else: data = self.PublicKey() + i_str Il, Ir = self.hmac(data) Il_int = string_to_int(Il) if Il_int > CURVE_ORDER: return None pvt_int = string_to_int(self.key.to_string()) k_int = (Il_int + pvt_int) % CURVE_ORDER if k_int == 0: return None secret = (b'\0' * 32 + int_to_string(k_int))[-32:] return CobraHDWallet( secret=secret, chain=Ir, depth=self.depth + 1, index=index, fingerprint=self.Fingerprint())
def derive_private_key(self, index): i_str = struct.pack(">L", index) if index & BIP32KEY_HARDEN: data = b"\0" + self.key.to_string() + i_str else: data = unhexlify(self.public_key()) + i_str il, ir = self.hmac(data) il_int = string_to_int(il) if il_int > CURVE_ORDER: return None pvt_int = string_to_int(self.key.to_string()) k_int = (il_int + pvt_int) % CURVE_ORDER if k_int == 0: return None secret = (b"\0" * 32 + int_to_string(k_int))[-32:] self.secret, self.chain, self.depth, self.index, self.parent_fingerprint = \ secret, ir, (self.depth + 1), index, unhexlify(self.finger_print()) self.key = ecdsa.SigningKey.from_string(self.secret, curve=SECP256k1) self.verified_key = self.key.get_verifying_key() return self
def child_key_derivation_from_private(master_private_key, master_chaincode, index): i_str = ser32(index) if index & BIP32_HARDEN: data = bytes.fromhex("00") + master_private_key + bytes(i_str) else: data = private_to_public(master_private_key) + bytes(i_str) (Il, Ir) = hmacsha512(data, master_chaincode) ilInt = string_to_int(Il) if ilInt > CURVE_ORDER: return None privateInt = string_to_int(master_private_key) priavte_key_int = (ilInt + privateInt) % CURVE_ORDER if (priavte_key_int == 0): return None secret = (b'\0'*32 + int_to_string(priavte_key_int))[-32:] print("child key:" + str(index)) print("private key:" + secret.hex()) print("wif priavte key:" + privatekey_to_wif(secret)) publicKey = private_to_public(secret) print("public key:" + publicKey.hex()) print("address:" + publickey_to_address(publicKey)) print("") return secret, Ir
def __CkdPub(self, index): """ Create a publicly derived child key of the specified index. Args: index (int): Index Returns: Bip32 object: Bip32 object constructed with the child parameters Raises: Bip32KeyError: If the index is hardened or results in an invalid key """ # Check if index is hardened if Bip32Utils.IsHardenedIndex(index): raise Bip32KeyError( "Public child derivation cannot be used to create a hardened child key" ) # Data for HMAC, same of __CkdPriv() for public child key data = self.PublicKey().RawCompressed().ToBytes() + index.to_bytes( 4, "big") # Get HMAC of data i_l, i_r = self.__HmacHalves(data) # Construct curve point i_l*G+K point = string_to_int( i_l) * generator_secp256k1 + self.m_ver_key.pubkey.point # Try to construct public key from the curve point try: k_i = ecdsa.VerifyingKey.from_public_point(point, curve=SECP256k1) except: raise Bip32KeyError( "Computed public child key is not valid, very unlucky index") # Construct and return a new Bip32 object return Bip32(secret=k_i, chain=i_r, depth=self.m_depth + 1, index=index, fprint=self.FingerPrint(), is_public=True, key_net_ver=self.m_key_net_ver)
def child_pub(self, index): if index >= 0x80000000: raise Exception("Cannot create hardened public key") data = self.get_public_key() + index.to_bytes(4, 'big') left, right = self.hmac(data) left_int = string_to_int(left) point = left_int * generator_secp256k1 + self.public_key.pubkey.point res = ecdsa.VerifyingKey.from_public_point(point, curve=SECP256k1) key = Key(secret=res, chain=right, level=self.level + 1, index=index.to_bytes(4, 'big'), fingerprint=self.fingerprint(), public=True) self.children.append(key) return key
def fromExtendedKey(xkey, public=False, testnet=False): """ Create a BIP32Key by importing from extended private or public key string If public is True, return a public-only key regardless of input type. """ # Sanity checks raw = check_decode(xkey, need_prefix=True) # Extract remaining fields # Python 2.x compatibility if isinstance(raw[5], int): depth = raw[5] else: depth = ord(raw[5]) fpr = raw[5:9] child = struct.unpack(">L", raw[9:13])[0] chain = raw[13:45] secret = raw[45:] # Extract private key or public key point if not public: secret = secret[1:] else: # Recover public curve point from compressed key # Python3 FIX lsb = secret[0] & 1 if isinstance(secret[0], int) else ord(secret[0]) & 1 x = string_to_int(secret[1:]) ys = (x**3 + 7) % FIELD_ORDER # y^2 = x^3 + 7 mod p y = sqrt_mod(ys, FIELD_ORDER) if y & 1 != lsb: y = FIELD_ORDER - y point = ecdsa.ellipticcurve.Point(SECP256k1.curve, x, y) secret = ecdsa.VerifyingKey.from_public_point(point, curve=SECP256k1) key = BIP32Key(secret=secret, chain=chain, depth=depth, index=child, fpr=fpr, public=public, testnet=testnet) if public: key = key.SetPublic() return key
data_pub, chain, k_priv, K_priv = bip32_key(Il, Ir, b'\x00', 0, b'\0\0\0\0') # chain m/0 ITERATE = 0 + BIP32_HARDEN # because chain m/0 i_str = struct.pack(">L", ITERATE) # for non-hardened derivation # data = data_pub + i_str # for hardened derivation data = b'\0' + k_priv.to_string() + i_str I = hmac.new(chain, data, hashlib.sha512).digest() Il, Ir = I[:32], I[32:] Il_int = string_to_int(Il) pvt_int = string_to_int(k_priv.to_string()) k_int = (Il_int + pvt_int) % CURVE_ORDER secret = (b'\0' * 32 + int_to_string(k_int))[-32:] depth = bytes([1]) #fingrprint: padx = (b'\0' * 32 + int_to_string(K_priv.pubkey.point.x()))[-32:] if K_priv.pubkey.point.y() & 1: ck = b'\3' + padx else: ck = b'\2' + padx fingerprint = hashlib.new('ripemd160', sha256(ck).digest()).digest()[:4] new_data_pub, new_chain, new_k_priv, new_K_priv = bip32_key( secret, Ir, depth, ITERATE, fingerprint)
def path_gen_keylist(master_cc, master_pk, master_pubkey, index_list, hardened_list, total_keys, address_type, testnet): depth = 1 inputs = [master_cc, master_pk, master_pubkey, b'\x00\x00\x00\x00'] for index_str in index_list: if depth == 1: getprint = Keylevel(inputs[0], inputs[1], inputs[2], int(index_str), hardened_list[depth], depth, inputs[3], address_type, testnet) inputs[3] = getprint.fprint() master_key_data = Keylevel(inputs[0], inputs[1], inputs[2], int(index_str), hardened_list[depth], depth, inputs[3], address_type, testnet) inputs = [ master_key_data.CKCpriv(), master_key_data.CKDpriv(), master_key_data.pubkey(), master_key_data.fprint() ] else: master_key_data = Keylevel(inputs[0], inputs[1], inputs[2], int(index_str), hardened_list[depth], depth, inputs[3], address_type, testnet) inputs = [ master_key_data.CKCpriv(), master_key_data.CKDpriv(), master_key_data.pubkey(), master_key_data.fprint() ] xprv = master_key_data.xprv() xpub = master_key_data.xpub() depth += 1 gen_fp = Keylevel(inputs[0], inputs[1], inputs[2], int(index_str), hardened_list[depth], depth, inputs[3], address_type, testnet) inputs[3] = gen_fp.fprint() key_index = 0 key_result = [] for key in range(0, total_keys): hardened_key = (hardened_list[depth]) index_key_data = Keylevel(inputs[0], inputs[1], inputs[2], key, hardened_key, depth, inputs[3], address_type, testnet) path_pubkey = index_key_data.pubkey() path_private = indv_priv_key(index_key_data.CKDpriv(), testnet) privatehex = index_key_data.CKDpriv().hex() if address_type == 'p2pkh': public = indv_P2PKH_pub_key(index_key_data.pubkey(), testnet) script_pub = p2pkh_script(index_key_data.pubkey()) elif address_type == 'p2sh': redeemscript = p2sh_redeemscript(index_key_data.pubkey()) public = indv_P2SH_pub_key(redeemscript, testnet) script_pub = p2sh_script(redeemscript) signscript = (bytes([len(redeemscript)]) + redeemscript).hex() elif address_type == 'p2wpkh-p2sh': public = indv_P2WPKH_P2SH_pub_key(index_key_data.pubkey(), testnet) script_pub = p2sh_script(index_key_data.pubkey()) redeemscript = p2wpkh_p2sh_redeemscript(index_key_data.pubkey()) signscript = ('1976a9' + redeemscript[6:] + '88ac') elif address_type == 'p2wpkh': public = indv_P2WPKH_pub_key(index_key_data.pubkey(), testnet) script_pub = p2wpkh_script(index_key_data.pubkey()) signscript = ('1976a9' + script_pub[4:] + '88ac') elif address_type == 'p2wsh': redeemscript = p2sh_redeemscript(index_key_data.pubkey()) public = indv_P2WSH_pub_key(redeemscript, testnet) script_pub = p2sh_script(index_key_data.pubkey()) signscript = (bytes([len(redeemscript)]) + redeemscript).hex() index_items = [str(item) for item in index_list] counter = 1 for item in hardened_list[1:]: if str(item) == 'True': index_items.insert(counter, "'") index_items.insert(counter + 1, "/") counter += 3 else: index_items.insert(counter, "/") counter += 2 derivation_path_text = "m/" + "".join(index_items[:-1]) script_to_sign_results = ['p2sh', 'p2wpkh-p2sh', 'p2wsh', 'p2wpkh'] if address_type in script_to_sign_results: result_text = 'XPRV=' + str(xprv, 'utf-8') + '\n' 'XPUB=' + str( xpub, 'utf-8' ) + '\n' + 'DERIVATION PATH=' + str( derivation_path_text ) + " -KEY INDEX=" + str(key_index) + ' HARDENED ADDRESS=' + str( hardened_list[-1:] ) + '\n' + 'privatekey=' + str( path_private, 'utf-8' ) + '\n' + 'Private hex=' + privatehex + '\n' + 'Private scalar=' + str( string_to_int(index_key_data.CKDpriv()) ) + '\n' + 'publickey=' + public + '\n' + 'public point=' + str( codecs.encode(path_pubkey, 'hex'), 'utf-8' ) + '\n' + 'Script Pubkey=' + script_pub + '\n' + 'Scriptpub to sign=' + signscript + '\n' # else: result_text = 'XPRV=' + str(xprv, 'utf-8') + '\n' 'XPUB=' + str( xpub, 'utf-8' ) + '\n' + 'DERIVATION PATH=' + str( derivation_path_text ) + " -KEY INDEX=" + str(key_index) + ' HARDENED ADDRESS=' + str( hardened_list[-1:] ) + '\n' + 'privatekey=' + str( path_private, 'utf-8' ) + '\n' + 'Private hex=' + privatehex + '\n' + 'Private scalar=' + str( string_to_int(index_key_data.CKDpriv()) ) + '\n' + 'publickey=' + public + '\n' + 'public point=' + str( codecs.encode(path_pubkey, 'hex'), 'utf-8') + '\n' + 'Script Pubkey=' + script_pub + '\n' # key_index += 1 key_result.append(result_text) return key_result