/** * Edge case tests for ICS23 proof verification * Covers error paths, boundary conditions, and special scenarios * Target: Bring ics23-verify.ts from 65.59% to 85%+ coverage */ import { afterAll, beforeAll, describe, expect, it, } from "vitest"; import { createTestDb, } from "../db/test-db-factory.js"; import { CommitmentProof, ProofSpec, } from "../generated/cosmos/ics23/v1/proofs.js"; import { HashOp, LengthOp, } from "../generated/cosmos/ics23/v1/proofs.js"; import { ImmutableTree, } from "../immutable-tree.js"; import { MutableTree, } from "../mutable-tree.js"; import { NodeDB, } from "../storage/node-db.js"; import { DEFAULT_OPTIONS, } from "../types/options.js"; import { IavlSpec, } from "./ics23-convert.js"; import { verifyMembership, verifyNonMembership, } from "./ics23-verify.js"; /** * Helper to convert string to Uint8Array */ function str(s: string): Uint8Array { return new TextEncoder().encode(s); } /** * Helper to create a test tree with some data */ async function createTestTree(): Promise<{ tree: MutableTree cleanup: () => Promise }> { const ctx = await createTestDb(); const ndb = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS); await ndb.initialize(); const workingTree = await ndb.getImmutableTree(0n); return { tree: new MutableTree(ndb, workingTree, true), cleanup: ctx.cleanup, }; } describe("ICS23 Verification Edge Cases", () => { describe("Non-existence proofs with single neighbor", () => { let tree: MutableTree; let immutable: ImmutableTree; let cleanup: () => Promise; beforeAll(async () => { const testTree = await createTestTree(); tree = testTree.tree; cleanup = testTree.cleanup; // Create tree with keys: a, c, e (skipping b and d for non-existence tests) await tree.set(str("a"), str("val-a")); await tree.set(str("c"), str("val-c")); await tree.set(str("e"), str("val-e")); const { version, } = await tree.saveVersion(); immutable = await tree.getImmutable(version); }); afterAll(async () => { await cleanup(); }); it("should verify non-existence proof with only left neighbor", async () => { // Key "d" doesn't exist, should have left neighbor "c" and right neighbor "e" const proof = await immutable.getNonMembershipProof(str("d")); expect(proof.nonexist).toBeDefined(); expect(proof.nonexist?.left).toBeDefined(); expect(proof.nonexist?.right).toBeDefined(); // Verify the proof const rootHash = immutable.hash(); expect(rootHash).not.toBeNull(); const isValid = verifyNonMembership(IavlSpec, rootHash!, proof, str("d")); expect(isValid).toBe(true); }); it("should verify non-existence for key before first (only right neighbor)", async () => { // Key "0" is before "a" - should only have right neighbor "a" const proof = await immutable.getNonMembershipProof(str("0")); expect(proof.nonexist).toBeDefined(); const nonExist = proof.nonexist!; // Should have right neighbor (first key "a"), no left neighbor expect(nonExist.right).toBeDefined(); // Left might be null or undefined const rootHash = immutable.hash(); expect(rootHash).not.toBeNull(); const isValid = verifyNonMembership(IavlSpec, rootHash!, proof, str("0")); expect(isValid).toBe(true); }); it("should verify non-existence for key after last (only left neighbor)", async () => { // Key "z" is after "e" - should only have left neighbor "e" const proof = await immutable.getNonMembershipProof(str("z")); expect(proof.nonexist).toBeDefined(); const nonExist = proof.nonexist!; // Should have left neighbor (last key "e"), no right neighbor expect(nonExist.left).toBeDefined(); // Right might be null or undefined const rootHash = immutable.hash(); expect(rootHash).not.toBeNull(); const isValid = verifyNonMembership(IavlSpec, rootHash!, proof, str("z")); expect(isValid).toBe(true); }); }); describe("Multi-level proof paths (multiple InnerOps)", () => { it("should verify proof with multiple inner operations", async () => { const { tree, cleanup, } = await createTestTree(); // Create deeper tree with 10 keys to ensure multiple levels for (let i = 0; i < 10; i++) { await tree.set(str(`key${i}`), str(`val${i}`)); } const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); // Get proof for middle key const proof = await immutable.getMembershipProof(str("key5")); expect(proof.exist).toBeDefined(); const exist = proof.exist!; // With 10 keys, tree should have depth > 1, meaning multiple InnerOps expect(exist.path.length).toBeGreaterThan(1); // Verify the proof const rootHash = immutable.hash(); const value = await immutable.get(str("key5")); const isValid = verifyMembership(IavlSpec, rootHash!, proof, str("key5"), value!); expect(isValid).toBe(true); await cleanup(); }); it("should verify proof with deep tree (15+ keys)", async () => { const { tree, cleanup, } = await createTestTree(); // Create even deeper tree for (let i = 0; i < 15; i++) { await tree.set(str(`k${i.toString().padStart(2, "0")}`), str(`v${i}`)); } const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); // Get proof for a key const proof = await immutable.getMembershipProof(str("k07")); expect(proof.exist).toBeDefined(); const exist = proof.exist!; // Should have multiple inner ops expect(exist.path.length).toBeGreaterThan(2); // Verify const rootHash = immutable.hash(); const value = await immutable.get(str("k07")); const isValid = verifyMembership(IavlSpec, rootHash!, proof, str("k07"), value!); expect(isValid).toBe(true); await cleanup(); }); }); describe("Batch proof support", () => { it("should handle CommitmentProof with batch existence entries", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("key1"), str("val1")); await tree.set(str("key2"), str("val2")); const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); // Get individual proofs const proof1 = await immutable.getMembershipProof(str("key1")); const proof2 = await immutable.getMembershipProof(str("key2")); // Create batch proof manually const batchProof: CommitmentProof = { exist: undefined, nonexist: undefined, batch: { entries: [proof1, proof2], }, compressed: undefined, }; // Verify batch proof for key1 const rootHash = immutable.hash(); const value1 = await immutable.get(str("key1")); const isValid = verifyMembership(IavlSpec, rootHash!, batchProof, str("key1"), value1!); expect(isValid).toBe(true); await cleanup(); }); it("should handle CommitmentProof with batch non-existence entries", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("a"), str("val-a")); await tree.set(str("c"), str("val-c")); const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); // Get non-existence proof for "b" const proofB = await immutable.getNonMembershipProof(str("b")); // Create batch proof manually const batchProof: CommitmentProof = { exist: undefined, nonexist: undefined, batch: { entries: [proofB], }, compressed: undefined, }; // Verify batch proof for key "b" const rootHash = immutable.hash(); const isValid = verifyNonMembership(IavlSpec, rootHash!, batchProof, str("b")); expect(isValid).toBe(true); await cleanup(); }); it("should return false for key not in batch", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("key1"), str("val1")); const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); const proof1 = await immutable.getMembershipProof(str("key1")); // Create batch proof const batchProof: CommitmentProof = { exist: undefined, nonexist: undefined, batch: { entries: [proof1], }, compressed: undefined, }; // Try to verify a different key not in batch const rootHash = immutable.hash(); const isValid = verifyMembership(IavlSpec, rootHash!, batchProof, str("key2"), str("val2")); expect(isValid).toBe(false); await cleanup(); }); }); describe("Invalid proof scenarios", () => { it("should reject existence proof with wrong root hash", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("key"), str("val")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const proof = await immutable.getMembershipProof(str("key")); // Use wrong root hash const wrongRoot = new Uint8Array(32).fill(0xFF); const value = await immutable.get(str("key")); const isValid = verifyMembership(IavlSpec, wrongRoot, proof, str("key"), value!); expect(isValid).toBe(false); await cleanup(); }); it("should reject existence proof with wrong key", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("key1"), str("val1")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const proof = await immutable.getMembershipProof(str("key1")); const rootHash = immutable.hash(); const value = await immutable.get(str("key1")); // Verify with different key const isValid = verifyMembership(IavlSpec, rootHash!, proof, str("key2"), value!); expect(isValid).toBe(false); await cleanup(); }); it("should reject existence proof with wrong value", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("key"), str("val")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const proof = await immutable.getMembershipProof(str("key")); const rootHash = immutable.hash(); // Verify with different value const isValid = verifyMembership(IavlSpec, rootHash!, proof, str("key"), str("wrong-value")); expect(isValid).toBe(false); await cleanup(); }); it("should reject non-existence proof for existing key", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("exists"), str("value")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); // Try to get non-existence proof for existing key (should error) await expect(async () => { await immutable.getNonMembershipProof(str("exists")); }).rejects.toThrow(); await cleanup(); }); it("should reject membership proof for non-existent key", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("a"), str("val")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); // getMembershipProof returns undefined for non-existent keys (doesn't throw) // This is actually handled by returning undefined, not throwing // Let's verify we can't verify a proof for wrong key const proofA = await immutable.getMembershipProof(str("a")); const rootHash = immutable.hash(); // Try to verify proof for key "a" but claim it's for key "b" const isValid = verifyMembership(IavlSpec, rootHash!, proofA, str("b"), str("val")); expect(isValid).toBe(false); await cleanup(); }); }); describe("Empty and null handling", () => { it("should handle proof verification with empty tree", async () => { const { tree, cleanup, } = await createTestTree(); const immutable = tree.getWorkingTree(); // Empty tree has null root hash const rootHash = immutable.hash(); expect(rootHash).toBeNull(); // Can't get proofs from empty tree - would throw // Just verify the root hash is null expect(immutable.isEmpty()).toBe(true); await cleanup(); }); it("should reject proof with empty commitment root", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("key"), str("val")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const proof = await immutable.getMembershipProof(str("key")); const value = await immutable.get(str("key")); // Empty root const emptyRoot = new Uint8Array(0); const isValid = verifyMembership(IavlSpec, emptyRoot, proof, str("key"), value!); expect(isValid).toBe(false); await cleanup(); }); }); describe("Spec validation edge cases", () => { it("should reject proof with mismatched spec", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("key"), str("val")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const proof = await immutable.getMembershipProof(str("key")); const rootHash = immutable.hash(); const value = await immutable.get(str("key")); // Create invalid spec (different from IAVL spec) const invalidSpec: ProofSpec = { leafSpec: { hash: HashOp.SHA512, // Wrong hash (IAVL uses SHA256) prehashKey: HashOp.NO_HASH, prehashValue: HashOp.SHA256, length: LengthOp.VAR_PROTO, prefix: new Uint8Array([ 0, 1, 0, ]), // Wrong prefix }, innerSpec: IavlSpec.innerSpec, minDepth: 0, maxDepth: 0, prehashKeyBeforeComparison: false, }; const isValid = verifyMembership(invalidSpec, rootHash!, proof, str("key"), value!); expect(isValid).toBe(false); await cleanup(); }); }); describe("Neighbor validation scenarios", () => { it("should validate adjacent neighbors in non-existence proof", async () => { const { tree, cleanup, } = await createTestTree(); // Create tree with specific gaps await tree.set(str("apple"), str("val1")); await tree.set(str("cherry"), str("val2")); await tree.set(str("elderberry"), str("val3")); const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); // Get non-existence proof for "banana" (between apple and cherry) const proof = await immutable.getNonMembershipProof(str("banana")); expect(proof.nonexist).toBeDefined(); const nonExist = proof.nonexist!; // Should have both left (apple) and right (cherry) neighbors expect(nonExist.left).toBeDefined(); expect(nonExist.right).toBeDefined(); // Verify const rootHash = immutable.hash(); const isValid = verifyNonMembership(IavlSpec, rootHash!, proof, str("banana")); expect(isValid).toBe(true); await cleanup(); }); it("should validate non-existence at tree boundaries", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("m"), str("middle")); const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); // Test before first key const proofBefore = await immutable.getNonMembershipProof(str("a")); const rootHash = immutable.hash(); const isValidBefore = verifyNonMembership(IavlSpec, rootHash!, proofBefore, str("a")); expect(isValidBefore).toBe(true); // Test after last key const proofAfter = await immutable.getNonMembershipProof(str("z")); const isValidAfter = verifyNonMembership(IavlSpec, rootHash!, proofAfter, str("z")); expect(isValidAfter).toBe(true); await cleanup(); }); }); describe("Proof structure validation", () => { it("should handle proof with no inner operations (single leaf tree)", async () => { const { tree, cleanup, } = await createTestTree(); // Single key tree await tree.set(str("only"), str("value")); const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); const proof = await immutable.getMembershipProof(str("only")); expect(proof.exist).toBeDefined(); const exist = proof.exist!; // Single leaf should have empty path expect(exist.path).toHaveLength(0); // Should still verify correctly const rootHash = immutable.hash(); const value = await immutable.get(str("only")); const isValid = verifyMembership(IavlSpec, rootHash!, proof, str("only"), value!); expect(isValid).toBe(true); await cleanup(); }); it("should handle proof with exactly one inner operation", async () => { const { tree, cleanup, } = await createTestTree(); // Two keys create exactly one inner node await tree.set(str("a"), str("val1")); await tree.set(str("b"), str("val2")); const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); const proof = await immutable.getMembershipProof(str("a")); expect(proof.exist).toBeDefined(); const exist = proof.exist!; // Should have exactly 1 inner operation expect(exist.path).toHaveLength(1); const rootHash = immutable.hash(); const value = await immutable.get(str("a")); const isValid = verifyMembership(IavlSpec, rootHash!, proof, str("a"), value!); expect(isValid).toBe(true); await cleanup(); }); }); describe("Invalid proof structures", () => { it("should reject proof without exist or nonexist fields", async () => { // Create malformed proof const emptyProof: CommitmentProof = { exist: undefined, nonexist: undefined, batch: undefined, compressed: undefined, }; const isValid = verifyMembership( IavlSpec, new Uint8Array(32), emptyProof, str("key"), str("value"), ); expect(isValid).toBe(false); }); it("should reject non-existence proof without left or right", async () => { // Create malformed non-existence proof (missing both neighbors) const invalidProof: CommitmentProof = { exist: undefined, nonexist: { key: str("missing"), left: undefined, right: undefined, }, batch: undefined, compressed: undefined, }; const isValid = verifyNonMembership( IavlSpec, new Uint8Array(32), invalidProof, str("missing"), ); expect(isValid).toBe(false); }); }); describe("Compressed proofs (unsupported)", () => { it("should return false for compressed proofs", () => { const compressedProof: CommitmentProof = { exist: undefined, nonexist: undefined, batch: undefined, compressed: { entries: [], }, }; const isValid = verifyMembership( IavlSpec, new Uint8Array(32), compressedProof, str("key"), str("value"), ); expect(isValid).toBe(false); }); it("should return false for compressed non-existence proofs", () => { const compressedProof: CommitmentProof = { exist: undefined, nonexist: undefined, batch: undefined, compressed: { entries: [], }, }; const isValid = verifyNonMembership( IavlSpec, new Uint8Array(32), compressedProof, str("key"), ); expect(isValid).toBe(false); }); }); describe("Error handling in verification", () => { it("should handle malformed leaf op", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(str("key"), str("val")); await tree.saveVersion(); const immutable = tree.getWorkingTree(); const proof = await immutable.getMembershipProof(str("key")); // Corrupt the leaf op if (proof.exist) { proof.exist.leaf = { hash: HashOp.NO_HASH, // Invalid for IAVL prehashKey: HashOp.NO_HASH, prehashValue: HashOp.NO_HASH, length: LengthOp.NO_PREFIX, prefix: new Uint8Array(), }; } const rootHash = immutable.hash(); const value = await immutable.get(str("key")); const isValid = verifyMembership(IavlSpec, rootHash!, proof, str("key"), value!); expect(isValid).toBe(false); await cleanup(); }); it("should handle malformed inner op", async () => { const { tree, cleanup, } = await createTestTree(); // Create tree with multiple levels for (let i = 0; i < 5; i++) { await tree.set(str(`k${i}`), str(`v${i}`)); } await tree.saveVersion(); const immutable = tree.getWorkingTree(); const proof = await immutable.getMembershipProof(str("k2")); // Corrupt an inner op if (proof.exist && proof.exist.path.length > 0) { proof.exist.path[0] = { hash: HashOp.NO_HASH, // Invalid prefix: new Uint8Array(), suffix: new Uint8Array(), }; } const rootHash = immutable.hash(); const value = await immutable.get(str("k2")); const isValid = verifyMembership(IavlSpec, rootHash!, proof, str("k2"), value!); expect(isValid).toBe(false); await cleanup(); }); }); describe("Binary key/value support", () => { it("should verify proofs with binary (non-UTF8) keys", async () => { const { tree, cleanup, } = await createTestTree(); // Binary keys const binaryKey = new Uint8Array([ 0x00, 0x01, 0xFF, 0xFE, ]); const binaryValue = new Uint8Array([ 0xDE, 0xAD, 0xBE, 0xEF, ]); await tree.set(binaryKey, binaryValue); const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); const proof = await immutable.getMembershipProof(binaryKey); const rootHash = immutable.hash(); const value = await immutable.get(binaryKey); const isValid = verifyMembership(IavlSpec, rootHash!, proof, binaryKey, value!); expect(isValid).toBe(true); await cleanup(); }); it("should verify non-existence proofs with binary keys", async () => { const { tree, cleanup, } = await createTestTree(); await tree.set(new Uint8Array([0x00]), str("val1")); await tree.set(new Uint8Array([0xFF]), str("val2")); const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); // Non-existent binary key in middle const missingKey = new Uint8Array([0x7F]); const proof = await immutable.getNonMembershipProof(missingKey); const rootHash = immutable.hash(); const isValid = verifyNonMembership(IavlSpec, rootHash!, proof, missingKey); expect(isValid).toBe(true); await cleanup(); }); }); describe("Large value proofs", () => { it("should verify proof with large value (1KB+)", async () => { const { tree, cleanup, } = await createTestTree(); const largeValue = new Uint8Array(2000).fill(0xAB); await tree.set(str("big"), largeValue); const { version, } = await tree.saveVersion(); const immutable = await tree.getImmutable(version); const proof = await immutable.getMembershipProof(str("big")); const rootHash = immutable.hash(); const value = await immutable.get(str("big")); const isValid = verifyMembership(IavlSpec, rootHash!, proof, str("big"), value!); expect(isValid).toBe(true); await cleanup(); }); }); });