← Research
Apr 2023

A Merkle tree in Rust

A small Merkle tree in Rust, with unit tests. It builds a tree from a list of items and computes the root. I wrote it to see how blockchains verify large sets of data with one hash.

Repository ↗

Motivation

I started this to look into how blockchains verify huge amounts of data with a single hash. I didn’t want to just read about Merkle trees. So I built one in Rust to see how each piece works.

How it works

The idea is pretty simple. You hash each piece of data into a leaf, then hash pairs of hashes together for the level above. Keep going until only one hash is left at the top. That’s the root.

A Merkle tree with four data blocks. Each block is hashed into a leaf, pairs of leaves are hashed into two parent hashes, and those two are hashed into the root. Root H(A+B) H(C+D) H(A)H(B)H(C)H(D) Data AData BData CData D
Four pieces of data, hashed into leaves, then into pairs, then into one root. Change any piece and the root changes.

Change any piece of data and the root changes too. Blockchains use this to commit to every transaction in a block with one hash. They can also prove a transaction is in a block without sending the whole thing.

Building it

Every level pairs hashes two by two, which means the number of leaves has to be a power of two. With three items, or five, that doesn’t line up. My code pads the list with empty data up to the next power of two.

Three items, a, b and c, become four leaves: a fourth empty leaf is added so the count is a power of two. abc empty 3 items → padded to 4 leaves
The tree needs a power of two leaves, so the code fills the gap with empty data.

Once the list is padded, it builds the tree level by level, pairing hashes until one is left. Each node keeps a link to its parent. That way you can walk from any leaf up to the root later.

You can grab the root hash, or verify that a list of items produces a given root. You can also get a proof for one item, either by its position or by the data itself.

The tests

I wrote 8 unit tests for it. Two of them check the shape: three items end up as 7 nodes, and five items end up as 15. Two more check verification, including that adding an extra item makes verification fail. The rest test proofs by position and by data, plus what happens when you ask for a position that doesn’t exist or data that isn’t in the tree.