Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 41 ยท Projects

Project: Supply Chain Provenance Tracker

Build a supply chain provenance tracker in Python: record product events on a hash-linked chain, prove one shipment with a Merkle proof and run audit queries.

"Where has this product been, and can I trust that record?" is the most common business question that blockchains are pitched to answer. In this project you build a small provenance tracker: manufacturers, carriers, customs and shops append events about physical products, the events are grouped into blocks, and an auditor can later check the history, prove a single event without downloading everything, and detect edits.

It combines three earlier lessons: hash pointers, Merkle trees and enterprise use cases. Read the last one first if you want the honest discussion of when a shared database would be enough. The tracker below is a ledger shared by a consortium: the parties are known, so there is no mining.

What we are building

Every product moves through the same fixed life cycle, and each step may only be recorded by an organization that is allowed to record it:

Step Who may record it
manufactured Acme
shipped FastFreight or SeaCargo
customs_cleared Border
delivered ShopCo

An event is a small dictionary: {"product", "kind", "actor", "place", "t"}, where t is a day number. The tracker refuses an event when the actor is not allowed, when the step is not the next one in the life cycle, or when time would go backwards for that product.

Events are collected into blocks. A block header holds only three things: its height, the hash of the previous header and the Merkle root of its events. The events themselves sit beside the header. This split is the key design choice:

  • Anyone with a header knows the root, which commits to every event in the block.
  • A Merkle proof shows that one event belongs to the root using only a handful of hashes, without the other events.
  • Editing any event changes the root, which changes the header hash, which breaks every later link.
flowchart TB
  H["block header<br/>height, prev hash, Merkle root"] --> R["Merkle root"]
  R --> A["hash of events 1 and 2"]
  R --> B["hash of events 3 and 4"]
  A --> E1["event 1"]
  A --> E2["event 2"]
  B --> E3["event 3"]
  B --> E4["event 4"]

Figure: the header commits to the root; the root commits to every event below it.

The engine

The code at the top of each example below defines the pieces, so every example runs on its own:

  • leaf_hash(event) hashes the event as canonical JSON, with a 0x00 prefix. node_hash(left, right) hashes two child hashes with a 0x01 prefix. These prefixes are called domain separation: a leaf can never be confused with an inner node, which closes a known forgery trick on Merkle trees.
  • merkle_root(leaves) combines hashes pairwise upward. When a level has an odd count, the last hash is paired with itself.
  • make_proof(leaves, index) collects the sibling hash at each level, remembering on which side it sits. check_proof(event, proof, root) recomputes the path.
  • Tracker enforces the rules in submit, builds blocks in seal, and checks everything in verify.

Step 1: record events and refuse bad ones

We manufacture three products, then try to ship them, including three events that must be refused.

Python Recording and refusing events

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 three bad events never reach a block. Mallory is not a registered carrier, P-1003 cannot be delivered before it has even shipped, and the t=0 event would put a shipment before its own manufacture date. Block 1 holds three events and block 2 holds two, so the list [0, 3, 2] includes the empty genesis block. The query for P-1001 reads like a passport: who did what, where and when.

A validation rule can only check what the chain knows. The tracker cannot know that a pallet physically arrived. Whoever records the event is trusted to say so. A blockchain proves that an event was recorded and not altered afterwards, not that it is true. This is the "oracle problem" from dApps, Oracles and Wallet Integration, and it is the biggest limit of every provenance system.

Step 2: prove one event with a Merkle proof

Imagine a shop that wants to show a customer that its delivery was recorded, or a regulator that audits one shipment. Sending the whole block would be wasteful, and revealing other companies' events could break confidentiality. A Merkle proof sends only the sibling hashes along the path from the event to the root.

Block 3 of our demo ledger has five events, an odd number, so the tree pairs a hash with itself on the way up. The auditor holds only the header (height, previous hash, root).

Python A Merkle proof for one shipment event

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.

