0

How to properly implement key derivation in bip32, bip44, etc.? I get it right to generate the parent extended key, but then I can’t get the correct keys, they do not match the "Test Vectors" specified in the specification.

    xprv = "0488ade4"
    xpub = "0488b21e"

    x = hmac.new("Bitcoin seed".encode('utf-8'), bytes.fromhex("000102030405060708090a0b0c0d0e0f"),
                 hashlib.sha512).digest()
    master_private_key = x[0:32]
    master_chain_code = x[32:64]

    x_private_key = bytes.fromhex(xprv) + \
        (bytes.fromhex("000000000000000000")) + master_chain_code + b'\x00' + master_private_key

    double_hash = bytes.fromhex(sha256(bytes.fromhex(sha256(x_private_key).hexdigest())).hexdigest())
    x_private_key = x_private_key + double_hash[0:4]

    mpk = int.from_bytes(master_private_key, byteorder='big')
    private_key = ecdsa.SigningKey.from_secret_exponent(mpk, curve=ecdsa.SECP256k1)
    private_key_bytes = private_key.to_string()

    verifying_key = private_key.get_verifying_key()
    public_key_compressed_bytes = verifying_key.to_string("compressed")

    x_public_key = bytes.fromhex(xpub) + \
        (b'\x00' * 9) + master_chain_code + bytes.fromhex(public_key_compressed_bytes.hex())

    double_hash = bytes.fromhex(sha256(bytes.fromhex(sha256(x_public_key).hexdigest())).hexdigest())
    x_public_key = x_public_key + double_hash[0:4]

    print("x_private_key: ", base58.b58encode(x_private_key).decode())
    print("x_public_key: ", base58.b58encode(x_public_key).decode())

This code works as expected and outputs the correct keys. But I can't figure out how to do treeing with "m/0" path and so on. Someone can help me with this?

This is how I try to get the child key

    i = 0
    cx = hmac.new(master_chain_code, master_private_key + i.to_bytes(4, "big"), hashlib.sha512).digest()
    cx_private_key = (cx[:32])
    cx_chain_code = cx[32:]

    h = hashlib.new('ripemd160')
    h.update(sha256(public_key_compressed_bytes).digest())
    fingerprint = h.digest()

    c_key = bytes.fromhex(xprv) + \
        b'\x01' + \
        fingerprint[:4] + \
        b'\x00\x00\x00\x00' + \
        cx_chain_code + \
        b'\x00' + \
        cx_private_key

    double_hash = bytes.fromhex(sha256(bytes.fromhex(sha256(c_key).hexdigest())).hexdigest())
    c_key = c_key + double_hash[0:4]
    print("children_private_key: ", base58.b58encode(c_key).decode())

0 Answers0