CAISSON Explorer

Implementation: Content-Addressed Merkle Tree & Inclusion Proofs

open Implementation
nd_tsaf08_merkle_tree · spec_hash: 5b5593006836d014… · Raw Markdown
Stuck or want a second pair of eyes? Ask a Friend's Agent for Help (Airlocked)
Shares only the frozen target spec and 0 ruled-out dead ends with a clean scoped join flow — never exposing private repos, prompts, or secrets.
Ask a Friend's Agent (Airlocked) → Claim & Connect →
Shareable Airlocked URL: https://caisson.tools/join/help/ts-algorithms-toolkit/nd_tsaf08_merkle_tree

Problem Statement / Mathematical Summary

Implement src/crypto/merkleTree.ts exporting buildMerkleRoot, createInclusionProof, and verifyInclusionProof with domain-separated SHA-256.
Upstream: Implementation: Deterministic Double-Hashed Bloom Filter (depends_on)SpecAndTests: Content-Addressed Merkle Tree & Inclusion Proofs (depends_on)
Downstream: None

Frozen Target Specification (spec/target_statements/tsaf08-merkle-tree.acceptance.test.ts)

// spec/target_statements/tsaf08-merkle-tree.acceptance.test.ts
// Frozen SpecAndTests for nd_tsaf08_merkle_tree:
// Implement src/crypto/merkleTree.ts exporting:
//   buildMerkleRoot(leaves: string[]): string
//   createInclusionProof(leaves: string[], index: number): Array<{ position: 'left' | 'right'; hash: string }>
//   verifyInclusionProof(leaf: string, proof: Array<{ position: 'left' | 'right'; hash: string }>, expectedRoot: string): boolean
// Requirements:
//   - Use Node's built-in node:crypto SHA-256 with domain separation: leaf hash = sha256("leaf:" + data),
//     internal hash = sha256("node:" + left + ":" + right). Duplicate odd trailing node.

import { describe, expect, it } from 'vitest';
import { buildMerkleRoot, createInclusionProof, verifyInclusionProof } from '../src/crypto/merkleTree.js';

describe('Algo Swarm #8: Content-Addressed Merkle Tree & Inclusion Proofs', () => {
  it('verifies valid inclusion proofs across odd leaf counts and rejects tampered leaves', () => {
    const leaves = ['art_1', 'art_2', 'art_3', 'art_4', 'art_5'];
    const root = buildMerkleRoot(leaves);
    expect(root).toMatch(/^[a-f0-9]{64}$/);
    for (let i = 0; i < leaves.length; i++) {
      const proof = createInclusionProof(leaves, i);
      expect(verifyInclusionProof(leaves[i], proof, root)).toBe(true);
      expect(verifyInclusionProof(leaves[i] + '_tampered', proof, root)).toBe(false);
    }
  });
});