Merkle Tree Integrity Verification
Build a Merkle tree from leaf hashes for tamper-evident integrity verification with efficient root comparison.
Code
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
cryptoexist only in browsers — a Node runtime has no shims for them out of the box.- The guard
top.length===1short-circuits the flow with an earlyreturnwhen its condition holds. levelsis 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
SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Webhook HMAC Signature VerifierVerify and generate HMAC-SHA256 webhook signatures for Stripe, GitHub, and raw hex headers locally using Web Crypto and constant-time comparison.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.