Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
Cryptography Cryptography Tutorial Java Java and Cryptography Mastery Series — Extended Module 16 - Applied Cryptography

Java Program for Merkle Proof Verification

Reviewed & accurate
AI Summary

Introduction

The Merkle proof was introduced by Ralph Merkle in his 1980 paper "Protocols for Public Key Cryptosystems" published at the IEEE Symposium on Security and Privacy, where he showed that a verifier can confirm a single leaf is part of a Merkle tree by computing only log2(N) hashes plus a single comparison against the published root. This logarithmic cost is the reason Bitcoin light clients (the simplified payment verification nodes from the Satoshi white paper) can verify a transaction is in a block with about 30 hash computations instead of downloading 600 GiB of block data. A Java learner should care because the Merkle proof is the most elegant example of an inclusion proof in all of cryptography, and because the same construction backs certificate transparency inclusion proofs, Cassandra replica audits, and Apache Kafka's internal log.

This tutorial builds the Merkle tree from the previous tutorial, then demonstrates generating and verifying an inclusion proof for one leaf. The prover (who has the full list) sends the verifier the leaf data plus a list of sibling hashes; the verifier walks the path from the leaf to the root, hashing each sibling in alongside the running hash, and checks that the final hash matches the published root.

What is a Merkle Proof?

A Merkle proof (also called an authentication path or inclusion proof) is the list of sibling hashes that a verifier needs to recompute the Merkle root from a single leaf. The proof has length log2(N) for a tree of N leaves, so verifying a leaf in a tree of one million leaves requires only 20 hashes. The proof is small (about 640 bytes for a million-leaf tree using SHA-256), cheap to verify (microseconds), and does not require the verifier to ever see the other N-1 leaves.

A Merkle proof differs from a zero-knowledge proof in that it reveals the leaf data; the verifier learns the leaf and can prove the leaf was part of the dataset. A zero-knowledge proof would let the verifier prove they know a leaf that satisfies some property without revealing which leaf. Merkle proofs are not zero-knowledge; they are pure inclusion proofs.

Each step of the proof includes a direction bit that tells the verifier whether the sibling goes on the left or the right of the current hash. Without the direction bit, the verifier cannot know whether to compute H(current || sibling) or H(sibling || current), and a malicious prover could swap the order to fake a valid proof. The direction bit is what commits the proof to the tree topology.

How Merkle Proofs Work - Step by Step

Step 1: Build the tree. The prover has the full list of leaves and builds the full binary Merkle tree, keeping every intermediate hash in memory.

Step 2: Generate the proof. To prove leaf at index i, the prover walks from leaf to root. At each level, the sibling of i is at index i xor 1 (the bit-flip of the last bit of i). The prover records the sibling hash and a direction bit indicating whether the sibling was on the right (if i is even) or the left (if i is odd). The prover then moves up one level (i = i / 2) and repeats until the root level.

Step 3: Verify the proof. The verifier starts with the leaf hash, then for each (sibling, direction) pair in the proof, computes newHash = H(sibling || current) if direction is LEFT (meaning the sibling was on the left), or H(current || sibling) if direction is RIGHT. After processing all proof steps, the verifier compares the final hash to the published root. If they match, the leaf is in the tree.

Step 4: Direction bit matters. Without the direction bit, a malicious prover could claim leaf i was at position i xor 1 by reversing the concatenation order, which would produce a valid-looking proof for a leaf that is actually in a different position in the tree. The direction bit prevents this attack by committing the prover to a specific leaf position.

Step 5: Tamper detection. Suppose a malicious prover tampers with the leaf data (replaces the actual leaf with a different one) but keeps the proof unchanged. The verifier computes the leaf hash of the modified data, which differs from the original leaf hash, so the running hash diverges from the expected path and the final hash does not match the published root. The proof fails.

