Free — no signup required

Anatomy of a Merkle Tree

2 min read

Building the Tree from the Ground Up

A Merkle Tree is a binary tree where every node contains a cryptographic hash. Construction starts at the bottom and works upward.

Step 1 — Leaf Nodes: Divide your data into chunks (file segments, database rows, transactions). Hash each chunk individually using a function like SHA-256. These hashes are your Leaf Nodes. The hash function is deterministic — the same input always produces the same output — and collision-resistant — it is computationally infeasible to find two different inputs that produce the same hash.

Step 2 — Internal Nodes (Branches): Take two adjacent leaf hashes, concatenate them, and hash the result:

Parent = Hash(LeftChild || RightChild)

This produces a hash that represents both children. Repeat this process for every pair at each level.

Step 3 — The Merkle Root: Continue combining pairs upward until only one hash remains. This is the Merkle Root — a single hash that is a cryptographic fingerprint of the entire dataset.

Why Concatenation Order Matters

The order of concatenation is fixed by convention. Hash(Left || Right) is not the same as Hash(Right || Left). Systems must agree on the ordering scheme, or two nodes building a tree from the same data will produce different roots. This is a common source of bugs in custom Merkle Tree implementations.

Odd Numbers of Leaves

If a level has an odd number of nodes, the last node is typically duplicated and hashed with itself: Parent = Hash(LastChild || LastChild). Bitcoin uses this convention. Some systems instead promote the lone node directly to the next level. The specific rule doesn't matter as long as all participants agree.

The Root is the Identity

The Merkle Root serves as a unique fingerprint for the entire dataset. Change a single bit anywhere:
- The hash of that data chunk changes.
- Its parent hash changes.
- Its grandparent hash changes.
- The Merkle Root changes.

If two systems have the same Root Hash, they mathematically possess the exact same data — every byte, in every chunk, in every position.

Key Point: A single bit change anywhere in the dataset propagates up the tree and changes the root hash. This makes tampering instantly detectable with a single hash comparison, regardless of dataset size.

This is one of 18 chapters

Every chapter is free — Kubernetes, Terraform, SRE, distributed systems, and more — with fast daily review built in.

Sign up free