← Course home Module 4 / 19
Blockchain Part 1
Module 4

Decentralisation & Proof of Work

From one laptop to ten thousand strangers — how a network of untrusting computers agrees on a single truth.

The Problem: One Computer Isn't Enough

In Module 3, you built a complete cryptocurrency — wallets, signed transactions, blocks, and chain validation. But all of it ran on a single machine. If that computer crashes, gets hacked, or its owner decides to cheat, the entire system dies. Centralisation is the bottleneck.

🧠

The Big Question

How can thousands of computers — owned by strangers who don't trust each other — agree on the exact same transaction history, without any central authority?

This is the Byzantine Generals' Problem applied to money. Some generals (nodes) may be traitors (malicious). The loyal generals must still reach agreement. Satoshi's answer: make lying more expensive than cooperating.

🏛️

Centralised

One server holds the truth. Fast but fragile — single point of failure, censorship, trust required.

🕸️

Decentralised

Many independent nodes each hold a full copy. No single point of failure, but they must agree.

🌐

Distributed

Nodes spread across the globe, communicating peer-to-peer. Bitcoin is both decentralised and distributed.

Aspect Centralised (Visa) Decentralised (Bitcoin)
Copies of ledger 1 (master database) ~60,000+ full nodes
Who validates? The company Anyone running a node
Trust model Trust the institution Trust the protocol (math)
Single point of failure? Yes — server down = network down No — thousands of independent copies
Can censor? Yes — can freeze accounts No — permissionless by design

Peer-to-Peer Networks

In a traditional client-server model, you connect to a central server (think Google, Netflix). In a peer-to-peer (P2P) network, every participant is both a client and a server. There's no boss, no headquarters, no "main" computer.

🕸️

Anatomy of a Bitcoin Node

A full node stores the entire blockchain (~600 GB as of 2024), validates every transaction and block independently, and relays valid data to its peers. No permission needed — anyone can run one.

Component
Role
Blockchain copy
Every block since Genesis (Jan 3, 2009) — your personal copy of the truth
Mempool
Waiting room for unconfirmed transactions — validated but not yet in a block
Peer list
Typically 8–125 outbound connections to other nodes — discovered via DNS seeds
Validation engine
Checks every rule: valid signatures, correct PoW, no double-spends, proper block structure
UTXO set
Index of all unspent outputs — fast balance lookups without scanning entire chain

🖥️ Node Types

  • Full node: Downloads and validates everything. The backbone of the network (~60,000 reachable as of 2024).
  • Mining node: Full node + competes to create new blocks. Burns electricity to earn rewards.
  • SPV / Light node: Only downloads block headers. Trusts full nodes for tx verification. Used in mobile wallets.
  • Archival node: Full node that keeps all historical states (not just UTXO set). Used by explorers.
🔑

Key Insight

Running a full node means you trust nobody. Your node independently verifies every rule. You don't ask anyone "is this block valid?" — you compute the answer yourself. That's what "trustless" really means.

The Gossip Protocol

How does a new transaction or block reach every node on the planet in seconds? Through gossip — the same way rumours spread in a school. A node hears something new, checks it, and tells all its friends. They tell their friends. Within seconds, the entire network knows.

📡

How Gossip Works

  1. Alice broadcasts a signed transaction to her connected peers (e.g., 8 nodes).
  2. Each peer validates it independently — signature OK? Sufficient funds? Not a duplicate?
  3. If valid, the peer adds it to its mempool and forwards it to its peers.
  4. Invalid? The message is silently dropped. Misbehaving peers may get disconnected.
  5. Within ~2–5 seconds, the transaction reaches most of the network's ~60,000 nodes.
Alice t=0s A B C D E F G H I ~60,000 nodes ~3s ~0.5s ~1.5s ~3s