Java Program for Merkle Proof Verification

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class MerkleProofDemo {

    static final byte LEAF_PREFIX = 0x00;
    static final byte INTERNAL_PREFIX = 0x01;

    static class ProofStep {
        byte[] siblingHash;
        boolean siblingOnLeft; // direction bit
        ProofStep(byte[] s, boolean left) {
            siblingHash = s;
            siblingOnLeft = left;
        }
    }

    public static void main(String[] args) throws Exception {
        List<String> data = Arrays.asList(
                "Tx0: Alice pays Bob 5 BTC",
                "Tx1: Bob pays Carol 3 BTC",
                "Tx2: Carol pays Dave 1 BTC",
                "Tx3: Dave pays Eve 2 BTC",
                "Tx4: Eve pays Frank 0.5 BTC",
                "Tx5: Frank pays Grace 1.5 BTC",
                "Tx6: Grace pays Heidi 0.25 BTC",
                "Tx7: Heidi pays Ivan 0.75 BTC");

        // Build the tree and store all levels.
        List<List<byte[]>> levels = buildTreeLevels(data);
        byte[] root = levels.get(levels.size() - 1).get(0);
        System.out.println("==> Merkle root");
        System.out.println("  Root: " + toHex(root));

        // Generate a proof for leaf index 3 ("Dave pays Eve 2 BTC").
        int leafIndex = 3;
        List<ProofStep> proof = generateProof(levels, leafIndex);
        System.out.println("\n==> Proof for leaf " + leafIndex);
        System.out.println("  Leaf data: " + data.get(leafIndex));
        System.out.println("  Proof length: " + proof.size() + " steps");
        for (int i = 0; i < proof.size(); i++) {
            System.out.printf("  Step %d: sibling=%s... on %s%n",
                    i,
                    toHex(proof.get(i).siblingHash).substring(0, 12),
                    proof.get(i).siblingOnLeft ? "LEFT" : "RIGHT");
        }

        // Verify the proof against the published root.
        byte[] leafHash = hashLeaf(data.get(leafIndex)
                .getBytes(StandardCharsets.UTF_8));
        boolean ok = verifyProof(leafHash, proof, root);
        System.out.println("\n==> Verifying inclusion proof");
        System.out.println("  Valid: " + ok);

        // Tamper: present a different leaf with the original proof.
        byte[] fakeLeaf = hashLeaf("Tx3: Dave pays Eve 200 BTC"
                .getBytes(StandardCharsets.UTF_8));
        boolean tampered = verifyProof(fakeLeaf, proof, root);
        System.out.println("\n==> Tampering test");
        System.out.println("  Tampered leaf verifies: " + tampered);

        // Wrong direction bit: should fail.
        List<ProofStep> swappedProof = new ArrayList<>();
        for (ProofStep s : proof) {
            swappedProof.add(new ProofStep(s.siblingHash, !s.siblingOnLeft));
        }
        boolean swapped = verifyProof(leafHash, swappedProof, root);
        System.out.println("\n==> Direction-bit swap attack");
        System.out.println("  Swapped direction verifies: " + swapped);
    }

    static List<List<byte[]>> buildTreeLevels(List<String> data)
            throws Exception {
        List<List<byte[]>> levels = new ArrayList<>();
        List<byte[]> leaves = new ArrayList<>();
        for (String s : data) {
            leaves.add(hashLeaf(s.getBytes(StandardCharsets.UTF_8)));
        }
        levels.add(leaves);
        while (levels.get(levels.size() - 1).size() > 1) {
            List<byte[]> prev = levels.get(levels.size() - 1);
            List<byte[]> next = new ArrayList<>();
            for (int i = 0; i < prev.size(); i += 2) {
                byte[] left = prev.get(i);
                byte[] right = (i + 1 < prev.size())
                        ? prev.get(i + 1) : left;
                next.add(hashInternal(left, right));
            }
            levels.add(next);
        }
        return levels;
    }

    static List<ProofStep> generateProof(List<List<byte[]>> levels,
            int leafIndex) {
        List<ProofStep> proof = new ArrayList<>();
        int idx = leafIndex;
        for (int level = 0; level < levels.size() - 1; level++) {
            List<byte[]> curr = levels.get(level);
            int sib = idx ^ 1;
            if (sib >= curr.size()) {
                // Odd node: sibling is self.
                proof.add(new ProofStep(curr.get(idx), true));
            } else {
                boolean sibOnLeft = (sib < idx);
                proof.add(new ProofStep(curr.get(sib), sibOnLeft));
            }
            idx = idx / 2;
        }
        return proof;
    }

    static boolean verifyProof(byte[] leafHash, List<ProofStep> proof,
            byte[] root) throws Exception {
        byte[] current = leafHash;
        for (ProofStep s : proof) {
            if (s.siblingOnLeft) {
                current = hashInternal(s.siblingHash, current);
            } else {
                current = hashInternal(current, s.siblingHash);
            }
        }
        return Arrays.equals(current, root);
    }

    static byte[] hashLeaf(byte[] data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(LEAF_PREFIX);
        return md.digest(md.digest(data));
    }

    static byte[] hashInternal(byte[] left, byte[] right) throws Exception {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(INTERNAL_PREFIX);
        md.update(left);
        return md.digest(right);
    }

    static String toHex(byte[] b) {
        StringBuilder sb = new StringBuilder();
        for (byte x : b) {
            sb.append(String.format("%02x", x & 0xff));
        }
        return sb.toString();
    }
}

Code Explanation - Line by Line

