/** * Tests for Node.pathToLeaf() - proof path generation * Tests that paths are correctly constructed when traversing the tree. */ import { describe, expect, it, } from "vitest"; import { createTestDb, } from "../db/test-db-factory.js"; import { MutableTree, } from "../mutable-tree.js"; import { NodeDB, } from "../storage/node-db.js"; import { DEFAULT_OPTIONS, } from "../types/options.js"; import { pathToLeafIndex, } from "./path-to-leaf.js"; import type { ProofInnerNode, } from "./proof-inner-node.js"; /** * Helper to convert string to Uint8Array */ function str(s: string): Uint8Array { return new TextEncoder().encode(s); } /** * Helper to convert Uint8Array to string */ function bytes(u: Uint8Array): string { return new TextDecoder().decode(u); } /** * Helper to create a MutableTree for testing */ async function createTestTree(): Promise { const ctx = await createTestDb(); const ndb = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await ndb.initialize(); const workingTree = await ndb.getImmutableTree(0n); return new MutableTree(ndb, workingTree, true); // skipFastStorageUpgrade = true } describe("Node.pathToLeaf() - Path Generation", () => { describe("Basic path generation", () => { it("should generate path for single leaf tree", async () => { const tree = await createTestTree(); await tree.set(str("a"), str("value-a")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, node, } = await root.pathToLeaf(tree.ndb, str("a")); // Single leaf - path should be empty (no inner nodes) expect(path).toHaveLength(0); expect(bytes(node.key!)).toBe("a"); expect(bytes(node.value!)).toBe("value-a"); }); it("should generate path for 2-leaf tree (left key)", async () => { const tree = await createTestTree(); await tree.set(str("a"), str("value-a")); await tree.set(str("b"), str("value-b")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, node, } = await root.pathToLeaf(tree.ndb, str("a")); // Path should have 1 inner node (the root) expect(path).toHaveLength(1); // Path[0] should be the root with right sibling const pin = path[0]; expect(pin.height).toBe(1); expect(pin.size).toBe(2n); expect(pin.left).toBeNull(); // went left expect(pin.right).not.toBeNull(); // right sibling hash // Found node should be 'a' expect(bytes(node.key!)).toBe("a"); expect(bytes(node.value!)).toBe("value-a"); // Calculate index - should be 0 (leftmost) const idx = pathToLeafIndex(path); expect(idx).toBe(0n); }); it("should generate path for 2-leaf tree (right key)", async () => { const tree = await createTestTree(); await tree.set(str("a"), str("value-a")); await tree.set(str("b"), str("value-b")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, node, } = await root.pathToLeaf(tree.ndb, str("b")); // Path should have 1 inner node expect(path).toHaveLength(1); // Path[0] should be the root with left sibling const pin = path[0]; expect(pin.height).toBe(1); expect(pin.size).toBe(2n); expect(pin.left).not.toBeNull(); // left sibling hash expect(pin.right).toBeNull(); // went right // Found node should be 'b' expect(bytes(node.key!)).toBe("b"); expect(bytes(node.value!)).toBe("value-b"); // Calculate index - should be 1 (rightmost) const idx = pathToLeafIndex(path); expect(idx).toBe(1n); }); it("should generate path for 4-leaf balanced tree", async () => { const tree = await createTestTree(); // Build a balanced tree with 4 leaves: a, b, c, d await tree.set(str("a"), str("1")); await tree.set(str("b"), str("2")); await tree.set(str("c"), str("3")); await tree.set(str("d"), str("4")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); // Test all 4 leaves for (const [key, expectedIdx] of [ ["a", 0n], ["b", 1n], ["c", 2n], ["d", 3n], ]) { const { path, node, } = await root.pathToLeaf(tree.ndb, str(key)); // Path should have 2 inner nodes (root + parent) expect(path.length).toBeGreaterThanOrEqual(1); // Found node should be the requested key expect(bytes(node.key!)).toBe(key); // Calculate index const idx = pathToLeafIndex(path); expect(idx).toBe(expectedIdx); } }); }); describe("Path ordering", () => { it("should order path from ROOT to LEAF", async () => { const tree = await createTestTree(); // Build a tree with 8 leaves for (let i = 0; i < 8; i++) { await tree.set(str(`key${i}`), str(`value${i}`)); } await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, } = await root.pathToLeaf(tree.ndb, str("key7")); // Path should have multiple levels expect(path.length).toBeGreaterThan(0); // Each level should have decreasing size (going from root down) for (let i = 0; i < path.length - 1; i++) { expect(path[i].size).toBeGreaterThan(path[i + 1].size); } // Root (path[0]) should have the largest size expect(path[0].size).toBe(8n); }); it("should have correct sibling hashes at each level", async () => { const tree = await createTestTree(); await tree.set(str("a"), str("1")); await tree.set(str("b"), str("2")); await tree.set(str("c"), str("3")); await tree.set(str("d"), str("4")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, } = await root.pathToLeaf(tree.ndb, str("a")); // Verify that exactly one of left/right is null at each level for (const pin of path) { const hasLeft = pin.left !== null; const hasRight = pin.right !== null; // Exactly one should be set (XOR) expect(hasLeft !== hasRight).toBe(true); // The one that's set should be a 32-byte hash if (hasLeft) { expect(pin.left!.length).toBe(32); } else { expect(pin.right!.length).toBe(32); } } }); }); describe("Non-existent keys", () => { it("should return closest leaf for key less than all keys", async () => { const tree = await createTestTree(); await tree.set(str("b"), str("2")); await tree.set(str("c"), str("3")); await tree.set(str("d"), str("4")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); // Search for 'a' which is less than all keys const { node, } = await root.pathToLeaf(tree.ndb, str("a")); // Should return the leftmost leaf ('b') expect(bytes(node.key!)).toBe("b"); }); it("should return closest leaf for key between existing keys", async () => { const tree = await createTestTree(); // Insert only even keys: a, c, e, g await tree.set(str("a"), str("1")); await tree.set(str("c"), str("3")); await tree.set(str("e"), str("5")); await tree.set(str("g"), str("7")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); // Search for 'b' (between 'a' and 'c') const { node, } = await root.pathToLeaf(tree.ndb, str("b")); // Should return 'a' (next leaf left of 'b') expect(bytes(node.key!)).toBe("a"); }); it("should return closest leaf for key greater than all keys", async () => { const tree = await createTestTree(); await tree.set(str("a"), str("1")); await tree.set(str("b"), str("2")); await tree.set(str("c"), str("3")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); // Search for 'z' which is greater than all keys const { node, } = await root.pathToLeaf(tree.ndb, str("z")); // Should return the rightmost leaf ('c') expect(bytes(node.key!)).toBe("c"); }); }); describe("Large trees", () => { it("should generate correct paths for 100-leaf tree", async () => { const tree = await createTestTree(); // Insert 100 keys for (let i = 0; i < 100; i++) { const key = new Uint8Array(4); new DataView(key.buffer).setUint32(0, i, false); await tree.set(key, str(`value-${i}`)); } await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); // Test first, middle, and last keys for (const i of [ 0, 50, 99, ]) { const key = new Uint8Array(4); new DataView(key.buffer).setUint32(0, i, false); const { path, node, } = await root.pathToLeaf(tree.ndb, key); // Should find the correct leaf const nodeKeyNum = new DataView( node.key!.buffer, node.key!.byteOffset, ).getUint32(0, false); expect(nodeKeyNum).toBe(i); // Path should be non-empty expect(path.length).toBeGreaterThan(0); // Index should match const idx = pathToLeafIndex(path); expect(Number(idx)).toBe(i); } }); }); describe("Edge cases", () => { it("should handle tree with single key", async () => { const tree = await createTestTree(); await tree.set(str("only-key"), str("only-value")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, node, } = await root.pathToLeaf(tree.ndb, str("only-key")); // No inner nodes for single leaf expect(path).toHaveLength(0); expect(bytes(node.key!)).toBe("only-key"); }); it("should handle search for non-existent key in single-leaf tree", async () => { const tree = await createTestTree(); await tree.set(str("only-key"), str("only-value")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, node, } = await root.pathToLeaf(tree.ndb, str("different-key")); // Should still return the only leaf expect(path).toHaveLength(0); expect(bytes(node.key!)).toBe("only-key"); }); it("should handle binary keys (not just strings)", async () => { const tree = await createTestTree(); // Insert binary keys (non-UTF8) for (let i = 0; i < 10; i++) { const key = new Uint8Array([ 0x00, i, 0xFF, ]); const value = new Uint8Array([i]); await tree.set(key, value); } await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); // Search for a binary key const searchKey = new Uint8Array([ 0x00, 5, 0xFF, ]); const { path, node, } = await root.pathToLeaf(tree.ndb, searchKey); // Should find the correct leaf expect(node.key).toEqual(searchKey); expect(path.length).toBeGreaterThan(0); }); }); describe("Path integrity", () => { it("should produce valid paths that can be hashed up to root", async () => { const tree = await createTestTree(); await tree.set(str("a"), str("1")); await tree.set(str("b"), str("2")); await tree.set(str("c"), str("3")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const rootHash = root.hash!; // Get proof path for 'b' const { path, node, } = await root.pathToLeaf(tree.ndb, str("b")); // We should be able to hash up from leaf to root // Start with leaf hash let currentHash = node.hash!; expect(currentHash).not.toBeNull(); // Hash up through each ProofInnerNode // Note: path is ROOT to LEAF, so we traverse backwards for (let i = path.length - 1; i >= 0; i--) { currentHash = path[i].hash(currentHash); } // Final hash should match root hash expect(currentHash).toEqual(rootHash); }); }); }); describe("PathToLeaf - Index Calculation and String Formatting", () => { describe("pathToLeafIndex - comprehensive coverage", () => { it("should return 0 for leftmost leaf", async () => { const tree = await createTestTree(); // Create a tree with multiple nodes await tree.set(str("a"), str("val")); await tree.set(str("m"), str("val")); await tree.set(str("z"), str("val")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, } = await root.pathToLeaf(tree.ndb, str("a")); const idx = pathToLeafIndex(path); expect(idx).toBe(0n); }); it("should calculate index for rightmost leaf", async () => { const tree = await createTestTree(); // Insert 5 keys await tree.set(str("a"), str("val")); await tree.set(str("b"), str("val")); await tree.set(str("c"), str("val")); await tree.set(str("d"), str("val")); await tree.set(str("e"), str("val")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, } = await root.pathToLeaf(tree.ndb, str("e")); const idx = pathToLeafIndex(path); expect(idx).toBe(4n); // Index 4 (5th element, 0-indexed) }); it("should calculate index for middle leaves", async () => { const tree = await createTestTree(); // Insert 7 keys to create a balanced tree const keys = [ "a", "b", "c", "d", "e", "f", "g", ]; for (const k of keys) { await tree.set(str(k), str(`val-${k}`)); } await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); // Test middle key const { path, } = await root.pathToLeaf(tree.ndb, str("d")); const idx = pathToLeafIndex(path); expect(idx).toBe(3n); // "d" is at index 3 }); it("should return 0 for single-level tree (root is leaf)", async () => { const tree = await createTestTree(); await tree.set(str("only"), str("val")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, } = await root.pathToLeaf(tree.ndb, str("only")); // Empty path (no inner nodes) expect(path).toHaveLength(0); const idx = pathToLeafIndex(path); expect(idx).toBe(0n); }); it("should handle deep left-only path", async () => { const tree = await createTestTree(); // Insert keys that create left-heavy tree // Insert in reverse order to force left-heavy structure for (let i = 10; i >= 1; i--) { await tree.set(str(`key${i.toString().padStart(2, "0")}`), str("val")); } await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, } = await root.pathToLeaf(tree.ndb, str("key01")); const idx = pathToLeafIndex(path); expect(idx).toBe(0n); // First key }); it("should handle deep right-only path", async () => { const tree = await createTestTree(); // Insert keys in ascending order for (let i = 1; i <= 10; i++) { await tree.set(str(`key${i.toString().padStart(2, "0")}`), str("val")); } await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); const { path, } = await root.pathToLeaf(tree.ndb, str("key10")); const idx = pathToLeafIndex(path); expect(idx).toBe(9n); // Last key (10th element, index 9) }); it("should match manual index calculation", async () => { const tree = await createTestTree(); // Create known structure const keys = [ "apple", "banana", "cherry", "date", "elderberry", ]; for (const k of keys) { await tree.set(str(k), str(`val-${k}`)); } await tree.saveVersion(); const immutable = tree.getWorkingTree(); const root = immutable.getRoot(); if (!root) throw new Error("Root should exist"); // Verify each key's index matches its position for (let i = 0; i < keys.length; i++) { const { path, } = await root.pathToLeaf(tree.ndb, str(keys[i])); const idx = pathToLeafIndex(path); expect(Number(idx)).toBe(i); } }); it("should return -1 for invalid path (both left and right set)", () => { // Create an invalid path where both left and right are set const invalidPath = [ { height: 1, size: 2n, version: 1n, left: new Uint8Array([ 1, 2, 3, ]), right: new Uint8Array([ 4, 5, 6, ]), // Both set - invalid! hash: () => new Uint8Array(), toString: () => "invalid", }, ]; const idx = pathToLeafIndex(invalidPath); expect(idx).toBe(-1n); }); it("should handle empty path", () => { const emptyPath: ProofInnerNode[] = []; const idx = pathToLeafIndex(emptyPath); expect(idx).toBe(0n); // No traversal = index 0 }); }); describe("pathToLeafToString - string representation", () => { it("should return 'empty-PathToLeaf' for empty path", async () => { const { pathToLeafToString, } = await import("./path-to-leaf.js"); const emptyPath: ProofInnerNode[] = []; const str = pathToLeafToString(emptyPath); expect(str).toBe("empty-PathToLeaf"); }); it("should format single-node path", async () => { const { pathToLeafToString, } = await import("./path-to-leaf.js"); const path = [ { height: 1, size: 2n, version: 1n, left: null, right: new Uint8Array([ 1, 2, 3, ]), hash: () => new Uint8Array(), toString: () => "InnerNode[h=1 s=2 v=1 right=010203]", }, ]; const str = pathToLeafToString(path); expect(str).toContain("PathToLeaf{"); expect(str).toContain("0:InnerNode"); expect(str).toContain("}"); }); it("should format multiple-node path", async () => { const { pathToLeafToString, } = await import("./path-to-leaf.js"); const path = [ { height: 2, size: 4n, version: 1n, left: null, right: new Uint8Array([1, 2]), hash: () => new Uint8Array(), toString: () => "Node1", }, { height: 1, size: 2n, version: 1n, left: new Uint8Array([3, 4]), right: null, hash: () => new Uint8Array(), toString: () => "Node2", }, ]; const str = pathToLeafToString(path); expect(str).toContain("0:Node1"); expect(str).toContain("1:Node2"); }); it("should use custom indentation", async () => { const { pathToLeafToString, } = await import("./path-to-leaf.js"); const path = [ { height: 1, size: 2n, version: 1n, left: null, right: new Uint8Array([1]), hash: () => new Uint8Array(), toString: () => "Node", }, ]; const str = pathToLeafToString(path, " "); // 4 spaces expect(str).toContain(" "); // Should use custom indent }); it("should truncate very long paths (>20 nodes)", async () => { const { pathToLeafToString, } = await import("./path-to-leaf.js"); // Create path with 25 nodes const longPath = Array.from({ length: 25, }, (_, i) => ({ height: i + 1, size: BigInt((i + 1) * 2), version: 1n, left: i % 2 === 0 ? new Uint8Array([i]) : null, right: i % 2 === 1 ? new Uint8Array([i]) : null, hash: () => new Uint8Array(), toString: () => `Node${i}`, })); const str = pathToLeafToString(longPath); expect(str).toContain("... (25 total)"); // Should show truncation expect(str).not.toContain("Node24"); // Last node shouldn't be shown }); it("should handle path with multiline node strings", async () => { const { pathToLeafToString, } = await import("./path-to-leaf.js"); const path = [ { height: 1, size: 2n, version: 1n, left: null, right: new Uint8Array([1]), hash: () => new Uint8Array(), toString: () => "Line1\nLine2\nLine3", // Multiline }, ]; const str = pathToLeafToString(path, " "); // Should indent each line of the node string expect(str).toContain("Line1"); expect(str).toContain("Line2"); expect(str).toContain("Line3"); }); }); });