/** * ICS23 Proof Verification * Implements verification logic for ICS23 existence and non-existence proofs * Based on Go ics23 v0.10.0 proof.go and ics23.go */ import type { CommitmentProof, ExistenceProof, InnerOp, InnerSpec, NonExistenceProof, ProofSpec, } from "../generated/cosmos/ics23/v1/proofs.js"; import { compareBytes, } from "../utils/bytes.js"; import { applyInner, applyLeaf, checkInnerOp, checkLeafOp, getPadding, hasPadding, } from "./ics23-ops.js"; /** Commitment root is the merkle root hash */ export type CommitmentRoot = Uint8Array; /** * Verify membership proof * Returns true iff proof contains valid ExistenceProof for key/value that hashes to root * Based on Go ics23 VerifyMembership (ics23.go lines 33-45) */ export function verifyMembership( spec: ProofSpec, root: CommitmentRoot, proof: CommitmentProof, key: Uint8Array, value: Uint8Array, ): boolean { // Get existence proof for key const ep = getExistProofForKey(proof, key); if (!ep) { return false; } // Verify the existence proof try { verifyExistenceProof(ep, spec, root, key, value); return true; } catch { return false; } } /** * Verify non-membership proof * Returns true iff proof contains valid NonExistenceProof that key is not in tree * Based on Go ics23 VerifyNonMembership (ics23.go lines 47-61) */ export function verifyNonMembership( spec: ProofSpec, root: CommitmentRoot, proof: CommitmentProof, key: Uint8Array, ): boolean { // Get non-existence proof for key const np = getNonExistProofForKey(spec, proof, key); if (!np) { return false; } // Verify the non-existence proof try { verifyNonExistenceProof(np, spec, root, key); return true; } catch { return false; } } /** * Verify ExistenceProof * Checks proof structure, key/value match, and root calculation * Based on Go ics23 ExistenceProof.Verify (proof.go lines 110-131) */ export function verifyExistenceProof( proof: ExistenceProof, spec: ProofSpec, root: CommitmentRoot, key: Uint8Array, value: Uint8Array, ): void { // Check proof against spec checkExistenceProof(proof, spec); // Verify key matches if (compareBytes(key, proof.key) !== 0) { throw new Error("provided key doesn't match proof"); } // Verify value matches if (compareBytes(value, proof.value) !== 0) { throw new Error("provided value doesn't match proof"); } // Calculate root from proof const calc = calculateExistenceRoot(proof); // Verify calculated root matches provided root if (compareBytes(root, calc) !== 0) { throw new Error("calculated root doesn't match provided root"); } } /** * Verify NonExistenceProof * Checks neighbor proofs are valid and bracket the key * Based on Go ics23 NonExistenceProof.Verify (proof.go lines 219-271) */ export function verifyNonExistenceProof( proof: NonExistenceProof, spec: ProofSpec, root: CommitmentRoot, key: Uint8Array, ): void { let leftKey: Uint8Array | null = null; let rightKey: Uint8Array | null = null; // Verify left proof if present if (proof.left) { verifyExistenceProof(proof.left, spec, root, proof.left.key, proof.left.value); leftKey = proof.left.key; } // Verify right proof if present if (proof.right) { verifyExistenceProof( proof.right, spec, root, proof.right.key, proof.right.value, ); rightKey = proof.right.key; } // At least one proof must be present if (!leftKey && !rightKey) { throw new Error("both left and right proofs missing"); } // Verify key is in valid range if (rightKey) { const keyComp = keyForComparison(spec, key); const rightKeyComp = keyForComparison(spec, rightKey); if (compareBytes(keyComp, rightKeyComp) >= 0) { throw new Error("key is not left of right proof"); } } if (leftKey) { const keyComp = keyForComparison(spec, key); const leftKeyComp = keyForComparison(spec, leftKey); if (compareBytes(keyComp, leftKeyComp) <= 0) { throw new Error("key is not right of left proof"); } } // Verify neighbor relationship if (!leftKey) { // Left proof missing, right must be leftmost if (proof.right && !isLeftMost(spec.innerSpec!, proof.right.path)) { throw new Error("left proof missing, right proof must be left-most"); } } else if (!rightKey) { // Right proof missing, left must be rightmost if (proof.left && !isRightMost(spec.innerSpec!, proof.left.path)) { throw new Error("right proof missing, left proof must be right-most"); } } else { // Both present, must be neighbors if (proof.left && proof.right && !isLeftNeighbor(spec.innerSpec!, proof.left.path, proof.right.path)) { throw new Error("left and right proofs are not neighbors"); } } } /** * Check ExistenceProof structure against spec * Based on Go ics23 ExistenceProof.CheckAgainstSpec (proof.go lines 182-206) */ export function checkExistenceProof( proof: ExistenceProof, spec: ProofSpec, ): void { if (!proof.leaf) { throw new Error("existence Proof needs defined LeafOp"); } // Check leaf op checkLeafOp(proof.leaf, spec); // Check depth constraints if (spec.minDepth > 0 && proof.path.length < spec.minDepth) { throw new Error(`innerOps depth too short: ${proof.path.length}`); } if (spec.maxDepth > 0 && proof.path.length > spec.maxDepth) { throw new Error(`innerOps depth too long: ${proof.path.length}`); } // Check each inner op let layerNum = 1; for (const inner of proof.path) { checkInnerOp(inner, spec, layerNum); layerNum += 1; } } /** * Calculate root hash from ExistenceProof * Based on Go ics23 ExistenceProof.calculate (proof.go lines 140-164) */ export function calculateExistenceRoot( proof: ExistenceProof, ): CommitmentRoot { if (!proof.leaf) { throw new Error("existence Proof needs defined LeafOp"); } // Apply leaf op to get leaf hash let res = applyLeaf(proof.leaf, proof.key, proof.value); // Apply each inner op in sequence for (const step of proof.path) { res = applyInner(step, res); } return res; } /** * Get key for comparison (prehash if spec requires it) * Based on Go ics23 keyForComparison (proof.go lines 208-217) */ function keyForComparison(spec: ProofSpec, key: Uint8Array): Uint8Array { if (!spec.prehashKeyBeforeComparison) { return key; } const prehashKey = spec.leafSpec?.prehashKey ?? 0; if (prehashKey === 0) { // NO_HASH return key; } // Hash the key return doHashOrNoop(prehashKey, key); } // Import doHashOrNoop from ops import { doHashOrNoop, } from "./ics23-ops.js"; /** * Check if path is leftmost (all steps go left) * Based on Go ics23 IsLeftMost (proof.go lines 273-284) */ function isLeftMost(spec: InnerSpec, path: InnerOp[]): boolean { const { minPrefix, maxPrefix, suffix, } = getPadding(spec, 0); // Every step must have expected padding for leftmost for (const step of path) { if (!hasPadding(step, minPrefix, maxPrefix, suffix) && !leftBranchesAreEmpty(spec, step)) { return false; } } return true; } /** * Check if path is rightmost (all steps go right) * Based on Go ics23 IsRightMost (proof.go lines 286-298) */ function isRightMost(spec: InnerSpec, path: InnerOp[]): boolean { const last = spec.childOrder.length - 1; const { minPrefix, maxPrefix, suffix, } = getPadding(spec, last); // Every step must have expected padding for rightmost for (const step of path) { if (!hasPadding(step, minPrefix, maxPrefix, suffix) && !rightBranchesAreEmpty(spec, step)) { return false; } } return true; } /** * Check if left and right are adjacent paths * Based on Go ics23 IsLeftNeighbor (proof.go lines 300-330) */ function isLeftNeighbor( spec: InnerSpec, left: InnerOp[], right: InnerOp[], ): boolean { // Find common suffix (from end, near root) const leftPath = [...left]; const rightPath = [...right]; if (leftPath.length === 0 || rightPath.length === 0) { return false; } // Remove common tail while (leftPath.length > 0 && rightPath.length > 0) { const leftTop = leftPath[leftPath.length - 1]; const rightTop = rightPath[rightPath.length - 1]; if (!bytesEqual(leftTop.prefix, rightTop.prefix) || !bytesEqual(leftTop.suffix, rightTop.suffix)) { break; } leftPath.pop(); rightPath.pop(); } if (leftPath.length === 0 || rightPath.length === 0) { return false; } // Get first divergent nodes const topLeft = leftPath[leftPath.length - 1]; const topRight = rightPath[rightPath.length - 1]; // Check they are left and right of each other if (!isLeftStep(spec, topLeft, topRight)) { return false; } // Remove the divergent nodes leftPath.pop(); rightPath.pop(); // Check left child is rightmost path below split if (!isRightMost(spec, leftPath)) { return false; } // Check right child is leftmost path below split if (!isLeftMost(spec, rightPath)) { return false; } return true; } /** * Check if left is exactly one slot to the left of right * Based on Go ics23 isLeftStep (proof.go lines 332-346) */ function isLeftStep(spec: InnerSpec, left: InnerOp, right: InnerOp): boolean { const leftIdx = orderFromPadding(spec, left); const rightIdx = orderFromPadding(spec, right); return rightIdx === leftIdx + 1; } /** * Determine branch order from padding * Based on Go ics23 orderFromPadding (proof.go lines 442-451) */ function orderFromPadding(spec: InnerSpec, inner: InnerOp): number { const maxBranch = spec.childOrder.length; for (let branch = 0; branch < maxBranch; branch++) { const { minPrefix, maxPrefix, suffix, } = getPadding(spec, branch); if (hasPadding(inner, minPrefix, maxPrefix, suffix)) { return branch; } } throw new Error("cannot determine order from padding"); } /** * Check if left branches are all empty (placeholder nodes) * Based on Go ics23 leftBranchesAreEmpty (proof.go lines 373-398) */ function leftBranchesAreEmpty(spec: InnerSpec, op: InnerOp): boolean { const idx = orderFromPadding(spec, op); const leftBranches = idx; if (leftBranches === 0) { return false; } // Calculate actual prefix length (excluding child hashes) const actualPrefix = op.prefix.length - leftBranches * spec.childSize; if (actualPrefix < 0) { return false; } // Check each left branch is empty child if (!spec.emptyChild || spec.emptyChild.length === 0) { return false; // No empty child defined } for (let i = 0; i < leftBranches; i++) { const position = getPosition(spec.childOrder, i); const from = actualPrefix + position * spec.childSize; const childSlice = op.prefix.slice(from, from + spec.childSize); if (!bytesEqual(spec.emptyChild, childSlice)) { return false; } } return true; } /** * Check if right branches are all empty (placeholder nodes) * Based on Go ics23 rightBranchesAreEmpty (proof.go lines 400-424) */ function rightBranchesAreEmpty(spec: InnerSpec, op: InnerOp): boolean { const idx = orderFromPadding(spec, op); const rightBranches = spec.childOrder.length - 1 - idx; if (rightBranches === 0) { return false; } // Sanity check suffix length if (op.suffix.length !== rightBranches * spec.childSize) { return false; } // Check each right branch is empty child if (!spec.emptyChild || spec.emptyChild.length === 0) { return false; // No empty child defined } for (let i = 0; i < rightBranches; i++) { const position = getPosition(spec.childOrder, i); const from = position * spec.childSize; const childSlice = op.suffix.slice(from, from + spec.childSize); if (!bytesEqual(spec.emptyChild, childSlice)) { return false; } } return true; } // Re-export getPosition from ops import { getPosition, } from "./ics23-ops.js"; /** * Extract ExistenceProof for specific key from CommitmentProof * Based on Go ics23 getExistProofForKey (ics23.go lines 134-149) */ function getExistProofForKey( proof: CommitmentProof, key: Uint8Array, ): ExistenceProof | null { // Check exist field if (proof.exist) { if (bytesEqual(proof.exist.key, key)) { return proof.exist; } } // Check batch entries if (proof.batch) { for (const entry of proof.batch.entries) { if (entry.exist && bytesEqual(entry.exist.key, key)) { return entry.exist; } } } return null; } /** * Extract NonExistenceProof for specific key from CommitmentProof * Based on Go ics23 getNonExistProofForKey (ics23.go lines 151-166) */ function getNonExistProofForKey( spec: ProofSpec, proof: CommitmentProof, key: Uint8Array, ): NonExistenceProof | null { // Check nonexist field if (proof.nonexist) { const np = proof.nonexist; if (isLeft(spec, np.left, key) && isRight(spec, np.right, key)) { return np; } } // Check batch entries if (proof.batch) { for (const entry of proof.batch.entries) { const np = entry.nonexist; if (np && isLeft(spec, np.left, key) && isRight(spec, np.right, key)) { return np; } } } return null; } /** * Check if left proof is to the left of key * Based on Go ics23 isLeft (ics23.go lines 168-170) */ function isLeft( spec: ProofSpec, left: ExistenceProof | undefined, key: Uint8Array, ): boolean { if (!left) { return true; // No left proof is valid } const leftKeyComp = keyForComparison(spec, left.key); const keyComp = keyForComparison(spec, key); return compareBytes(leftKeyComp, keyComp) < 0; } /** * Check if right proof is to the right of key * Based on Go ics23 isRight (ics23.go lines 172-174) */ function isRight( spec: ProofSpec, right: ExistenceProof | undefined, key: Uint8Array, ): boolean { if (!right) { return true; // No right proof is valid } const rightKeyComp = keyForComparison(spec, right.key); const keyComp = keyForComparison(spec, key); return compareBytes(rightKeyComp, keyComp) > 0; } /** * Helper: Compare two byte arrays for equality */ function bytesEqual(a: Uint8Array, b: Uint8Array): boolean { if (a.length !== b.length) { return false; } for (let i = 0; i < a.length; i++) { if (a[i] !== b[i]) { return false; } } return true; }