Merkle Tree Integrity Verification

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

JavascriptSecurity Boundaries

Code

snippet
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}));}