Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 41 ยท Projects

Project: A Complete Mini Blockchain

Combine blocks, proof of work, signed transactions, balances and full-chain validation into one Python class, then prove it works with assert tests and tampering.

In this project you put everything together. You will build a small but complete blockchain in one file: wallets that sign transactions, a mempool, blocks mined with proof of work, balances tracked by replaying the chain, and a validator that rejects forged, overspent, replayed and tampered data. At the end you will run a test suite made of plain assert statements.

Most of the pieces have their own lessons (Designing a Block, Proof of Work and Mining, Transactions and the Mempool), so here the focus is how they fit together. The code is for learning. In particular, the signature scheme is a small stand-in so that the program stays short; the next project upgrades it to a real elliptic curve (Project: A Wallet with Signed Transactions).

The design

Write down the rules first. A good blockchain is mostly a list of rules that every node checks independently.

Transactions carry from, to, amount, a per-sender nonce (a counter that stops replays), the sender's public key and a signature. A transaction is valid if:

  1. the amount is a positive whole number,
  2. the address matches the public key (so you cannot sign for someone else's address),
  3. the signature is correct for the transaction's content,
  4. the nonce equals the sender's next expected nonce,
  5. the sender's balance covers the amount.

Blocks hold an index, the previous block's hash, a list of transactions, a nonce and a hash. A block is valid if its hash meets the difficulty (starts with enough zeros), it points at the previous block, its first transaction is a single coinbase reward for the miner and all other transactions are valid in order.

The chain is valid if it starts with the agreed genesis block and every block is valid. Balances are not stored in blocks; they are always computed by replaying the chain.

flowchart LR
  W["Wallet<br/>(keys, sign)"] -->|"signed transaction"| M["Mempool"]
  M -->|"pick valid ones"| B["Block assembly<br/>+ coinbase reward"]
  B -->|"search nonce"| PoW["Proof of work"]
  PoW --> C[("Chain")]
  C -->|"replay all blocks"| S["Balances and nonces"]
  S -->|"check new transactions"| M

Transactions flow into blocks; the chain, replayed from the start, is the only source of truth for balances.

Step 1: wallets, signatures and a mined block

Start with the smallest slice: a wallet that signs, a verifier, and one block mined by brute force. The signature is a Schnorr signature in the multiplicative group modulo the prime 2**127 - 1. The signer picks a deterministic nonce from the secret and the message, computes a commitment t, derives the challenge by hashing, and answers with s. This is the Fiat-Shamir idea from Privacy and Zero-Knowledge Proofs used as a signature.

Python Step 1: sign a transaction and mine a block

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.

The signature verifies only for the right message and the right key. Mining finds a nonce by trial and error, which on average takes about 4,096 tries for three hex zeros.

Step 2: the whole blockchain in one class

Now the full program. Read it from the top: wallet and signature helpers, transaction helpers, then the Blockchain class with its rules.

Python The complete mini blockchain

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.

Alice mined the first block and received 50 coins. She then sent 20 and 5 to Bob in the second block, which the miner assembled and earned 50 more for. Everything is computed by replaying the chain, so there is no separate "balance database" to get out of sync.

A few design decisions deserve attention:

  • state() is both validator and ledger. It raises on the first broken rule, so the same code that computes balances also proves the chain legal. Real nodes do exactly this when they download and verify a chain.
  • submit() simulates the mempool. It applies queued transactions to a copy of the state, so Alice cannot queue two transactions that together spend more than she has.
  • The coinbase is applied after the other transactions of its block, so a miner cannot spend a reward that the same block creates.
  • The nonce counter (not to be confused with the mining nonce) forces each sender's transactions into order and makes an old, valid transaction useless if someone replays it.

Step 3: prove it with tests

A blockchain is a set of rules, and rules deserve tests. The tests below use only assert. Each one tries something that must succeed or something that must fail. This TryIt contains the full code again so that it runs on its own; the code is the same as above, with the demo replaced by tests.

Python A test suite and tampering experiments

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.

Look closely at the tampering experiments. Editing an amount and leaving the hash alone fails at the hash check. Fixing the hash fails at proof of work (the edited block no longer meets the difficulty) or at the signature check, because the signed content changed. Deleting a block breaks the links. Even paying the cost to re-mine a block with an inflated reward fails, because the rules say that the reward is exactly 50. Proof of work makes rewriting history expensive, but the validation rules make cheating impossible: a block is rejected for breaking a rule no matter how much work was spent on it.

Ideas to extend it

  • Add a Merkle root of the transactions to each block header (Merkle Trees and Proofs of Inclusion).
  • Add fees and let the miner choose the most profitable transactions first.
  • Add difficulty adjustment based on how long the last blocks took (Difficulty Adjustment and Block Time).
  • Add a timestamp and reject blocks that are too far in the future.
  • Let two copies of the chain exchange blocks and pick the longest valid one; that is the next-but-one project.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the project compute balances by replaying the chain instead of storing them in blocks?

    Every node can derive the same balances from the same blocks. A separate stored balance could drift out of sync or be forged.
  2. 2. What does the per-sender nonce in a transaction prevent?

    Each transaction must carry the sender's next expected counter value. An old transaction carries a counter that has already been used, so it is rejected.
  3. 3. An attacker edits a transaction amount inside an old block and re-mines that block so its hash is valid. Why is the chain still rejected?

    Re-mining fixes only that block's proof of work. The signed content changed, so the signature fails, and the following block still points at the old hash.
  4. 4. Why must the reward transaction be the first transaction and have a fixed amount?

    The coinbase is the only transaction without a signature, so its amount must be fixed by a rule that every validator enforces.

Summary

  • A blockchain is a set of rules that every node checks: transaction rules (signature, address, nonce, balance) and block rules (hash, link, proof of work, reward).
  • Balances and nonces are never stored; they are computed by replaying the chain, which doubles as full validation.
  • The mempool check applies pending transactions to a copy of the state so queued transactions cannot overspend together.
  • assert tests turn the rules into a safety net: valid transfers pass, and overspending, replays, forged addresses, edited signatures and tampered history fail.
  • Proof of work makes rewriting costly; validation rules make cheating impossible regardless of work.

Next: Project: A Wallet with Signed Transactions, where you replace the stand-in signature with ECDSA on a real elliptic curve.