Post
Topic
Board Development & Technical Discussion
Re: I made my own code to Create your own Bitcoin address (Python)
by
Phobos_Quake
on 03/12/2024, 15:12:39 UTC
I have found an error with my code. The seed phrase had no connection with the private key, which it would make it impossible to restore it with the seed phrase it printed.
An AI search helped me detect it.

"Incorrect Derivation of the Master Key:
In BIP32, the master key is derived from the seed using HMAC-SHA512 with a specific key (b"Bitcoin seed"), not hashlib.pbkdf2_hmac as you are using.
Your code uses hashlib.pbkdf2_hmac to derive the master key, which is not part of the BIP32 standard.

Private Key Derivation:

The private key is not directly derived from the master key. Instead, BIP32 defines a hierarchical deterministic (HD) wallet structure where private keys are derived from the master key using child key derivation (CKD) functions.

Bech32 Address Generation:

The Bech32 address generation in your code is not following the correct derivation path. For a valid Bech32 address, you need to derive the public key from the private key and then hash it using SHA256 and RIPEMD-160 before encoding it into Bech32 format."

Here is the corrected code:

import hashlib
from mnemonic import Mnemonic
from bip32utils import BIP32Key
import bech32

# Input your entropy code
entropy_code = ""  # IMPORTANT: After running the program, erase your code
# Convert the entropy code to bytes
entropy = bytes.fromhex(entropy_code)

# Generate a BIP39 mnemonic phrase
mnemonic = Mnemonic("english")
words = mnemonic.to_mnemonic(entropy)  # 12-word phrase

# Derive a seed from the mnemonic phrase
seed = mnemonic.to_seed(words)

# Derive the master key from the seed using BIP32
bip32_master_key = BIP32Key.fromEntropy(seed)

# Get the private key (hexadecimal) from the master key
private_key = bip32_master_key.PrivateKey()

# Convert private key to WIF format
wif_private_key = bip32_master_key.WalletImportFormat()

# Derive the public key
public_key = bip32_master_key.PublicKey()

# Hash the public key to generate the Bech32 address
hashed_public_key = hashlib.new('ripemd160', hashlib.sha256(public_key).digest()).digest()

# Generate the Bech32 address
hrp = "bc"  # Human-readable part for Bitcoin mainnet addresses
witver = 0  # Witness version (0 for Pay-to-Witness-Public-Key-Hash addresses)
bech32_address = bech32.encode(hrp, witver, hashed_public_key)

# Print the Bitcoin private key (WIF format), mnemonic phrase, and Bech32 address
print("Bitcoin Private Key (WIF format):", wif_private_key)
print("Bitcoin Private Key (Hexadecimal):", private_key.hex())
print("BIP39 Mnemonic Phrase:", words)
print("Bech32 Address:", bech32_address)