/** * Node represents a node in the IAVL tree. * Based on the Go iavl node.go implementation. * * A node can be either: * - Leaf node: has key and value, subtreeHeight = 0 * - Branch node: has left and right children, subtreeHeight > 0 */ import type { NodeKey, } from "./node-key.js"; import { NodeKey as NodeKeyClass, } from "./node-key.js"; import { ProofInnerNode, } from "./proof/types.js"; import { decodeBytes, decodeVarint, decodeVarintBigInt, encodeUvarint, encodeVarint, } from "./utils/encoding.js"; import { hash, } from "./utils/hash.js"; /** * Mode constants for node encoding/decoding. * These flags indicate whether child node keys are in legacy format (hash-based) * or v1 format (NodeKey-based). */ const MODE_LEGACY_LEFT_NODE = 0x01; const MODE_LEGACY_RIGHT_NODE = 0x02; /** * Hash size in bytes (SHA-256). */ const HASH_SIZE = 32; /** * Interface for loading nodes from storage. * This allows traversal methods to work without depending on the full tree implementation. */ export interface NodeGetter { /** * Gets a node by its key (12 bytes for v1, 32 bytes for legacy). * @param nodeKey - The node's database key * @returns The node, or null if not found */ getNode(nodeKey: Uint8Array): Promise } /** * Node represents a node in the IAVL tree. * * Leaf nodes: * - Have key and value * - Have subtreeHeight = 0 * - Have size = 1 * - Do not have children * * Branch nodes: * - Have key (from leftmost descendant) * - Have left and right children (references or pointers) * - Have subtreeHeight > 0 * - Have size = sum of children sizes */ export class Node { /** Key for leaf nodes, leftmost descendant key for branch nodes */ key: Uint8Array | null = null; /** Value for leaf nodes only */ value: Uint8Array | null = null; /** Cached hash of the node, computed lazily */ hash: Uint8Array | null = null; /** NodeKey (version + nonce) for this node in the database */ nodeKey: NodeKey | null = null; /** * Left child node key (12 bytes) or legacy hash (32 bytes) * For v1: 12-byte NodeKey * For legacy: 32-byte hash */ leftNodeKey: Uint8Array | null = null; /** * Right child node key (12 bytes) or legacy hash (32 bytes) * For v1: 12-byte NodeKey * For legacy: 32-byte hash */ rightNodeKey: Uint8Array | null = null; /** Cached left child node */ leftNode: Node | null = null; /** Cached right child node */ rightNode: Node | null = null; /** Height of the subtree rooted at this node (0 for leaves) */ subtreeHeight: number = 0; /** Number of nodes in the subtree rooted at this node (1 for leaves) */ size: bigint = 1n; /** * Whether this node uses legacy format (hash-based child references) * Legacy nodes use 32-byte hashes instead of 12-byte NodeKeys */ isLegacy: boolean = false; /** * Creates a new leaf node with the given key and value. * * @param key - The key for this leaf node * @param value - The value for this leaf node * @returns A new leaf node */ static newLeafNode(key: Uint8Array, value: Uint8Array): Node { const node = new Node(); node.key = key; node.value = value; node.subtreeHeight = 0; node.size = 1n; return node; } /** * Creates a new branch node with the given children. * * @param left - The left child node * @param right - The right child node * @returns A new branch node */ static newBranchNode(left: Node, right: Node): Node { const node = new Node(); // Key is the smallest key in the right subtree // This allows search logic: if key < node.key, go left; otherwise go right node.key = right.key; // Set children node.leftNode = left; node.rightNode = right; // Height is 1 + max(left.height, right.height) node.subtreeHeight = 1 + Math.max(left.subtreeHeight, right.subtreeHeight); // Size is sum of children node.size = left.size + right.size; return node; } /** * Checks if this node is a leaf node. * A leaf node has subtreeHeight = 0. * * @returns true if this is a leaf node, false otherwise */ isLeaf(): boolean { return this.subtreeHeight === 0; } /** * Gets the key of this node. * For legacy nodes, returns the hash. * For v1 nodes, returns the NodeKey bytes. * * @returns The node's key as a byte array */ getNodeKey(): Uint8Array { if (this.isLegacy) { if (!this.hash) { throw new Error("Legacy node must have hash"); } return this.hash; } if (!this.nodeKey) { throw new Error("Node must have nodeKey"); } return this.nodeKey.toBytes(); } /** * Gets the balance factor of this node. * Balance factor = left.height - right.height * * @returns The balance factor (-2 to +2 for balanced tree) */ getBalanceFactor(): number { const leftHeight = this.leftNode?.subtreeHeight ?? -1; const rightHeight = this.rightNode?.subtreeHeight ?? -1; return leftHeight - rightHeight; } /** * Recalculates and updates the height and size of this node based on its children. * This should be called after any modification to child nodes. * * IMPORTANT: This method loads children from storage if needed. * For performance, prefer to call this only after structural changes. * * @param getter - NodeGetter for loading child nodes from storage if needed */ async calcHeightAndSize(getter: NodeGetter): Promise { // Load children from storage if needed const leftNode = await this.getLeftNode(getter); const rightNode = await this.getRightNode(getter); // Calculate height: max of children + 1 const leftHeight = leftNode?.subtreeHeight ?? -1; const rightHeight = rightNode?.subtreeHeight ?? -1; this.subtreeHeight = Math.max(leftHeight, rightHeight) + 1; // Calculate size: sum of children const leftSize = leftNode?.size ?? 0n; const rightSize = rightNode?.size ?? 0n; this.size = leftSize + rightSize; } /** * Validates the node structure. * Checks for common invariant violations. * * @returns Error message if invalid, null if valid */ validate(): string | null { if (this.key === null) { return "key cannot be null"; } if (this.nodeKey === null && !this.isLegacy) { return "nodeKey cannot be null for non-legacy nodes"; } if (this.nodeKey && this.nodeKey.version <= 0n) { return "version must be greater than 0"; } if (this.subtreeHeight < 0) { return "height cannot be less than 0"; } if (this.size <= 0n) { return "size must be greater than 0"; } // Leaf node validation if (this.isLeaf()) { if (this.value === null) { return "leaf node must have a value"; } if (this.size !== 1n) { return "leaf node must have size = 1"; } if (this.leftNode !== null || this.rightNode !== null) { return "leaf node cannot have children"; } if (this.leftNodeKey !== null || this.rightNodeKey !== null) { return "leaf node cannot have child keys"; } } else { // Branch node validation if (this.value !== null) { return "branch node cannot have a value"; } // Must have child keys (either loaded children or keys) const hasLeftRef = this.leftNode !== null || this.leftNodeKey !== null; const hasRightRef = this.rightNode !== null || this.rightNodeKey !== null; if (!hasLeftRef) { return "branch node must have left child reference"; } if (!hasRightRef) { return "branch node must have right child reference"; } // If children are loaded, validate height and size if (this.leftNode && this.rightNode) { const expectedHeight = 1 + Math.max( this.leftNode.subtreeHeight, this.rightNode.subtreeHeight, ); if (this.subtreeHeight !== expectedHeight) { return `invalid height: expected ${expectedHeight}, got ${this.subtreeHeight}`; } const expectedSize = this.leftNode.size + this.rightNode.size; if (this.size !== expectedSize) { return `invalid size: expected ${expectedSize}, got ${this.size}`; } } } return null; } /** * Returns a string representation of the node. * Useful for debugging. * * @returns String representation */ toString(): string { const keyStr = this.key ? `key=${this.key.length}B` : "key=null"; const valueStr = this.value ? `value=${this.value.length}B` : "value=null"; const typeStr = this.isLeaf() ? "LEAF" : "BRANCH"; const heightStr = `h=${this.subtreeHeight}`; const sizeStr = `s=${this.size}`; const nodeKeyStr = this.nodeKey ? this.nodeKey.toString() : "nk=null"; return `Node[${typeStr} ${keyStr} ${valueStr} ${heightStr} ${sizeStr} ${nodeKeyStr}]`; } /** * Computes and caches the hash of this node. * The hash is computed based on the node type: * - For leaves: SHA256(height || size || version || key || valueHash) * - For branches: SHA256(height || size || version || leftHash || rightHash) * * @param version - The version to use for hash computation * @returns The 32-byte hash of this node */ computeHash(version: bigint): Uint8Array { // Return cached hash if available if (this.hash !== null) { return this.hash; } // Build the hash input const hashInput = this._buildHashInput(version); // Compute hash and cache it this.hash = hash(hashInput); return this.hash; } /** * Recursively computes and caches hashes for this node and all descendants. * This is used when computing the working hash of a tree that has unsaved nodes. * Corresponds to Go's hashWithCount method. * * @param version - Version to use for hash computation * @returns The computed hash */ computeHashWithDescendants(version: bigint): Uint8Array { // Return cached hash if available if (this.hash !== null) { return this.hash; } // For branch nodes, recursively hash children first if (!this.isLeaf()) { if (this.leftNode) { this.leftNode.computeHashWithDescendants( this.leftNode.nodeKey?.version ?? version, ); } if (this.rightNode) { this.rightNode.computeHashWithDescendants( this.rightNode.nodeKey?.version ?? version, ); } } // Now compute this node's hash return this.computeHash(version); } /** * Builds the byte array to be hashed for this node. * This is the internal implementation that constructs the hash input. * * @param version - The version to use for hash computation * @returns The byte array to be hashed * @private */ private _buildHashInput(version: bigint): Uint8Array { // Encode height, size, and version as varints const heightBytes = encodeVarint(this.subtreeHeight); const sizeBytes = encodeVarint(this.size); const versionBytes = encodeVarint(version); if (this.isLeaf()) { // Leaf node: encode key and value hash if (!this.key) { throw new Error("Leaf node must have key"); } if (!this.value) { throw new Error("Leaf node must have value"); } // Encode key with length prefix const keyBytes = encodeBytes(this.key); // Hash the value and encode the hash const valueHash = hash(this.value); const valueHashBytes = encode32BytesHash(valueHash); // Concatenate all parts const totalLength = heightBytes.length + sizeBytes.length + versionBytes.length + keyBytes.length + valueHashBytes.length; const result = new Uint8Array(totalLength); let offset = 0; result.set(heightBytes, offset); offset += heightBytes.length; result.set(sizeBytes, offset); offset += sizeBytes.length; result.set(versionBytes, offset); offset += versionBytes.length; result.set(keyBytes, offset); offset += keyBytes.length; result.set(valueHashBytes, offset); return result; } else { // Branch node: encode left and right child hashes if (!this.leftNode || !this.rightNode) { throw new Error("Branch node must have both children loaded for hashing"); } // Ensure child hashes are computed // If child is persisted (has nodeKey), compute its hash with its own version if (!this.leftNode.hash) { if (this.leftNode.nodeKey !== null) { this.leftNode.computeHash(this.leftNode.nodeKey.version); } else { throw new Error("Left child hash must be computed before parent"); } } if (!this.rightNode.hash) { if (this.rightNode.nodeKey !== null) { this.rightNode.computeHash(this.rightNode.nodeKey.version); } else { throw new Error("Right child hash must be computed before parent"); } } // Encode child hashes // At this point, hashes are guaranteed to be non-null (computed above) const leftHashBytes = encode32BytesHash(this.leftNode.hash!); const rightHashBytes = encode32BytesHash(this.rightNode.hash!); // Concatenate all parts const totalLength = heightBytes.length + sizeBytes.length + versionBytes.length + leftHashBytes.length + rightHashBytes.length; const result = new Uint8Array(totalLength); let offset = 0; result.set(heightBytes, offset); offset += heightBytes.length; result.set(sizeBytes, offset); offset += sizeBytes.length; result.set(versionBytes, offset); offset += versionBytes.length; result.set(leftHashBytes, offset); offset += leftHashBytes.length; result.set(rightHashBytes, offset); return result; } } /** * Serializes this node to bytes. * The format depends on whether this is a leaf or branch node. * * Leaf format: * height (varint) || size (varint) || key (length-prefixed) || value (length-prefixed) * * Branch format: * height (varint) || size (varint) || key (length-prefixed) || hash (33 bytes) || * mode (varint) || leftNodeKey || rightNodeKey * * @returns Serialized bytes */ toBytes(): Uint8Array { // Calculate required buffer size const parts: Uint8Array[] = []; // Encode height parts.push(encodeVarint(this.subtreeHeight)); // Encode size parts.push(encodeVarint(this.size)); // Encode key if (!this.key) { throw new Error("Node must have key for serialization"); } parts.push(encodeBytes(this.key)); if (this.isLeaf()) { // Leaf node: encode value if (!this.value) { throw new Error("Leaf node must have value for serialization"); } parts.push(encodeBytes(this.value)); } else { // Branch node: encode hash and child keys if (!this.hash) { throw new Error("Branch node must have hash for serialization"); } parts.push(encode32BytesHash(this.hash)); // Determine mode based on child key formats if (!this.leftNodeKey) { throw new Error("Branch node must have leftNodeKey for serialization"); } if (!this.rightNodeKey) { throw new Error("Branch node must have rightNodeKey for serialization"); } let mode = 0; if (this.leftNodeKey.length === HASH_SIZE) { mode |= MODE_LEGACY_LEFT_NODE; } if (this.rightNodeKey.length === HASH_SIZE) { mode |= MODE_LEGACY_RIGHT_NODE; } parts.push(encodeVarint(mode)); // Encode left child key if (mode & MODE_LEGACY_LEFT_NODE) { // Legacy: 32-byte hash parts.push(encode32BytesHash(this.leftNodeKey)); } else { // V1: version + nonce varints const leftNodeKey = NodeKeyClass.fromBytes(this.leftNodeKey); parts.push(encodeVarint(leftNodeKey.version)); parts.push(encodeVarint(leftNodeKey.nonce)); } // Encode right child key if (mode & MODE_LEGACY_RIGHT_NODE) { // Legacy: 32-byte hash parts.push(encode32BytesHash(this.rightNodeKey)); } else { // V1: version + nonce varints const rightNodeKey = NodeKeyClass.fromBytes(this.rightNodeKey); parts.push(encodeVarint(rightNodeKey.version)); parts.push(encodeVarint(rightNodeKey.nonce)); } } // Concatenate all parts const totalLength = parts.reduce((sum, part) => sum + part.length, 0); const result = new Uint8Array(totalLength); let offset = 0; for (const part of parts) { result.set(part, offset); offset += part.length; } return result; } /** * Deserializes a node from bytes. * The nodeKey parameter identifies this node in the database. * * @param nodeKey - The NodeKey bytes (12 bytes for v1, 32 bytes for legacy) * @param bytes - Serialized node bytes * @returns Deserialized node */ static fromBytes(nodeKey: Uint8Array, bytes: Uint8Array): Node { let offset = 0; // Decode height const heightResult = decodeVarint(bytes, offset); const height = heightResult.value; if (height < -128 || height > 127) { throw new Error(`Invalid height: ${height} (must fit in int8)`); } offset += heightResult.bytesRead; // Decode size const sizeResult = decodeVarintBigInt(bytes, offset); const size = sizeResult.value; offset += sizeResult.bytesRead; // Decode key const keyResult = decodeBytes(bytes, offset); const key = keyResult.bytes; offset += keyResult.bytesRead; // Determine if this is a legacy node const isLegacy = nodeKey.length === HASH_SIZE; // Create node with basic fields const node = new Node(); node.subtreeHeight = height; node.size = size; node.key = key; node.isLegacy = isLegacy; if (isLegacy) { node.hash = nodeKey; } else { node.nodeKey = NodeKeyClass.fromBytes(nodeKey); } // Decode node body if (height === 0) { // Leaf node: decode value const valueResult = decodeBytes(bytes, offset); node.value = valueResult.bytes; offset += valueResult.bytesRead; // Compute hash for leaf nodes if (!isLegacy && node.nodeKey) { node.computeHash(node.nodeKey.version); } } else { // Branch node: decode hash and children const hashResult = decodeBytes(bytes, offset); node.hash = hashResult.bytes; offset += hashResult.bytesRead; // Decode mode const modeResult = decodeVarint(bytes, offset); const mode = modeResult.value; // Validate mode before using it if (mode < 0 || mode > 3) { throw new Error(`Invalid mode: ${mode}`); } offset += modeResult.bytesRead; // Decode left child key if (mode & MODE_LEGACY_LEFT_NODE) { // Legacy: 32-byte hash const leftHashResult = decodeBytes(bytes, offset); node.leftNodeKey = leftHashResult.bytes; offset += leftHashResult.bytesRead; } else { // V1: version + nonce varints const leftVersionResult = decodeVarintBigInt(bytes, offset); offset += leftVersionResult.bytesRead; const leftNonceResult = decodeVarint(bytes, offset); const leftNonce = leftNonceResult.value; if (leftNonce < 0 || leftNonce > 0xFFFFFFFF) { throw new Error(`Invalid left nonce: ${leftNonce}`); } offset += leftNonceResult.bytesRead; const leftNodeKey = new NodeKeyClass(leftVersionResult.value, leftNonce); node.leftNodeKey = leftNodeKey.toBytes(); } // Decode right child key if (mode & MODE_LEGACY_RIGHT_NODE) { // Legacy: 32-byte hash const rightHashResult = decodeBytes(bytes, offset); node.rightNodeKey = rightHashResult.bytes; offset += rightHashResult.bytesRead; } else { // V1: version + nonce varints const rightVersionResult = decodeVarintBigInt(bytes, offset); offset += rightVersionResult.bytesRead; const rightNonceResult = decodeVarint(bytes, offset); const rightNonce = rightNonceResult.value; if (rightNonce < 0 || rightNonce > 0xFFFFFFFF) { throw new Error(`Invalid right nonce: ${rightNonce}`); } offset += rightNonceResult.bytesRead; const rightNodeKey = new NodeKeyClass(rightVersionResult.value, rightNonce); node.rightNodeKey = rightNodeKey.toBytes(); } } return node; } /** * Gets the left child node, loading it from storage if needed. * @param getter - NodeGetter for loading nodes from storage * @returns The left child node, or null if not found */ async getLeftNode(getter: NodeGetter): Promise { // Return cached node if available if (this.leftNode !== null) { return this.leftNode; } // Load from storage if we have a key if (this.leftNodeKey !== null) { return await getter.getNode(this.leftNodeKey); } return null; } /** * Gets the right child node, loading it from storage if needed. * @param getter - NodeGetter for loading nodes from storage * @returns The right child node, or null if not found */ async getRightNode(getter: NodeGetter): Promise { // Return cached node if available if (this.rightNode !== null) { return this.rightNode; } // Load from storage if we have a key if (this.rightNodeKey !== null) { return await getter.getNode(this.rightNodeKey); } return null; } /** * Creates a clone of this node for copy-on-write operations. * Leaf nodes cannot be cloned (throw error). * Branch nodes are cloned with children loaded from storage if needed. * * IMPORTANT: In JavaScript, we must be careful with reference semantics: * - Primitive fields (subtreeHeight, size) are copied by value * - Object references (key, leftNodeKey, rightNodeKey, leftNode, rightNode) are copied by reference * - The clone shares references to child nodes (copy-on-write semantics) * - hash and nodeKey are set to null (will be recomputed/assigned) * * @param getter - NodeGetter for loading child nodes from storage * @returns A new cloned Node instance * @throws Error if called on a leaf node */ async clone(getter: NodeGetter): Promise { // Leaf nodes cannot be cloned if (this.isLeaf()) { throw new Error("Cannot clone leaf node"); } // Ensure children are loaded from storage if needed // NOTE: In Go, this clears the cached children in the original node // In TypeScript, we just load them but don't clear (no side effects on original) let leftNode = this.leftNode; let rightNode = this.rightNode; if (this.nodeKey !== null) { // Node has been persisted, need to load children leftNode = await this.getLeftNode(getter); rightNode = await this.getRightNode(getter); } // Create new node with same structure but cleared hash/nodeKey // NOTE: This shares references to child nodes (copy-on-write) const cloned = new Node(); // Copy fields cloned.key = this.key; // Reference to same Uint8Array (shared) cloned.value = null; // Branch nodes have no value cloned.subtreeHeight = this.subtreeHeight; cloned.size = this.size; cloned.leftNodeKey = this.leftNodeKey; // Reference to same Uint8Array (shared) cloned.rightNodeKey = this.rightNodeKey; // Reference to same Uint8Array (shared) cloned.leftNode = leftNode; // Reference to same Node (shared) cloned.rightNode = rightNode; // Reference to same Node (shared) // Clear hash and nodeKey - these will be recomputed/assigned cloned.hash = null; cloned.nodeKey = null; return cloned; } /** * Searches for a key in the subtree rooted at this node. * Returns the index and value if found. * * @param getter - NodeGetter for loading nodes from storage * @param key - The key to search for * @returns Object with index (position in tree), value (if found), and error */ async get(getter: NodeGetter, key: Uint8Array): Promise<{ index: bigint value: Uint8Array | null }> { if (this.isLeaf()) { if (!this.key) { throw new Error("Leaf node must have key"); } // Compare keys const cmp = compareBytes(key, this.key); if (cmp < 0) { // Key is less than this node's key return { index: 0n, value: null, }; } else if (cmp > 0) { // Key is greater than this node's key return { index: 1n, value: null, }; } else { // Found the key return { index: 0n, value: this.value, }; } } // Branch node: recursively search children if (!this.key) { throw new Error("Branch node must have key"); } // Go implementation (node.go lines 375-395): // If key < node.key: search left subtree, return immediately // Otherwise: search right subtree, adjust index if (compareBytes(key, this.key) < 0) { // Key is in left subtree const leftNode = await this.getLeftNode(getter); if (!leftNode) { throw new Error("Failed to load left child node"); } return await leftNode.get(getter, key); } // Key is in right subtree (>= node.key) const rightNode = await this.getRightNode(getter); if (!rightNode) { throw new Error("Failed to load right child node"); } const result = await rightNode.get(getter, key); // Adjust index to account for left subtree result.index += this.size - rightNode.size; return result; } /** * Gets the key-value pair at the specified index (0-based). * Index represents the position in an in-order traversal. * * @param getter - NodeGetter for loading nodes from storage * @param index - The index to retrieve (0-based) * @returns Object with key and value, or null if index out of bounds */ async getByIndex(getter: NodeGetter, index: bigint): Promise<{ key: Uint8Array | null value: Uint8Array | null }> { if (this.isLeaf()) { if (index === 0n) { return { key: this.key, value: this.value, }; } return { key: null, value: null, }; } // Branch node: find which subtree contains the index const leftNode = await this.getLeftNode(getter); if (!leftNode) { throw new Error("Failed to load left child node"); } if (index < leftNode.size) { // Index is in left subtree return await leftNode.getByIndex(getter, index); } // Index is in right subtree const rightNode = await this.getRightNode(getter); if (!rightNode) { throw new Error("Failed to load right child node"); } return await rightNode.getByIndex(getter, index - leftNode.size); } /** * Traverses the subtree in order, calling the callback for each node. * Traversal continues until the callback returns true (stop) or all nodes visited. * * @param getter - NodeGetter for loading nodes from storage * @param ascending - If true, traverse in ascending order; otherwise descending * @param callback - Function called for each node; return true to stop * @returns True if traversal was stopped by callback, false if completed */ async traverse( getter: NodeGetter, ascending: boolean, callback: (node: Node) => boolean, ): Promise { return await this.traverseInRange( getter, null, null, ascending, false, false, // pre-order (normal in-order traversal) callback, ); } /** * Traverses the entire tree in post-order (LRN: left, right, node). * Post-order traversal visits children before parents, which is required for export. * Based on Go IAVL node.go lines 725-729. * * @param getter - NodeGetter for loading child nodes * @param ascending - If true, traverse in ascending order; otherwise descending * @param callback - Function called for each node; return true to stop * @returns True if traversal was stopped by callback, false if completed */ async traversePost( getter: NodeGetter, ascending: boolean, callback: (node: Node) => boolean, ): Promise { return await this.traverseInRange( getter, null, null, ascending, false, true, // post-order traversal callback, ); } /** * Traverses nodes within a key range, calling the callback for each node. * Supports both ascending and descending order. * * @param getter - NodeGetter for loading nodes from storage * @param start - Start key (inclusive if inclusive=true), or null for no lower bound * @param end - End key (inclusive if inclusive=true), or null for no upper bound * @param ascending - If true, traverse in ascending order; otherwise descending * @param inclusive - If true, include start and end keys; otherwise exclusive * @param callback - Function called for each node; return true to stop * @returns True if traversal was stopped by callback, false if completed */ async traverseInRange( getter: NodeGetter, start: Uint8Array | null, end: Uint8Array | null, ascending: boolean, inclusive: boolean, post: boolean, callback: (node: Node) => boolean, ): Promise { if (this.isLeaf()) { if (!this.key) { throw new Error("Leaf node must have key"); } // Check if this leaf is in range if (start !== null) { const cmp = compareBytes(this.key, start); if (cmp < 0 || (!inclusive && cmp === 0)) { return false; // Key is before range } } if (end !== null) { const cmp = compareBytes(this.key, end); if (cmp > 0 || (!inclusive && cmp === 0)) { return false; // Key is after range } } // Key is in range, call callback return callback(this); } // Branch node: recursively traverse children if (!this.key) { throw new Error("Branch node must have key"); } if (ascending) { // Ascending: left, then right // Always traverse left subtree (it may contain nodes in range) const leftNode = await this.getLeftNode(getter); if (leftNode) { const stop = await leftNode.traverseInRange( getter, start, end, ascending, inclusive, post, callback, ); if (stop) return true; } // Always traverse right subtree (it may contain nodes in range) const rightNode = await this.getRightNode(getter); if (rightNode) { const stop = await rightNode.traverseInRange( getter, start, end, ascending, inclusive, post, callback, ); if (stop) return true; } // Post-order: visit node after children (for export) // Pre-order: node is visited implicitly by callback in leaves only if (post) { // In post-order, also visit branch nodes after their children return callback(this); } } else { // Descending: right, then left // Always traverse right subtree (it may contain nodes in range) const rightNode = await this.getRightNode(getter); if (rightNode) { const stop = await rightNode.traverseInRange( getter, start, end, ascending, inclusive, post, callback, ); if (stop) return true; } // Always traverse left subtree (it may contain nodes in range) const leftNode = await this.getLeftNode(getter); if (leftNode) { const stop = await leftNode.traverseInRange( getter, start, end, ascending, inclusive, post, callback, ); if (stop) return true; } // Post-order: visit node after children if (post) { return callback(this); } } return false; } /** * PathToLeaf generates a proof path from this node to the leaf containing the given key. * * If the key does not exist, returns the path to the next leaf left of the key, * except when the key is less than the least item, in which case it returns * a path to the least item. * * The path is ordered ROOT to LEAF, where path[0] is the topmost node and * path[path.length-1] is the leaf's parent. * * Based on Go IAVL v1.3.5 proof.go PathToLeaf (lines 169-173) * * @param getter - NodeGetter for loading nodes from storage * @param key - The key to search for * @returns Object containing the path and the leaf node found * @throws Error if there's an issue loading nodes from storage */ async pathToLeaf( getter: NodeGetter, key: Uint8Array, ): Promise<{ path: ProofInnerNode[] node: Node }> { const path: ProofInnerNode[] = []; const node = await this._pathToLeaf(getter, key, path); return { path, node, }; } /** * _pathToLeaf is a helper which recursively constructs the PathToLeaf. * As an optimization, the already constructed path is passed in as an argument * and is shared among recursive calls. * * Based on Go IAVL v1.3.5 proof.go pathToLeaf (lines 178-239) * * @param getter - NodeGetter for loading nodes from storage * @param key - The key to search for * @param path - The path being constructed (mutated in place) * @returns The leaf node found * @throws Error if there's an issue loading nodes from storage */ private async _pathToLeaf( getter: NodeGetter, key: Uint8Array, path: ProofInnerNode[], ): Promise { // Base case: we've reached a leaf if (this.subtreeHeight === 0) { // Note: In Go, this returns an error if key doesn't match. // In TypeScript, we just return the leaf (closest match). // The caller can check if the key matches if needed. return this; } // Get the version for this node // Use nodeKey.version if available, otherwise use a default const nodeVersion = this.nodeKey?.version ?? 0n; // Determine which direction to traverse const cmp = compareBytes(key, this.key!); if (cmp < 0) { // Go left // Load right sibling to include its hash in the proof const rightNode = await this.getRightNode(getter); if (!rightNode) { throw new Error("Right child node not found"); } // Create ProofInnerNode for this level // Note: left is null because we're traversing left (optimization) const pin = new ProofInnerNode( this.subtreeHeight, this.size, nodeVersion, null, // left (we're going left, so don't store) rightNode.hash!, // right sibling hash ); path.push(pin); // Recurse into left child const leftNode = await this.getLeftNode(getter); if (!leftNode) { throw new Error("Left child node not found"); } return await leftNode._pathToLeaf(getter, key, path); } else { // Go right (includes the case where cmp === 0, i.e., key === node.key) // Load left sibling to include its hash in the proof const leftNode = await this.getLeftNode(getter); if (!leftNode) { throw new Error("Left child node not found"); } // Create ProofInnerNode for this level // Note: right is null because we're traversing right (optimization) const pin = new ProofInnerNode( this.subtreeHeight, this.size, nodeVersion, leftNode.hash!, // left sibling hash null, // right (we're going right, so don't store) ); path.push(pin); // Recurse into right child const rightNode = await this.getRightNode(getter); if (!rightNode) { throw new Error("Right child node not found"); } return await rightNode._pathToLeaf(getter, key, path); } } } /** * Compares two byte arrays lexicographically. * @param a - First byte array * @param b - Second byte array * @returns -1 if a < b, 0 if a === b, 1 if a > b */ function compareBytes(a: Uint8Array, b: Uint8Array): number { const minLen = Math.min(a.length, b.length); for (let i = 0; i < minLen; i++) { if (a[i] < b[i]) return -1; if (a[i] > b[i]) return 1; } if (a.length < b.length) return -1; if (a.length > b.length) return 1; return 0; } /** * Encodes a byte array with a varint length prefix. * Compatible with Go's encoding.EncodeBytes. * * Note: Uses UNSIGNED varint for length (EncodeUvarint in Go) * * @param bytes - The byte array to encode * @returns Unsigned varint length + bytes */ function encodeBytes(bytes: Uint8Array): Uint8Array { const lengthBytes = encodeUvarint(bytes.length); const result = new Uint8Array(lengthBytes.length + bytes.length); result.set(lengthBytes, 0); result.set(bytes, lengthBytes.length); return result; } /** * Encodes a 32-byte hash with an optimized prefix. * Compatible with Go's encoding.Encode32BytesHash. * Uses 0x20 as the length prefix for 32-byte hashes. * * @param hashBytes - The 32-byte hash to encode * @returns 0x20 + hash (33 bytes total) */ function encode32BytesHash(hashBytes: Uint8Array): Uint8Array { if (hashBytes.length !== 32) { throw new Error(`Hash must be 32 bytes, got ${hashBytes.length}`); } const result = new Uint8Array(33); result[0] = 0x20; // Length prefix for 32 bytes result.set(hashBytes, 1); return result; }