python - 从私钥计算压缩比特币地址
问题描述
我开始了解比特币,并想编写一个非常简单的程序,将私钥转换为公钥、密钥、地址等。但是,对于某些私钥,当我尝试为它们计算压缩地址时,它突然失败了。据我所知,它失败的原因是我传递给函数的压缩公钥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
解决方案
推荐阅读
- latex - LaTeX - 表格上的全宽行 - 占据多个单元格的单元格
- ruby - 这个带有 struct 的对象构造如何在内部工作?
- css - 公民:/scripting/lua/scheduler.lua:61:尝试调用一个零值(upvalue'fn')
- deployment - 我可以在 redshift 中使用 ADFS 用户作为超级用户吗?
- linux - 分析没有核心文件的分段错误
- optaplanner - 我们正在尝试为动物收容所构建一个简单的 OptaPlanner 解决方案,但效果不佳
- javascript - 未捕获的 ReferenceError:AI 未在 Object.play.AIPlay 中定义
- react-admin - 在 App.js 中访问 redux 存储中的值
- java - 使用 Java Swing GroupLayout 从 SQL 数据库创建数据表
- mysql - 如果时间戳不存在,Mysql Query 不返回值