Three hashes are enough to prove one of five events, and twenty hashes would be enough for a block of a million events. The proof for the real event passes. A forged version (Bergen instead of Oslo) fails, because even a one-letter change gives a different leaf hash. An event that was never recorded fails too: the same sibling hashes cannot lead to the right root from a different starting leaf.

Notice what the proof does not tell you. It shows that the event is in the block whose header you hold. You must still make sure that header is the real one, for example because it is the head of a chain you follow, or because its hash was published somewhere you trust. This is exactly how light clients work in Merkle Trees and Proofs of Inclusion.

Step 3: audit queries and tamper detection

Because all events are plain data in blocks, audits are just loops over the chain. Below, the day is 14. We list the status of each product, find shipments with no news for a week, answer a recall question ("which products did FastFreight touch?"), count events per actor, and finally check that nobody changed the past.

Python Audit queries and tamper check

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 "stuck" report found three products that have not moved for ten days, and the recall query narrows a problem with one carrier down to three product ids in one pass. Both queries are ordinary code; the blockchain's contribution is that every party can run them on the same data and get the same answer.

The last two lines are the tamper check. Before the edit, verify() returns (True, None, 'ok'). After someone rewrites the place of an old event in block 2, it returns (False, 2, 'events do not match the Merkle root'). It names the block, so an investigator knows where to look. A careful attacker could also recompute the root and all later headers, so a real deployment makes sure several independent parties keep copies of the latest header hash, as in Building and Validating the Chain.

Design notes and limits

  • Privacy. Real consortia rarely put full event data in a shared ledger. A common pattern stores only the hash of each event (or a Merkle root per batch) on the chain and keeps the data in the companies' own systems. The proof then convinces an auditor without publishing the data.
  • Identity. Our actor field is a plain name. In practice each event would be signed with the organization's key, as in Digital Signatures with a Toy Scheme.
  • Garbage in, garbage out. Sensors, scans and data entry can be wrong or dishonest. Good systems combine the ledger with physical tamper evidence, such as sealed containers and IoT readings signed by the device.
  • Do you need a chain at all? If one company controls the data and everyone trusts it, a normal database with an audit log is simpler and faster. The ledger earns its keep when several organizations that do not fully trust each other need one shared record.

Ideas to extend the project

  1. Add a recalled event that any regulator may record at any time, and make status_of show it.
  2. Allow a product to be split into smaller lots (one parent, many children) and write a query that follows lineage upward.
  3. Store only leaf_hash(event) in the block and keep the event data in a separate dictionary, then adjust verify() to check both.
  4. Add a rule that a shipped event must come from the same place where the previous event happened.
  5. Write assert tests for every rule and for a proof on blocks with 1, 2, 3 and 8 events.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a block header in the tracker commit to?

    The header holds height, previous hash and the Merkle root. The root commits to every event, so changing any event changes the header hash.
  2. 2. How many hashes does a Merkle proof need for a block of about one million events?

    Proof size grows with log2 of the number of leaves. 2 to the power 20 is about one million, so twenty sibling hashes are enough.
  3. 3. The ledger shows that a pallet was delivered. What does that prove?

    A blockchain protects the record, not the real world. Whether the delivery truly happened still depends on the honesty of whoever reported it.
  4. 4. Why do the leaf hash and the node hash use different prefix bytes?

    Domain separation prevents an attacker from presenting an inner node as if it were a leaf, which would let them forge proofs.
  5. 5. After an edit to an old event, verify() returns (False, 2, ...). What does the 2 mean?

    The second value is the index of the first block that fails verification, which tells auditors where to start looking.

Summary

  • A provenance ledger records product events from allowed actors in a fixed life cycle and rejects out-of-order, unauthorized or backdated events.
  • Block headers commit to a Merkle root, so editing any event breaks the chain.
  • A Merkle proof convinces an auditor of one event with only about log2(n) hashes and without revealing the others.
  • Audit and recall queries are ordinary loops over data everyone shares.
  • The chain protects records after they are written; it cannot prove the physical event happened.

Next: Practice Exercises with Solutions, ten graded problems to test everything in this tutorial.