Merkle Tree Integrity Verification

Build a Merkle tree from leaf hashes for tamper-evident integrity verification with efficient root comparison.

JavascriptSecurity Boundaries

Code

javascriptsnippet
1 line
export function merkleTree(leaves){const sha256=async(s)=>{const buf=new TextEncoder().encode(s);return new Uint8Array(await crypto.subtle.digest('SHA-256',buf));};async function build(levels){const top=levels[levels.length-1];if(top.length===1)return levels;const next=[];for(let i=0;i<top.length;i+=2){const l=top[i],r=top[i+1]??top[i];next.push(sha256(Buffer.concat([l,r])));}levels.push(await Promise.all(next));return build(levels);}return build([await Promise.all(leaves.map(l=>sha256(l)))]).then(tree=>({root:()=>tree[tree.length-1][0],levels:()=>tree}));}

What the code does

One way to read it: the functions sha256, merkleTree and build, doing all the work.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

The input levels is mutated in place — callers that need the original must pass a copy. What comes back is a new object, not a reference to anything passed in.

Points of care

  • crypto exist only in browsers — a Node runtime has no shims for them out of the box.
  • The guard top.length===1 short-circuits the flow with an early return when its condition holds.
  • levels is mutated in place — the value you pass will not be the same afterward.

Taking the usage further

The main signature reads export function merkleTree(leaves)

The surface worth importing is merkleTree; the helpers around it are private to the snippet.

Interactive Tools for This Topic

FAQ

Does `merkleTree` modify its input?
Yes — `levels` is mutated in place, and the return value is a new object rather than the mutated input. Pass a copy if the caller needs the original preserved.
Can I paste this into a project as-is?
Yes. Paste it in and run; no package manager step is needed. The file defines `sha256`, `merkleTree`, `build` at load time.