def serialize_xpub(k): b = b'' b += HD_HEADER_PUBLIC b += convert.int_to_byte(k['depth']) b += k['fingerprint'] b += convert.int_to_bytes(k['i'], 4) b += k['chaincode'] b += ecdsa.serialize_pub(k['pub']) return convert.bytes_to_b58check(b)
def serialize_xpriv(k): b = b'' b += HD_HEADER_PRIVATE b += convert.int_to_byte(k['depth']) b += k['fingerprint'] b += convert.int_to_bytes(k['i'], 4) b += k['chaincode'] b += b'\x00' + ecdsa.serialize_priv(k['priv']) return convert.bytes_to_b58check(b)
def derive_xpriv(k, i): i = int(i) pub = ecdsa.priv_to_pub(k['priv']) pub_ser = ecdsa.serialize_pub(pub) priv_ser = ecdsa.serialize_priv(k['priv']) if i >= 2**31: hmacdata = b'\x00' + priv_ser + convert.int_to_bytes(i, 4) else: hmacdata = pub_ser + convert.int_to_bytes(i, 4) I = hmac.new(k['chaincode'], hmacdata, hashlib.sha512).digest() return { 'depth': k['depth'] + 1, 'fingerprint': hashes.hash160(pub_ser)[:4], 'i': i, 'chaincode': I[32:], 'priv': ec.add_scalar(k['priv'], ecdsa.deserialize_priv(I[:32])) }
def derive_xpub(k, i): i = int(i) if i >= 2**31: raise Exception("Can't do private derivation on public key!") pub = k['pub'] pub_ser = ecdsa.serialize_pub(pub) hmacdata = pub_ser + convert.int_to_bytes(i, 4) I = hmac.new(k['chaincode'], hmacdata, hashlib.sha512).digest() return { 'depth': k['depth'] + 1, 'fingerprint': hashes.hash160(pub_ser)[:4], 'i': i, 'chaincode': I[32:], 'pub': ec.add(k['pub'], ecdsa.priv_to_pub(ecdsa.deserialize_priv(I[:32]))) }
def serialize_pub(pub, compressed=True): if compressed: return convert.int_to_byte(2 + (pub[1] % 2)) + convert.int_to_bytes(pub[0], 32) else: return b"\x04" + convert.int_to_bytes(pub[0], 32) + convert.int_to_bytes(pub[1], 32)
def serialize_priv(priv): assert isinstance(priv, int) return convert.int_to_bytes(priv, 32)