Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 41 ยท Projects

Project: Simulating a Multi-Node Network

Simulate a blockchain network in Python: several nodes mine and gossip blocks, forks appear from latency, the longest chain wins, and a report shows convergence.

A blockchain is not one program. It is thousands of independent nodes that each hold their own copy of the chain, hear about new blocks at different times, and still end up agreeing. In this project you build a small simulation of that process. First a hand-driven scenario shows a fork and its resolution step by step. Then a discrete-event simulation runs eight nodes that mine at random, gossip blocks over a network with delays, switch to the longest chain when they learn about it, and print a convergence report.

You will see the real behaviour of the system: forks are not a bug but a normal consequence of latency, some honest work gets thrown away, and the amount of waste depends on how long messages take compared with the block interval. Background for these ideas is in Longest Chain Rule, Forks and Reorgs and Peer-to-Peer Networking and Gossip.

The rules every node follows

Each node is a small state machine with just a few rules:

  1. Keep the best chain you know: the longest valid chain. If two are equally long, keep the one you saw first.
  2. When you mine a block, extend your own best chain and tell your peers.
  3. When you hear about a block you have not seen, accept it if it is valid, tell your peers (this is gossip), and switch to it if it makes a longer chain.
  4. If a block arrives before its parent, hold it as an orphan until the parent shows up.
flowchart TD
  R["Block arrives"] --> K{"Already known?"}
  K -->|"yes"| I["Ignore"]
  K -->|"no"| P{"Parent known?"}
  P -->|"no"| O["Park as orphan"]
  P -->|"yes"| A["Add block, gossip to peers"]
  A --> L{"Longer than my tip?"}
  L -->|"yes"| S["Switch tip<br/>(maybe a reorg), restart mining"]
  L -->|"no"| E["Keep my tip"]

The decision every node makes for each incoming block.

Part 1: a fork you can follow

First, a tiny network without timing. Three nodes mine real blocks (with a light proof of work). Nodes A and B both find block 2 at the same moment, so the network splits. Node C hears from A first. Later B finds a third block and the longer chain wins everywhere.

Python A fork and its resolution, step by step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is the whole story of a fork. The temporary disagreement is resolved without any coordinator, simply because every node applies the same rule to the same information. The block that lost is stale (also called orphaned). The miner of that block did real work and earns nothing, which is why miners want fast, well-connected networks.

Part 2: a discrete-event simulation

Part 1 moved messages by hand. To study the system as a whole you need time. A discrete-event simulation keeps a priority queue of future events and always processes the earliest one: "node 3 finds a block at time 41.7" or "node 5 receives block 12 at time 43.1". Nothing really waits; the simulated clock jumps from event to event, so thousands of blocks finish in a fraction of a second.

The model has these ingredients:

  • Hash power. Node i has a share of the total mining power. Finding a block is a random process, so the time until a node finds one is exponentially distributed with mean (block interval) / (its share).
  • Topology. A ring of nodes plus some random shortcuts, each link with its own latency (0.5 to 3 time units, multiplied by a scale factor).
  • Gossip. The first time a node learns of a block, it forwards it to all neighbours.
  • Memorylessness. Because mining attempts do not "remember" earlier attempts, a node that switches tips simply draws a new waiting time.

Time units are arbitrary; imagine seconds with a block interval of 10. The run uses a fixed seed, so the numbers are the same each time.

Python Eight nodes mining and gossiping, with a report

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the report from top to bottom. With the default settings roughly one block in five is stale, even though every miner is honest. The reason is that two nodes sometimes find a block before they hear about each other's, and this toy network has a block interval of only 10 time units against link delays of up to 3 per hop. The table by node shows that the share of main-chain blocks roughly follows the hash-power share, which is the fairness property of proof of work. The match is not exact: random luck matters in a short run, and a node whose blocks reach the others slowly (node 7 here mined many blocks but saw many of them go stale) loses a little.

The latency sweep is the most important result. When messages are fast compared with the block interval, almost no work is wasted (about 3 percent at one tenth of the default latency). When latency approaches the block interval, more than half of all blocks go stale, and in the last two rows the run even ends with nodes on different tips: the network was still arguing about the newest blocks when mining stopped. This is why Bitcoin picked an interval of about ten minutes, and why chains with very short blocks need different designs (such as GHOST-style fork choice, or proof of stake with fixed slots).

What the simulation leaves out

  • No attackers. All miners follow the rules. Add a node that mines in secret and releases its chain late to see selfish mining and double spends.
  • No validation cost. Real nodes spend time verifying blocks, which adds to effective latency.
  • Constant difficulty. Real chains retarget so that the interval stays near the target as hash power changes (Difficulty Adjustment and Block Time).
  • No transactions. Add the ledger from the first project and each block would carry real transfers; a reorg would then return transactions from stale blocks to the mempool.
  • Simplified topology. Real peer-to-peer graphs change constantly, and big miners are often closely connected.

Experiments to try

  1. Change the seed and look at which node is "lucky". Does the share of main-chain blocks stay close to the power share over long runs?
  2. Give one node 60 percent of the power. How does its stale rate compare with the others? (A well-connected large miner wastes less.)
  3. Cut the network into two halves for part of the run, then reconnect them. How deep is the biggest reorg?
  4. Change mean_interval to 2 and compare the stale rate with the sweep above.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do forks happen on a network of honest miners?

    Latency means nodes work from different information for a short time. Both blocks are valid, so the network is briefly split until a longer chain emerges.
  2. 2. What does a node do when it learns about a longer valid chain than its own?

    Following the longest valid chain is the rule every node applies, and it is what makes the network converge without a coordinator.
  3. 3. In the latency sweep, what happens to the stale-block rate as latency grows relative to the block interval?

    The longer messages take, the larger the window in which two miners can work on the same parent, producing more forks and stale blocks.
  4. 4. Why can the simulation draw a fresh waiting time whenever a node switches to a new tip?

    Each hash attempt is independent. The waiting time to a success is exponentially distributed and has no memory of the time already spent.
  5. 5. What is a stale (orphaned) block?

    Stale blocks are valid but were outcompeted by another branch. Their miners get no reward.

Summary

  • Each node applies simple rules: keep the longest valid chain, gossip new blocks, park orphans until their parent arrives.
  • Forks are a normal result of latency; they resolve on their own when one branch becomes longer, and the losing blocks are stale.
  • A discrete-event simulation jumps from event to event with a priority queue, so long network histories run instantly with a fixed seed.
  • Mining is memoryless, so a node that changes tip just draws a new random waiting time.
  • Rewards follow hash power, and waste grows as latency approaches the block interval, which is a core reason for block-time design choices.

Next: Project: On-Chain Voting and a Token, where you run governance on a toy contract engine.