如何在bip32、bip44等中正确实现密钥派生?

问题描述 投票:0回答:1

如何在bip32、bip44等中正确实现密钥派生?我正确地生成了父扩展密钥,但随后我无法获得正确的密钥,它们与规范中指定的“测试向量”不匹配。

    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())

此代码按预期工作并输出正确的密钥。但我不知道如何使用“m/0”路径进行树化等等。有人可以帮我解决这个问题吗?

这就是我尝试获取子密钥的方法

    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())
python bitcoin ecdsa ripemd bip32
1个回答
0
投票

您可以在实现 BIP-32、BIP-39 和 BIP-44 的流行 Python 库中检查它是如何完成的。以下是如何使用 BIP-32 的说明:

https://github.com/ebellocchia/bip_utils/blob/master/readme/bip32.md

实现派生的类是:https://github.com/ebellocchia/bip_utils/blob/master/bip_utils/bip/bip32/slip10/bip32_slip10_key_derivator.py

© www.soinside.com 2019 - 2024. All rights reserved.