TeachMeBitcoin

Custom Python Fork Validator

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

Custom Python Fork Validator

In this simulation, we will program a simplified Bitcoin node that enforces a strict 1MB block size rule. We will then simulate a Hard Fork by attempting to process a 2MB block and observe how the node protects the consensus.

The Python Validator Script

import hashlib
import time

class Block:
    def __init__(self, index, data, previous_hash, size_mb):
        self.index = index
        self.timestamp = time.time()
        self.data = data
        self.size_mb = size_mb
        self.previous_hash = previous_hash
        self.hash = self.calculate_hash()

    def calculate_hash(self):
        sha = hashlib.sha256()
        sha.update(str(self.index).encode('utf-8') +
                   str(self.timestamp).encode('utf-8') +
                   str(self.data).encode('utf-8') +
                   str(self.size_mb).encode('utf-8') +
                   str(self.previous_hash).encode('utf-8'))
        return sha.hexdigest()

class Node:
    def __init__(self, name, max_block_size):
        self.name = name
        self.max_block_size = max_block_size  # Consensus Rule
        self.chain = []
        print(f"[*] Node '{self.name}' initialized with {self.max_block_size}MB limit.")

    def add_block(self, new_block):
        # 1. Check if block size exceeds consensus rules
        if new_block.size_mb > self.max_block_size:
            print(f"[!] REJECTED: Block {new_block.index} size ({new_block.size_mb}MB) "
                  f"exceeds limit ({self.max_block_size}MB). Consensus Failure!")
            return False

        # 2. Add to chain
        self.chain.append(new_block)
        print(f"[+] ACCEPTED: Block {new_block.index} added. Hash: {new_block.hash[:16]}...")
        return True

# --- Simulation ---

# 1. Initialize an 'Old Rule' node (1MB limit)
honest_node = Node("Bitcoin Core 0.14", max_block_size=1.0)

# 2. Simulate valid blocks
genesis = Block(0, "Genesis", "0", 0.1)
honest_node.add_block(genesis)

block1 = Block(1, "TX_DATA_1", genesis.hash, 0.8)
honest_node.add_block(block1)

# 3. Simulate a Hard Fork Block (2MB)
print("\n--- ATTACK: A miner attempts a Hard Fork ---")
fork_block = Block(2, "BIG_TX_DATA", block1.hash, 2.0)
success = honest_node.add_block(fork_block)

if not success:
    print("\n[*] RESULT: The node ignored the fork and stayed on the original chain.")
    print(f"[*] Chain Height: {len(honest_node.chain)}")

How to Run the Simulator

  1. Ensure you have Python 3 installed.
  2. Copy the code into a file named fork_sim.py.
  3. Run it using python3 fork_sim.py.

Technical Takeaways

  1. Rule Enforcement: The Node class acts as a consensus validator. It doesn't care if a miner spent energy on a block; if the block size is 2MB, it is invalid.
  2. Partitioning: If other nodes upgrade to 2MB, they will accept the block. Our node will be "partitioned" from them, creating a Chain Split.
  3. Security via Incompatibility: This rejection is exactly how Bitcoin prevents unwanted protocol changes. Even if 99% of miners hash the 2MB block, the 1MB node will simply wait for a valid 1MB block, ignoring the miners entirely.

Congratulations! You have completed the Hard Fork module. You now understand the deep technical and economic mechanics that keep Bitcoin's rules set in stone.

☕ 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!