pycoin学习记录(3) hd钱包 bip32

from pycoin.ecdsa import public_pair_for_secret_exponent, generator_secp256k1
from pycoin.encoding import wif_to_secret_exponent, public_pair_to_bitcoin_address
from pycoin.key.BIP32Node import BIP32Node
from pycoin.serialize import h2b

master = BIP32Node.from_master_secret(h2b("000102030405060708090a0b0c0d0e0f"))
print(master.wallet_key(as_private=True))
#xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi

用root seed生成主私钥

m0p = master.subkey(is_hardened=True)
m0p_priv_wif = m0p.wallet_key(as_private=True)
print(m0p.wif())
#L5BmPijJjrKbiUfG4zbiFKNqkvuJ8usooJmzuD7Z8dkRoTThYnAT
print(m0p.bitcoin_address())
#19Q2WoS5hSS6T8GjhK8KZLMgmWaq4neXrh

强化派生出子私钥m/0p

pub_m0p = master.subkey(is_hardened=True, as_private=False)
print(pub_m0p.wallet_key())
#xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw

获得子公钥m/0p.pub

m0p1 = m0p.subkey(as_private=True,i=1)
pub_m0p1 = pub_m0p.subkey(i=1)
print(m0p1.bitcoin_address())
#1JQheacLPdM5ySCkrZkV66G2ApAXe1mqLj
print(pub_m0p1.bitcoin_address())
#1JQheacLPdM5ySCkrZkV66G2ApAXe1mqLj

继续派生出m/0p/1

print(master.subkey_for_path("0p/1").wallet_key() == m0p1.wallet_key())
#True
print(master.subkey_for_path("0p/1.pub").wallet_key() == pub_m0p1.wallet_key())
#True

当然是相等的。

_pub_m0p = BIP32Node.from_hwif("xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw")
print(master.subkey_for_path("0p/1/2").wallet_key())
#xpub6D4BDPcEgbv6wqbZ5Vfp1MUpa5tieyHKAoJCFjcUJpzSc9BV92TpCM85m3jfth6jfKA7LWFiip8zp8RuARjoLjkD13Z8cb9VdyMm3MMdTcA
print(_pub_m0p.subkey_for_path("1/2").wallet_key())
#xpub6D4BDPcEgbv6wqbZ5Vfp1MUpa5tieyHKAoJCFjcUJpzSc9BV92TpCM85m3jfth6jfKA7LWFiip8zp8RuARjoLjkD13Z8cb9VdyMm3MMdTcA
print(master.subkey_for_path("0p/1/2").wallet_key() == _pub_m0p.subkey_for_path("1/2").wallet_key())
#True

这是重点应用场景。将m/0p.pub部署出去,服务器获得扩展公钥后,派生出m/0p/1/2.pub;当想使用这个地址上的资金时,可以用主私钥派生出路径为m/0p/1/2的子私钥来使用这个地址上的资金

priv = master.subkey_for_path("0p/1/2/1").wif()
print(priv)
#L2g1UHRYrVStynDkML8R8YcKkXdC1B6M8sF6aDuaxf272kUK2zws
pub = _pub_m0p.subkey_for_path("1/2/1").bitcoin_address()
print(pub)
#1GtQRUwEKjpRocadTMZ3SnhmReUvHiwbJk

继续进行实验,获取m/0p/1/2/1的wif以及bitcoin address,注意子公钥是从m/0p.pub派生的

secret_exponent = wif_to_secret_exponent(priv)
public_point = public_pair_for_secret_exponent(generator_secp256k1, secret_exponent)
_pub = public_pair_to_bitcoin_address(public_point)
print(_pub)
#1GtQRUwEKjpRocadTMZ3SnhmReUvHiwbJk
print(_pub == pub)
#True

利用上一篇的知识,来验证下这个密钥对是否匹配,结果是匹配的。




你可能感兴趣的:(pycoin学习记录(3) hd钱包 bip32)