Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 41 ยท Projects

Project: On-Chain Voting and a Token

Build a governance token and snapshot-based voting with quorum on a toy blockchain in Python, then prove with tamper checks that edited history is caught.

In this project you build the heart of a small DAO: a token that people hold, and a voting system that counts those tokens. Everything runs as transactions on a toy hash-linked chain, so the whole history can be replayed and checked. It is a good test of what you learned about tokens, the toy contract engine and DeFi and governance.

Real governance contracts are written in Solidity and run on a public chain. We use Python so you can run and change every line in your browser. The rules are the same ones you would write in a contract: who may mint, what a transfer needs, when a vote counts and how the result is decided.

What we are building

The system has four kinds of transactions:

Transaction Rule
mint Only admin may create new tokens, and the amount must be positive.
transfer The sender must hold at least the amount.
propose The proposer must hold tokens. The chain snapshots every balance at this moment.
vote Voting weight is the voter's balance in the snapshot. One vote per address, and only before the deadline.

Two ideas deserve a closer look.

Snapshot voting. If weight came from live balances, someone could vote, send their tokens to a second address, and vote again. Freezing balances when the proposal is created removes that trick. Tokens bought or received later simply carry no weight in this vote.

Quorum. A vote with three participants out of ten thousand holders is not a decision. We require that the total weight cast (yes plus no) is at least 20 percent of the supply at the snapshot. A proposal passes when quorum is met and yes weight beats no weight.

flowchart LR
  A["mint and transfer<br/>balances change"] --> B["propose<br/>snapshot of balances"]
  B --> C["votes arrive<br/>weight = snapshot balance"]
  C --> D{"deadline passed?"}
  D -- "no" --> C
  D -- "yes" --> E["tally: quorum?<br/>yes greater than no?"]

Figure: a proposal freezes balances, collects weighted votes until the deadline, then is tallied.

The engine

Three small pieces make up the project:

  • Chain stores blocks. Each block holds a list of transactions and the hash of the previous block, exactly like in Building and Validating the Chain. Hashes use json.dumps(..., sort_keys=True) so the serialization is canonical.
  • State is the state machine: apply(tx, height) checks the rules and changes balances or proposals. It raises ValueError before changing anything when a rule is broken.
  • Node checks each new transaction against State, queues the valid ones and seals them into a block. Invalid transactions never reach the chain.

Because the chain stores only transactions, any node can rebuild the state by replaying them from the genesis block with replay(chain). That is the core idea of state machine replication: everyone applies the same transactions in the same order and ends in the same state.

The code below is repeated at the top of every example, so each one runs on its own. To keep the project focused, transactions are not signed. Signing is the topic of A Wallet with Signed Transactions.

Step 1: the token

First we mint tokens, move some around and try two illegal actions: a non-admin minting, and an overdraft.

Python Token on a toy chain

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.

Mallory's mint and Bob's overdraft were rejected at the door, so they appear nowhere in the blocks. The chain holds three blocks (genesis plus two), it verifies, and replaying its transactions reproduces exactly the balances the live node holds. The supply stayed at 900 because only valid mints change it.

Step 2: snapshot voting with quorum

Now we run a proposal. Block 1 creates the balances, block 2 contains the proposal with a three-block voting window, and votes follow. Pay attention to Dave: he moves his tokens to Erin after the snapshot, and Erin's vote is refused because she held nothing when the snapshot was taken.

Python Snapshot voting and quorum

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 output line by line:

  • Erin's vote is rejected: no tokens in the snapshot. Moving tokens around cannot create voting power.
  • Bob's second vote is rejected: one address, one vote.
  • After Bob alone, no is 300 of a 1,000 supply. Quorum (200) is met, but yes is 0, so the proposal has not passed.
  • After Alice votes yes with weight 500, the tally is 500 against 300 and the proposal passes.
  • Carol's late vote is refused: the next block would be block 7, and the window ended at block 5.
  • The second proposal shows the quorum rule: yes beats no (100 to 0), but the 100 tokens cast are only 10 percent of the supply, so it fails.

The tally uses integer arithmetic ((yes + no) * 100 >= supply * 20) instead of floating point. Money and voting rules should never depend on rounding.

Weight here is "one token, one vote", which favors large holders. Other designs use quadratic weights, delegation or one vote per verified person. They are all small changes to the vote branch and the tally function.

Step 3: tamper checks

Governance is only worth something if nobody can rewrite the result afterwards. We attack our own chain in two ways. First we flip Bob's recorded vote inside an old block. Then, like a smarter attacker, we recompute every hash from that block on so that verify() passes again.

Python Editing history and getting caught

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 quiet edit is caught at once: verify() returns (False, 3), which says block 3 no longer matches its hash. The cover-up fools verify() alone, because an attacker can recompute hashes, and the replayed tally even shows the doctored result (800 yes, 0 no). But the head hash is now dd0e4fcd... instead of the published 342f8b20.... A hash chain cannot stop someone from rewriting history on their own copy. What it does is make every rewrite detectable by anyone who remembers the head hash (or, on a real network, anyone who holds the honest chain). That is why real chains add proof of work or stake: they make a competing history expensive to produce (Longest Chain Rule, Forks and Reorgs).

Ideas to extend the project

  1. Delegation. Let a holder delegate their snapshot weight to another address. Decide what happens when the delegate also holds tokens.
  2. Execution. Add an execute transaction that applies a passed proposal, for example by transferring tokens from a treasury address.
  3. Voting period in time. Replace block heights with timestamps, and discuss why block heights are safer to use inside a contract.
  4. Signatures. Reject any transaction not signed by its from or voter address, reusing the scheme from Digital Signatures with a Toy Scheme.
  5. Tests. Write assert statements for each rule: minting by non-admins, double votes, closed votes, quorum edge cases (exactly 20 percent should meet quorum).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the vote use balances from a snapshot instead of current balances?

    With live balances, a holder could vote, transfer tokens to a second address and vote again. A snapshot taken at proposal time freezes the weights.
  2. 2. A proposal has 100 yes and 0 no, but only 10 percent of the supply voted and the quorum is 20 percent. What is the outcome?

    Quorum is a separate requirement. Even a unanimous vote does not count when too little of the supply took part.
  3. 3. After an attacker edits an old block and recomputes every later hash, what still exposes the change?

    The new chain is internally consistent, but its head hash differs from the one others remember. Hash links make rewriting detectable, not impossible.
  4. 4. Why does State.apply check every rule before changing any balance?

    A transaction must apply completely or not at all. Checking first and changing state afterwards keeps the state consistent when a rule fails.

Summary

  • A governance token is a ledger of balances changed only by valid mint and transfer transactions.
  • A snapshot taken when a proposal is created freezes voting weights, so moving tokens cannot buy extra votes.
  • Quorum plus a yes-over-no rule decides a proposal; use integer math for the comparison.
  • Nodes keep only valid transactions in blocks, and anyone can rebuild the state by replaying the chain.
  • Hash links make edits detectable, and a remembered head hash exposes even a rewrite with recomputed hashes.

Next: Project: Supply Chain Provenance Tracker, where events about physical goods are recorded and proven with Merkle proofs.