pycoin学习记录(2) 生成 bitcoin address

from pycoin import encoding
from pycoin.ecdsa import public_pair_for_secret_exponent, generator_secp256k1
from pycoin.serialize import h2b

is_compressed = False

secret_exponent = 0x3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6
wif = encoding.secret_exponent_to_wif(secret_exponent, compressed=is_compressed)
print(wif)
#5JG9hT3beGTJuUAmCQEmNaxAuMacCTfXuw1R3FCXig23RQHMr4K

任选一随机数作为私钥,并得到其wif格式表示

public_point = public_pair_for_secret_exponent(generator_secp256k1, secret_exponent)
print(public_point)
#(41637322786646325214887832269588396900663353932545912953362782457239403430124, 16388935128781238405526710466724741593761085120864331449066658622400339362166)

得到公钥,即椭圆曲线上的一对点

sec = encoding.public_pair_to_sec(public_point, compressed=is_compressed)
print(sec)
#b'\x04\\\r\xe3\xb9\xc8\xab\x18\xdd\x04\xe3Q\x12C\xec)R\x00-\xbf\xad\xc8d\xb9b\x89\x10\x16\x9d\x9b\x9b\x00\xec$;\xce\xfd\xd44pt\xd4K\xd75mjS\xc4\x95s}\xd9b\x95\xe2\xa97K\xf5\xf0.\xbf\xc1v'

public_point_change_back = encoding.sec_to_public_pair(sec, strict=False)#strict意义不明
print(public_point_change_back == public_point)
#True

hash160_sec = encoding.public_pair_to_hash160_sec(public_point, compressed=is_compressed)
print(hash160_sec)
#b'\t\xc6\xe7\x11\x18\xd8\xf1+\xeck\\a\x88K5g|\n\n\xe3'

讲公钥通过一系列哈希变换为长度为20字节的公钥哈希

bitcoin_address =encoding.hash160_sec_to_bitcoin_address(hash160_sec)
print(bitcoin_address)
#1thMirt546nngXqyPEz532S8fLwbozud8

testnet_bitcoin_address = encoding.hash160_sec_to_bitcoin_address(hash160_sec, address_prefix=h2b('6F'))
print(testnet_bitcoin_address)
#mgQeemwrt5Y3Zo1TgxDMtxEkzeweW3gXAg

将公钥哈希,根据不同的prefix,生成不同类型的地址,上面为比特币mainnet地址,下面为比特币测试网络地址


将脚本的is_compressed设置为True,可观察到压缩格式下的地址。




你可能感兴趣的:(杂项)