如何生成比特币压缩公钥?代码导入PrivateKey时遇ImportError
解决bitcoinlib导入PrivateKey的ImportError问题
用户代码:
from bitcoinlib.keys import PrivateKey from bitcoinlib.encoding import pubkeyhash_to_addr # Example WIF private key wif_private_key = "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf" # Decode the WIF private key to obtain the raw private key raw_private_key = PrivateKey(wif=wif_private_key).to_hex() # Derive the compressed public key from the raw private key compressed_public_key = PrivateKey(raw=raw_private_key).public_key().to_hex(compressed=True) # Generate the Bitcoin address from the compressed public key compressed_address = pubkeyhash_to_addr(compressed_public_key) print("Compressed Bitcoin Address:", compressed_address)
运行报错:
Traceback (most recent call last): File "C:\Users\Hp\Desktop\puzzle\a.py", line 1, in <module> from bitcoinlib.keys import PrivateKey ImportError: cannot import name 'PrivateKey' from 'bitcoinlib.keys' (C:\Users\Hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\bitcoinlib\keys.py)
解决方案
1. 适配新版本bitcoinlib API
bitcoinlib 0.11及以上版本重构了密钥类,PrivateKey已被整合到Key类中,修改代码如下:
from bitcoinlib.keys import Key from bitcoinlib.encoding import pubkeyhash_to_addr wif_private_key = "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf" # 直接用Key类加载WIF私钥,无需额外转换原始私钥 key = Key(wif_private_key) # 获取压缩公钥十六进制字符串 compressed_public_key = key.public_key().to_hex(compressed=True) # 生成对应压缩地址 compressed_address = pubkeyhash_to_addr(key.public_hash(compressed=True)) print("Compressed Bitcoin Address:", compressed_address)
2. 降级到旧版本(兼容原代码)
如果不想修改代码,可以安装0.10.1版本的bitcoinlib,这是仍保留PrivateKey类的最后一个版本:
pip uninstall bitcoinlib -y pip install bitcoinlib==0.10.1
安装完成后,原代码即可直接运行。
内容的提问来源于stack exchange,提问作者Asif Iqbal
相关产品推荐
相关产品推荐

