TeachMeBitcoin

Custom Python Nonce Miner

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

Custom Python Nonce Brute-Forcer

In this final simulation for the Block Structure module, we will build a Proof of Work Miner. This script will iterate through the Nonce field to find a hash that meets a specific difficulty target.

The Python Nonce Miner

import hashlib
import time

def hash256(data):
    """Double-SHA256."""
    return hashlib.sha256(hashlib.sha256(data).digest()).digest()

def mine_block(header_prefix, target_hex):
    target = int(target_hex, 16)
    nonce = 0
    start_time = time.time()

    print(f"--- Mining Started ---")
    print(f"[*] Target: {target_hex}")

    while nonce < 2**32:
        # 1. Append nonce (4-byte little-endian) to header prefix
        # header_prefix is 76 bytes, nonce is 4 bytes = 80 byte header
        header = header_prefix + nonce.to_bytes(4, 'little')

        # 2. Hash
        block_hash = hash256(header)
        hash_val = int.from_bytes(block_hash, 'little')

        # 3. Check against target
        if hash_val < target:
            elapsed = time.time() - start_time
            print(f"\n[SUCCESS] Block Mined!")
            print(f"[*] Nonce: {nonce}")
            print(f"[*] Hash:  {block_hash[::-1].hex()}")
            print(f"[*] Time:  {elapsed:.2f} seconds")
            return nonce, block_hash

        # Status update every 1M hashes
        if nonce % 1000000 == 0 and nonce > 0:
            print(f"[*] Progress: {nonce/1000000:.0f}M hashes...")

        nonce += 1

    return None

# --- Simulation ---

# Mock 76-byte header (Version, PrevHash, Merkle, Time, Bits)
mock_header_prefix = b'\x02\x00\x00\x00' + b'\x00'*32 + b'\x00'*32 + b'\x64\xb0\x11\xc9' + b'\x2a\x6f\x06\x17'

# We will set a VERY EASY target for this simulation (4 leading hex zeroes)
easy_target = "0000ffff" + "f"*56 

mine_block(mock_header_prefix, easy_target)

How to Run the Simulator

  1. Ensure you have Python 3 installed.

  2. Copy the code into a file named nonce_miner.py.

  3. Run it using python3 nonce_miner.py.

Technical Takeaways

  1. Trial and Error: Notice how the script just blindly increments the number. There is no "strategy" to finding a hash; it is pure probability.

  2. The Target boundary: Even with a "very easy" target (4 hex zeroes), your CPU might take several seconds to find a solution. Real Bitcoin targets currently require ~20 hex zeroes!

  3. Little-Endian Nonce: The nonce.to_bytes(4, 'little') command is essential for creating a protocol-valid block header.

Congratulations! You have completed the Block Structure module. You now understand every single byte of the 80-byte header that secures the world's first decentralized financial system.

☕ Help support TeachMeBitcoin

TeachMeBitcoin is an ad-free, open-source educational repository curated by a passionate team of Bitcoin researchers and educators for public benefit. If you found our articles helpful, please consider supporting our hosting and ongoing content updates with a clean donation:

Ethereum: 0x578417C51783663D8A6A811B3544E1f779D39A85
Bitcoin: bc1q77k9e95rn669kpzyjr8ke9w95zhk7pa5s63qzz
Solana: 4ycT2ayqeMucixj3wS8Ay8Tq9NRDYRPKYbj3UGESyQ4J
Address copied to clipboard!