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.
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.
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.
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.