🤔 Why Gossip?

  • No single broadcaster — no server to DDoS or shut down.
  • Exponential spread — each hop multiplies reach. 8 peers → 64 → 512 → entire network in seconds.
  • Built-in validation — each node checks before forwarding. Invalid data dies immediately.
  • Redundancy — a node receives the same transaction from multiple peers. If one connection fails, others still deliver.
⚠️

Flood Protection

To prevent spam, nodes enforce rules: minimum transaction fees (to make spam expensive), maximum block sizes, rate-limiting per peer, and banning peers that send invalid data. Without these guardrails, an attacker could flood the mempool with millions of fake transactions.

Nakamoto Consensus

Every node has a copy of the blockchain. If two miners find valid blocks at nearly the same time, which block "wins"? Bitcoin's answer is elegantly simple — and it changed computer science forever.

⚖️

The Three Rules

  1. Longest chain wins. The chain with the most cumulative proof of work is the valid one. Nodes always follow the heaviest chain.
  2. Mining = voting with electricity. You can't fake votes — each block costs real energy. The more hashpower behind a chain, the more "votes" it has.
  3. Probabilistic finality. A transaction isn't "proven forever" but becomes exponentially harder to reverse with each new block on top. After 6 confirmations, reversal is practically impossible.
0 confirmations
In mempool — not yet mined
1 confirmation
Mined — could still be orphaned
3 confirmations
Safe for small payments
6 confirmations
Standard — practically irreversible

Difficulty Adjustment

Bitcoin targets one block every ~10 minutes. But hashpower fluctuates as miners join and leave. How does the network adapt?

🎛️

The Difficulty Adjustment Algorithm

Every 2,016 blocks (~2 weeks), the network recalculates difficulty. If blocks came too fast (average < 10 min), difficulty increases. Too slow? It decreases. This ensures consistent block times regardless of how many miners participate.

Target 1 block every ~10 min
Adjustment window Every 2,016 blocks (~2 weeks)
Formula new_target = old_target × (actual_time / expected_time)
Safety cap Max 4× increase or ¼× decrease per period

⏱️ Why 10 Minutes?

  • Propagation time. It takes ~2–5 seconds for a block to reach most nodes. 10 minutes gives ample time for the network to sync before the next block.
  • Fork minimisation. Shorter intervals would cause more accidental forks (two miners finding blocks simultaneously).
  • Security margin. Longer confirmation times give honest miners more time to outpace attackers.

Forks & Resolution

Two miners in different parts of the world find valid blocks at nearly the same moment. Some nodes see Block A first, others see Block B. The chain has temporarily forked. This is normal and happens regularly.

🔀

Natural Fork (Stale Blocks)

Both branches are valid. Nodes keep whichever they heard first and continue mining on that tip. As soon as one branch gets a second block, it becomes longer — and all nodes switch to the longer chain. The shorter branch (and its "stale block") is discarded. Transactions in the stale block return to the mempool.

Block 99
Block 100-A Miner Tokyo
Block 101 ✓ Longer!
Block 100-B Miner London
✗ Orphaned

Types of Forks

🔀

Natural Fork

Two miners find blocks simultaneously. Resolves automatically within 1–2 blocks. Happens every few days.

🔧

Soft Fork

Backwards-compatible rule tightening. Old nodes still accept new blocks. Example: SegWit (2017).

💥

Hard Fork

Incompatible rule change. Splits the network permanently. Example: Bitcoin Cash (Aug 2017) increased block size from 1 MB to 8 MB.

🔄 Chain Reorganisation (Reorg)

  • When a node discovers a longer valid chain, it rewinds its local chain and replays the longer one.
  • Transactions from the abandoned branch are returned to the mempool (if still valid).
  • Deep reorgs (more than 1–2 blocks) are extremely rare in practice — they require massive hashpower.
  • This is why exchanges wait for 6 confirmations before crediting deposits.

Attack Vectors

A decentralised network must withstand adversaries. Understanding attack vectors isn't just academic — it reveals why each design decision exists.

☠️

The 51% Attack

