def bip32_root(seed, testnet=False): header_pub, header_priv = _get_headers(testnet) I = hmac.new("Bitcoin seed", seed, hashlib.sha512).digest() master_k = I[0:32] master_c = I[32:] K, cK = get_pubkeys_from_secret(master_k) xprv = (header_priv + "00" + "00000000" + "00000000").decode("hex") + master_c + chr( 0) + master_k xpub = (header_pub + "00" + "00000000" + "00000000").decode("hex") + master_c + cK return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
def xpub_from_pubkey(cK, testnet=False): header_pub, header_priv = _get_headers(testnet) assert cK[0] in ['\x02', '\x03'] master_c = chr(0) * 32 xpub = (header_pub + "00" + "00000000" + "00000000").decode("hex") + master_c + cK return EncodeBase58Check(xpub)
def xpub_from_xprv(xprv, testnet=False): depth, fingerprint, child_number, c, k = deserialize_xkey(xprv) K, cK = get_pubkeys_from_secret(k) header_pub, _ = _get_headers(testnet) xpub = header_pub.decode('hex') + chr( depth) + fingerprint + child_number + c + cK return EncodeBase58Check(xpub)
def bip32_private_derivation(xprv, branch, sequence, testnet=False): assert sequence.startswith(branch) if branch == sequence: return xprv, xpub_from_xprv(xprv, testnet) header_pub, header_priv = _get_headers(testnet) depth, fingerprint, child_number, c, k = deserialize_xkey(xprv) sequence = sequence[len(branch):] for n in sequence.split('/'): if n == '': continue i = int(n[:-1]) + BIP32_PRIME if n[-1] == "'" else int(n) parent_k = k k, c = CKD_priv(k, c, i) depth += 1 _, parent_cK = get_pubkeys_from_secret(parent_k) fingerprint = hash_160(parent_cK)[0:4] child_number = ("%08X" % i).decode('hex') K, cK = get_pubkeys_from_secret(k) xprv = header_priv.decode('hex') + chr(depth) + fingerprint + child_number + c + chr(0) + k xpub = header_pub.decode('hex') + chr(depth) + fingerprint + child_number + c + cK return EncodeBase58Check(xprv), EncodeBase58Check(xpub)
def parse_xpubkey(cls, pubkey): assert is_extended_pubkey(pubkey) pk = pubkey.decode('hex') pk = pk[1:] xkey = EncodeBase58Check(pk[0:78]) dd = pk[78:] s = [] while dd: n = int(rev_hex(dd[0:2].encode('hex')), 16) dd = dd[2:] s.append(n) assert len(s) == 2 return xkey, s
def bip32_public_derivation(xpub, branch, sequence, testnet=False): header_pub, _ = _get_headers(testnet) depth, fingerprint, child_number, c, cK = deserialize_xkey(xpub) assert sequence.startswith(branch) sequence = sequence[len(branch):] for n in sequence.split('/'): if n == '': continue i = int(n) parent_cK = cK cK, c = CKD_pub(cK, c, i) depth += 1 fingerprint = hash_160(parent_cK)[0:4] child_number = ("%08X" % i).decode('hex') xpub = header_pub.decode('hex') + chr(depth) + fingerprint + child_number + c + cK return EncodeBase58Check(xpub)
def SecretToASecret(secret, compressed=False, addrtype=0): vchIn = chr((addrtype + 128) & 255) + secret if compressed: vchIn += '\01' return EncodeBase58Check(vchIn)