如何解决从私钥计算压缩的比特币地址
我开始了解比特币,并想编写一个非常简单的程序,将私钥转换为公钥、密钥、地址等。但是,对于某些私钥,当我尝试为它们计算压缩地址时突然失败.据我所知,它失败的原因是我传递给函数 bitcoin.pubkey_to_address()
的压缩公钥太短了一位。由于它是最著名的比特币库之一,我认为我的理解存在根本性错误。因此,问题是:从私钥计算压缩的比特币地址时我做错了什么?
我已经安装了以下库:pip3 install pybitcointools
在下面的最小示例中导入为 bitcoin
,我在 Ubuntu 20.04 上使用 Python 3.8.5。
import bitcoin
class WalletWithBalance:
def __init__(self,_private_key: str):
self.private_key_uncompressed_hex: str = _private_key
# public keys:
self.public_key_uncompressed_as_x_y_tuple_hex = self.get_private_key_as_x_y_tuple()
self.public_key_compressed_hex = self.get_compressed_public_key_hex()
# addresses:
self.address_compressed = bitcoin.pubkey_to_address(self.public_key_compressed_hex)
def get_public_key_as_raw_hex_str(self):
public_key_as_raw_hex_str = bitcoin.encode_pubkey(self.public_key_uncompressed_as_x_y_tuple_hex,'hex')
return public_key_as_raw_hex_str
def get_private_key_as_x_y_tuple(self):
private_key_raw_decimal_number = bitcoin.decode_privkey(self.private_key_uncompressed_hex,'hex')
return bitcoin.fast_multiply(bitcoin.G,private_key_raw_decimal_number)
def get_compressed_public_key_hex(self):
(public_key_x,public_key_y) = self.public_key_uncompressed_as_x_y_tuple_hex
return self.get_compressed_prefix(public_key_y) + bitcoin.encode(public_key_x,16)
@staticmethod
def get_compressed_prefix(public_key_y):
if public_key_y % 2 == 0:
return "02"
else:
return "03"
if __name__ == "__main__":
wallet = WalletWithBalance(_private_key="0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c")
堆栈跟踪内容如下:
/usr/bin/python3 /foo/minimal_example.py
Traceback (most recent call last):
File "/foo/minimal_example.py",line 36,in <module>
wallet = WalletWithBalance(_private_key="0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c0c")
File "/foo/minimal_example.py",line 13,in __init__
self.address_compressed = bitcoin.pubkey_to_address(self.public_key_compressed_hex)
File "/DoeJohn/.local/lib/python3.8/site-packages/bitcoin/main.py",line 452,in pubkey_to_address
return bin_to_b58check(bin_hash160(pubkey),magicbyte)
File "/DoeJohn/.local/lib/python3.8/site-packages/bitcoin/main.py",line 334,in bin_hash160
intermed = hashlib.sha256(string).digest()
TypeError: Unicode-objects must be encoded before hashing
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。