/** * PathToLeaf represents an inner path to a leaf node. * * Note: Based on the Go construction code (not the comment which appears incorrect), * the nodes are ordered from ROOT (index 0) to LEAF's parent (last index). * The construction appends before recursing, so path[0] is added at root level. * * Based on Go IAVL v1.3.5 proof_path.go PathToLeaf */ import type { ProofInnerNode, } from "./proof-inner-node.js"; /** * PathToLeaf is an array of ProofInnerNodes representing the path from root to a leaf. * The nodes are ordered from the root (index 0) to the leaf's parent (last index). */ export type PathToLeaf = ProofInnerNode[]; /** * Calculate the index of the leaf node from the path. * * The path is ordered ROOT to LEAF (path[0] is root, path[len-1] is leaf's parent). * * The index is computed by examining which side (left or right) we traversed * at each level, and accumulating the offset based on the sizes of skipped subtrees. * * Key insight from Go implementation: * - When left == null: we traversed LEFT (left sibling doesn't exist), add nothing * - When right == null: we traversed RIGHT (right sibling doesn't exist), add left sibling size * - Left sibling size = current_node.size - child_node.size (we went into the right child) * * Returns -1 if the path is invalid (both left and right are set on any node). * * @param path - The path from root to leaf * @returns The index of the leaf, or -1 if invalid */ export function pathToLeafIndex(path: PathToLeaf): bigint { let idx = 0n; for (let i = 0; i < path.length; i++) { const node = path[i]; // Check which case we're in if (node.left === null) { // We traversed left - no offset added continue; } else if (node.right === null) { // We traversed right - add the left sibling's size // path[i] is current level, path[i+1] is the child we traversed into if (i < path.length - 1) { // Not at leaf yet - left sibling size = current size - right child size idx += node.size - path[i + 1].size; } else { // At leaf's parent - left sibling has all nodes except the leaf (size 1) idx += node.size - 1n; } } else { // Both left and right are set - invalid path return -1n; } } return idx; } /** * String representation of a PathToLeaf for debugging. * * @param path - The path to stringify * @param indent - Optional indentation string * @returns String representation */ export function pathToLeafToString(path: PathToLeaf, indent = ""): string { if (path.length === 0) { return "empty-PathToLeaf"; } const strs: string[] = []; const maxDisplay = 20; for (let i = 0; i < path.length && i < maxDisplay; i++) { const nodeStr = path[i].toString().split("\n").join(`\n${indent} `); strs.push(`${i}:${nodeStr}`); } if (path.length > maxDisplay) { strs.push(`... (${path.length} total)`); } return `PathToLeaf{ ${indent} ${strs.join(`\n${indent} `)} ${indent}}`; }