首页 > 解决方案 > 从私钥计算压缩比特币地址

问题描述

我开始了解比特币,并想编写一个非常简单的程序,将私钥转换为公钥、密钥、地址等。但是,对于某些私钥,当我尝试为它们计算压缩地址时,它突然失败了。据我所知,它失败的原因是我传递给函数的压缩公钥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

标签: pythoncryptographyblockchainbitcoinelliptic-curve

解决方案


推荐阅读