I am attempting to put in writing a script that may generate a personal key and the compressed and uncompressed addresses. It appears to work nevertheless the personal key would not correspond to the addresses generated. Can not seem to discover the place I am going mistaken although…
import hashlib
import base58
import secrets and techniques
import ecdsa
# generate personal key utilizing safe random quantity generator
private_key = secrets and techniques.randbelow(2**256)
# convert personal key to hexadecimal format
private_key_hex = hex(private_key)[2:]
# generate public key utilizing personal key and Elliptic Curve Digital Signature Algorithm (ECDSA)
public_key = ecdsa.SigningKey.from_string(bytes.fromhex(private_key_hex), curve=ecdsa.SECP256k1).verifying_key
# convert public key to hexadecimal format
public_key_hex = public_key.to_string().hex()
# generate uncompressed bitcoin handle by hashing public key with SHA-256 and RIPEMD-160
uncompressed_address = hashlib.new('ripemd160', hashlib.sha256(bytes.fromhex(public_key_hex)).digest()).hexdigest()
# add prefix "00" to uncompressed handle to point it's an uncompressed handle
uncompressed_address = "00" + uncompressed_address
# generate checksum by hashing handle with SHA-256 twice
checksum = hashlib.sha256(hashlib.sha256(bytes.fromhex(uncompressed_address)).digest()).hexdigest()[:8]
# add checksum to handle
uncompressed_address += checksum
# encode handle in base58 format
uncompressed_address = base58.b58encode(bytes.fromhex(uncompressed_address))
# generate compressed bitcoin handle by including prefix "03" to public key whether it is odd, or "02" whether it is even
if public_key_hex[-1] in ["1", "3", "5", "7", "9", "b", "d", "f"]:
compressed_address = "03" + public_key_hex[:66]
else:
compressed_address = "02" + public_key_hex[:66]
# hash compressed handle with SHA-256 and RIPEMD-160
compressed_address = hashlib.new('ripemd160', hashlib.sha256(bytes.fromhex(compressed_address)).digest()).hexdigest()
# add prefix "00" to compressed handle to point it's a compressed handle
compressed_address = "00" + compressed_address
# generate checksum by hashing handle with SHA-256 twice
checksum = hashlib.sha256(hashlib.sha256(bytes.fromhex(compressed_address)).digest()).hexdigest()[:8]
# add checksum to handle
compressed_address += checksum
# encode handle in base58 format
compressed_address = base58.b58encode(bytes.fromhex(compressed_address))
print("Non-public key:", private_key_hex)
print("Uncompressed handle:", uncompressed_address)
print("Compressed handle:", compressed_address)