If an attacker controls more than 50% of the total hashpower, they can outpace the honest chain and rewrite history. They could double-spend: send coins to a merchant, wait for confirmation, then privately mine a longer chain that omits that transaction — effectively "taking back" the payment.

1
Send & Confirm

Attacker sends 100 BTC to a merchant. Honest network mines it into a block. Merchant sees 1 confirmation and ships goods.

2
Secret Mining

Meanwhile, attacker has been privately mining an alternative chain that does not include the 100 BTC transaction. With >50% hashpower, this secret chain grows faster.

3
Broadcast

Once the secret chain is longer, attacker broadcasts it. All nodes switch to the longer chain (Nakamoto consensus). The merchant's payment vanishes — the attacker keeps both the goods and the coins.

💰 What Would 51% Cost?

  • Bitcoin's hashrate is hundreds of EH/s as of 2024. You'd need majority of that — meaning millions of specialised ASIC machines.
  • Estimated cost: billions of dollars in hardware alone, plus electricity costs of millions per day.
  • Even if you succeeded, the attack would crash BTC price — destroying the value of the coins you stole.
  • Game theory: With $10B in mining gear, you'd earn more by mining honestly than by attacking.

Other Attack Vectors

🔁

Double-Spend

Send same coins twice. Solved by waiting for confirmations. 6 blocks makes this practically impossible.

🌊

Eclipse Attack

Isolate a node by controlling all its connections. The node sees only attacker-crafted data. Mitigated by diverse peer selection.

🗑️

Selfish Mining

Withhold found blocks to gain strategic advantage. Requires ~33% hashpower. Bitcoin protocol updates have reduced its effectiveness.

📧

Sybil Attack

Create thousands of fake nodes. In Bitcoin, this is useless — influence comes from hashpower (electricity), not node count.

🛡️

Defence in Depth

Bitcoin's security isn't any single mechanism — it's the combination: proof of work makes lying expensive, gossip makes censorship hard, economic incentives make honesty profitable, and 6 confirmations make double-spends impractical. Each layer reinforces the others.

Code: Simulating a P2P Network

Let's build a simplified peer-to-peer network where multiple nodes share blocks and resolve forks. We'll use our Blockchain class from Module 3 and add networking logic on top.

Node.js: A Simple Node

node.js Node.js
class P2PNode {
  constructor(name, difficulty = 2) {
    this.name       = name;
    this.blockchain = new Blockchain(difficulty);
    this.peers      = [];      // connected nodes
    this.mempool    = [];      // pending transactions
  }

  // Connect two nodes (bidirectional)
  connect(peer) {
    if (!this.peers.includes(peer)) {
      this.peers.push(peer);
      peer.peers.push(this);
    }
  }

  // Gossip: broadcast a transaction to all peers
  broadcastTransaction(tx) {
    for (const peer of this.peers) {
      if (!peer.mempool.find(t => t === tx)) {
        peer.receiveTx(tx);
      }
    }
  }

  // Receive a transaction from a peer
  receiveTx(tx) {
    if (tx.isValid() && !this.mempool.includes(tx)) {
      this.mempool.push(tx);
      this.broadcastTransaction(tx); // gossip forward
    }
  }

  // Mine pending transactions and broadcast the new block
  mine(minerAddress) {
    this.blockchain.minePendingTransactions(minerAddress);
    const latest = this.blockchain.getLatestBlock();
    this.mempool = [];
    this.broadcastBlock(latest);
  }

  // Send new block to peers (they decide whether to accept)
  broadcastBlock(block) {
    for (const peer of this.peers) {
      peer.receiveBlock(block, this);
    }
  }

  // Longest chain rule: accept block only if it extends a valid longer chain
  receiveBlock(block, sender) {
    if (sender.blockchain.chain.length > this.blockchain.chain.length) {
      if (sender.blockchain.isValid()) {
        console.log(`${this.name}: Adopting longer chain from ${sender.name}`);
        this.blockchain.chain = [...sender.blockchain.chain];
      }
    }
  }
}

