How to make bitcoin compressed public key

40 views Asked by At

This is my code

from bitcoinlib.keys import PrivateKey
from bitcoinlib.encoding import pubkeyhash_to_addr

# Example WIF private key
wif_private_key = "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf"

# Decode the WIF private key to obtain the raw private key
raw_private_key = PrivateKey(wif=wif_private_key).to_hex()

# Derive the compressed public key from the raw private key
compressed_public_key = PrivateKey(raw=raw_private_key).public_key().to_hex(compressed=True)

# Generate the Bitcoin address from the compressed public key
compressed_address = pubkeyhash_to_addr(compressed_public_key)

print("Compressed Bitcoin Address:", compressed_address)

But output is

Traceback (most recent call last):
  File "C:\Users\Hp\Desktop\puzzle\a.py", line 1, in <module>
    from bitcoinlib.keys import PrivateKey
ImportError: cannot import name 'PrivateKey' from 'bitcoinlib.keys' (C:\Users\Hp\AppData\Local\Programs\Python\Python312\Lib\site-packages\bitcoinlib\keys.py)
1

There are 1 answers

0
Asif Iqbal On
import bitcoin

# Example WIF private key
wif_private_key = "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDf"

# Decode the WIF private key to obtain the raw private key
raw_private_key = bitcoin.decode_privkey(wif_private_key, 'hex')

# Derive the public key from the raw private key
uncompressed_public_key = bitcoin.privkey_to_pubkey(raw_private_key)

# Compress the public key
compressed_public_key = bitcoin.compress(uncompressed_public_key)

# Generate the compressed Bitcoin address from the compressed public key
compressed_address = bitcoin.pubkey_to_address(compressed_public_key)

print("Compressed Bitcoin Address:", compressed_address)