'Compute compressed bitcoin address from private key
I am starting to get an overview about bitcoin and wanted to write a very simple programme converting private keys into public, keys, addresses etc. However, for some private keys it suddenly fails when I try to compute the compressed address for them. The reason it fails as far as I can see is that the compressed public key I am passing to the function bitcoin.pubkey_to_address() is one digit too short. As it is one of the most famous bitcoin libraries I assume that there is a fundamental error in my understanding. Thus, the question: what am I doing wrong in computing the compressed bitcoin address from a private key?
I have installed the following library: pip3 install bitcoin in the minimal example below, I am using Python 3.8.5 on Ubuntu 20.04.
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")
The stacktrace reads:
/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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