Node.js: Longest Chain Resolution

longest-chain.js Node.js
// Create three nodes
const tokyo  = new P2PNode('Tokyo');
const london = new P2PNode('London');
const nyc    = new P2PNode('NYC');

// Connect them in a triangle
tokyo.connect(london);
london.connect(nyc);
nyc.connect(tokyo);

// Tokyo mines two blocks
tokyo.mine('tokyo-address');
tokyo.mine('tokyo-address');

// London and NYC adopted Tokyo's longer chain
console.log('Tokyo blocks:',  tokyo.blockchain.chain.length);
console.log('London blocks:', london.blockchain.chain.length);
console.log('NYC blocks:',    nyc.blockchain.chain.length);
// All should be 3 (genesis + 2 mined)
💡

Simplifications vs. Reality

  • Real Bitcoin uses TCP connections, binary message format, and handshake protocols. Our code uses direct function calls.
  • Real syncing downloads blocks one-by-one with getblocks / inv / getdata messages. We copy the entire chain at once.
  • Real validation checks block headers, Merkle roots, timestamps, and cumulative difficulty — not just chain length.
  • But the core principle is exactly the same: longest valid chain wins, gossip spreads data, each node validates independently.

Exercise: Network Simulation

Build a multi-node network and experiment with consensus, forks, and attacks. Work through the exercises in order — each one builds on the last.

📝

Setup

Use the Playground link below which includes all classes from Module 3 plus the P2PNode wrapper. Or add the P2PNode class to your existing project files from Module 3.

Playground Open the full P2P template in the Node.js Playground

Exercises

  1. Build a network: Create 5 nodes (Tokyo, London, NYC, Sydney, São Paulo) and connect them in a ring topology: Tokyo→London→NYC→Sydney→São Paulo→Tokyo. Mine 3 blocks on Tokyo. Do all nodes agree on the chain length?
  2. Simulate a fork: Disconnect Tokyo from the others. Mine 2 blocks on Tokyo and 1 block on London (separately). Now reconnect them. Which chain wins? Why?
  3. Mempool gossip: Create a signed transaction on NYC. Before mining, check if all connected nodes received it in their mempool. Now mine on London. Is the transaction included?
  4. Difficulty experiment: Create two networks — one with difficulty 2, another with difficulty 4. Mine 5 blocks on each. Compare the times. How does difficulty affect finality speed?
  5. 51% thought experiment: If you have 3 honest nodes and 4 attacker nodes, describe (in comments) step-by-step how the attacker could double-spend. What if it was 6 honest vs 4 attacker? Write the scenario as code comments.

Self-Check Questions

  1. Why does Bitcoin use proof of work instead of a simple voting system? (Hint: think about Sybil attacks.)
  2. If the average block time drops to 5 minutes, what will the difficulty adjustment do at the next 2,016-block window?
  3. A merchant accepts 0-confirmation transactions. Describe exactly how they could be scammed.
  4. Why is a 51% attack on Bitcoin more expensive than on a smaller proof-of-work coin?
  5. Explain the difference between a natural fork and a hard fork. Which one is dangerous? Which one is normal?
🎯

Module Summary

You now understand how Bitcoin goes from one machine to a global network. Peer-to-peer gossip spreads data without central servers. Nakamoto consensus — "longest chain wins" — resolves disagreements using accumulated proof of work. Natural forks resolve within blocks. The 51% attack is theoretically possible but economically irrational. Every design decision — 10-minute blocks, difficulty adjustment, 6 confirmations — serves a specific security purpose. In the next module, we'll explore how other networks improve on Bitcoin's design: Proof of Stake, network upgrades, and the evolution of consensus.

Next module

Bitcoin's proof of work is secure but energy-intensive. Can we achieve consensus without burning electricity? Enter Proof of Stake, network upgrades, and the evolution of blockchain consensus mechanisms.

Module 5: Network, Forks & Proof of Stake →