buildTreeLevels() is identical to the buildMerkleRoot() of the previous tutorial except that it stores every level of the tree in a List of Lists instead of just keeping the latest level. The proof generator needs access to all the intermediate sibling hashes, which is why we keep them. In production the prover would build the tree once and answer many proofs against it; here we build it once per program run.

generateProof() walks from the leaf level up to the root, capturing one sibling per level. At each level, the sibling of index idx is at idx xor 1, which is the bit-flip of the last bit of idx; this works because we are in a binary tree where siblings share all bits except the last one. If the sibling index exceeds the level size (odd-node case), the sibling is the node itself, matching the duplicate-last-leaf convention. The direction bit sibOnLeft is true if sib is less than idx (sibling is on the left). After processing the level, idx is divided by 2 to move up one level.

verifyProof() is the heart of the verifier. It starts with the leaf hash and walks the proof, hashing the running current value with the sibling in the order indicated by the direction bit. If the direction bit says the sibling is on the left, the verifier computes hashInternal(sibling, current); otherwise hashInternal(current, sibling). After processing all proof steps, the verifier compares the final hash to the published root with Arrays.equals().

The tamper test in main() hashes a different leaf string ("Dave pays Eve 200 BTC" instead of "Dave pays Eve 2 BTC") and submits it with the original proof. The leaf hash diverges from the original, the running hash diverges from the expected path, and the final hash does not match the root. The direction-bit swap test reverses every direction bit in the proof and submits the original leaf hash. The verifier computes the hashes in the wrong order, which produces a different parent hash, which diverges from the expected path. Both attacks fail, demonstrating that the proof binds both the leaf data and the leaf position.

Sample Input and Output

==> Merkle root
  Root: 5a3c...8b1d... (full 64 hex chars)

==> Proof for leaf 3
  Leaf data: Tx3: Dave pays Eve 2 BTC
  Proof length: 3 steps
  Step 0: sibling=2b8a... on LEFT
  Step 1: sibling=c4f1... on RIGHT
  Step 2: sibling=7d2e... on LEFT

==> Verifying inclusion proof
  Valid: true

==> Tampering test
  Tampered leaf verifies: false

==> Direction-bit swap attack
  Swapped direction verifies: false

The output proves three properties: the honest proof verifies against the published root; a tampered leaf with the honest proof fails; and a direction-bit swap of the honest leaf fails. Together these demonstrate that the Merkle proof commits to both the leaf data and the leaf position.

Common Mistakes to Avoid

First, do not omit the direction bit. Without it, a malicious prover can swap the order of concatenation at any level and produce a valid-looking proof for a leaf at a different position. The direction bit is one bit per level, which is negligible overhead. Second, do not allow the prover to choose which level the proof starts at; the proof must start at the leaf level and walk all the way to the root, otherwise an attacker can submit a partial proof that verifies against a non-root intermediate hash. Third, do not use the leaf hash itself as the proof's first element; that would let the prover submit any leaf hash they like as long as they compute the rest of the path correctly, which defeats the inclusion guarantee. Finally, do not forget to compare against the actual root that the verifier trusts; in production the root is signed by an authority (Bitcoin's coinbase commitment, the CT log's signed tree head, etc.) so the verifier must check the signature before comparing the recomputed root.

Real-World Applications

Bitcoin's simplified payment verification (SPV) light clients download only the block headers (80 bytes each) and request Merkle proofs for transactions they care about from full nodes. The proof is about 12 hashes for a block with 4,000 transactions, so the light client can confirm a transaction in about 12 microseconds of compute and 400 bytes of bandwidth instead of downloading 2 MiB of block data. Ethereum's light clients use Merkle-Patricia proofs for state queries so a wallet can verify the balance of an address without syncing the entire 500-GiB chain.

Certificate Transparency logs (RFC 6962) sign the tree head (the root plus the tree size) and deliver inclusion proofs to clients that have observed a certificate being issued; the browser can verify the certificate is in the log without downloading the entire log. Apache Cassandra's repair process uses Merkle proofs to find which token ranges between two replicas disagree, so the repair transfers only the disagreeing ranges instead of the entire data set. The ZFS file system uses Merkle trees for its snapshots: every block in the file system is hashed into a tree whose root is the snapshot identifier, so a snapshot is verifiably immutable and a single root commits to petabytes of data.

Conclusion

We saw that a Merkle proof is the list of log2(N) sibling hashes needed to recompute the Merkle root from a single leaf, that the proof must include direction bits to defeat position-swap attacks, and that the proof commits to both the leaf data and the leaf position. Next, study the Proof of Work tutorial to learn how the Merkle root anchors into a tamper-resistant blockchain, then read the Proof of Stake tutorial to see the alternative consensus mechanism.

Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments