TeachMeBitcoin

Custom Python Chain Linker

From TeachMeBitcoin, the free encyclopedia Reading time: 2 min

Custom Python Chain Linker

In this simulation, we will verify the cryptographic integrity of a "Mini-Blockchain." We will use a script to ensure that each block correctly references its parent's Double-SHA256 Hash and identify if a link has been broken.

The Python Chain Linker Script

import hashlib

def calculate_block_hash(header_data):
    """Performs Double-SHA256 hashing on header data."""
    first_pass = hashlib.sha256(header_data.encode('utf-8')).digest()
    second_pass = hashlib.sha256(first_pass).digest()
    return second_pass.hex()

class BlockHeader:
    def __init__(self, height, prev_hash, data):
        self.height = height
        self.prev_hash = prev_hash
        self.data = data
        self.hash = calculate_block_hash(f"{height}{prev_hash}{data}")

def verify_chain(chain):
    print(f"--- Verifying Chain Integrity (Length: {len(chain)}) ---")

    for i in range(1, len(chain)):
        current = chain[i]
        parent = chain[i-1]

        print(f"[*] Checking Block {current.height} -> Parent {parent.height}...")

        # Verify the link
        if current.prev_hash == parent.hash:
            print(f"    [OK] Link valid. Parent hash matches.")
        else:
            print(f"    [!!] ERROR: Broken link at Block {current.height}!")
            print(f"         Expected: {parent.hash[:16]}...")
            print(f"         Found:    {current.prev_hash[:16]}...")
            return False

    print("\n[SUCCESS] Chain is cryptographically secure and immutable.")
    return True

# --- Simulation ---

# 1. Create a valid chain
genesis = BlockHeader(0, "0"*64, "Genesis Data")
block1 = BlockHeader(1, genesis.hash, "Transaction Data 1")
block2 = BlockHeader(2, block1.hash, "Transaction Data 2")

blockchain = [genesis, block1, block2]

# 2. Verify valid chain
verify_chain(blockchain)

# 3. Simulate an "Attack" (Modifying Block 1)
print("\n--- ATTACK: Modifying Block 1 Data ---")
block1.data = "FRAUDULENT_DATA"
# Note: The attacker doesn't update the hash of block1 or the prev_hash of block2
verify_chain(blockchain)

How to Run the Simulator

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

Technical Takeaways

  1. Strict Verification: The verify_chain function mimics how a Bitcoin full node audits the header chain. It doesn't trust the block height; it verifies the cryptographic proof of the previous link.
  2. Immutability in Action: As soon as we modified block1.data, the link between Block 1 and Block 2 became invalid. To "fix" the chain, the attacker would have to re-calculate block1.hash and then update the prev_hash of block2, which would change block2.hash, and so on.
  3. The Zero Hash: The simulation starts with 0*64, representing the Genesis Anchor.

Congratulations! You have mastered the Previous Block Header module. You now understand the "Chain" in Blockchain at a fundamental level.

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