/** * ImmutableTree contains the immutable tree at a given version. * It is typically created by calling MutableTree.getImmutable(), in which case * the returned tree is safe for concurrent access as long as the version is * not deleted via deleteVersion() or the tree's pruning settings. * * Returned key/value byte slices must not be modified, since they may point * to data located inside IAVL which would also be modified. */ import type { Logger, } from "winston"; import { Exporter, } from "./export/index.js"; import type { ExportNode, } from "./export/types.js"; import type { CommitmentProof, ExistenceProof, NonExistenceProof, } from "./generated/cosmos/ics23/v1/proofs.js"; import { TreeIterator, } from "./iterator/iterator.js"; import type { Node, } from "./node.js"; import type { NodeGetter, } from "./node.js"; import { convertInnerOps, convertLeafOp, IavlSpec, verifyMembership, verifyNonMembership, } from "./proof/types.js"; import type { ChangeSet, } from "./types/index.js"; /** * ImmutableTree represents a read-only snapshot of the tree at a specific version. */ export class ImmutableTree { /** Root node of the tree */ readonly root: Node | null; /** NodeDB instance for loading nodes (forward reference using NodeGetter interface) */ readonly ndb: NodeGetter; /** Version of this tree snapshot */ readonly version: bigint; /** Whether to skip fast storage upgrade (use traditional IAVL node storage only) */ readonly skipFastStorageUpgrade: boolean; /** Logger instance for diagnostics */ readonly logger: Logger | null; /** * Creates a new ImmutableTree instance. * * @param root - Root node of the tree (null for empty tree) * @param ndb - NodeDB instance for loading nodes * @param version - Version number of this tree snapshot * @param skipFastStorageUpgrade - Whether to skip fast storage (default: false) * @param logger - Optional logger instance */ constructor( root: Node | null, ndb: NodeGetter, version: bigint, skipFastStorageUpgrade = false, logger: Logger | null = null, ) { this.root = root; this.ndb = ndb; this.version = version; this.skipFastStorageUpgrade = skipFastStorageUpgrade; this.logger = logger; // Make the tree truly immutable by freezing it Object.freeze(this); } /** * Returns the version of the tree. * * @returns Version number */ getVersion(): bigint { return this.version; } /** * Returns the root node of the tree. * * @returns Root node or null if tree is empty */ getRoot(): Node | null { return this.root; } /** * Returns whether the tree is empty. * * @returns true if tree has no nodes */ isEmpty(): boolean { return this.root === null; } /** * Returns the number of leaf nodes in the tree. * * @returns Total number of key-value pairs */ size(): bigint { if (this.root === null) { return 0n; } return this.root.size; } /** * Returns the height of the tree. * Height is defined as the number of edges in the longest path from root to leaf. * An empty tree has height 0, a single node has height 0, two levels have height 1. * * @returns Tree height */ height(): number { if (this.root === null) { return 0; } return this.root.subtreeHeight; } /** * Returns the root hash of the tree. * Computes the hash if it hasn't been computed yet. * Returns null for empty trees. * * @returns Root hash or null for empty tree */ hash(): Uint8Array | null { if (this.root === null) { return null; } // Compute hash if not already computed return this.root.computeHash(this.version); } /** * Returns whether a key exists in the tree. * * @param key - The key to check * @returns true if key exists, false otherwise */ async has(key: Uint8Array): Promise { if (this.root === null) { return false; } const result = await this.root.get(this.ndb, key); return result.value !== null; } /** * Creates a shallow clone of this ImmutableTree. * The clone shares the same root node and NodeDB reference. * Used for creating snapshots (e.g., lastSaved in MutableTree). * * @returns A new ImmutableTree instance with same root/version/ndb */ clone(): ImmutableTree { return new ImmutableTree( this.root, this.ndb, this.version, this.skipFastStorageUpgrade, this.logger, ); } /** * Returns the value for a given key. * The returned value must not be modified, since it may point to data stored within IAVL. * * Employs fast storage optimization when available for better performance. * This matches Go IAVL's Get() implementation (immutable_tree.go:180-216). * * @param key - The key to look up * @returns The value, or null if key doesn't exist */ async get(key: Uint8Array): Promise { if (this.root === null) { return null; } // Fast storage optimization: attempt to get FastNode directly from db/cache // If this fails, fall back to tree traversal // Note: ndb is typed as NodeGetter interface, but NodeDB implements additional methods if (!this.skipFastStorageUpgrade && "getFastNode" in this.ndb && "getLatestVersion" in this.ndb) { try { // Type assertion: we've verified the methods exist const ndb = this.ndb as { getFastNode: (key: Uint8Array) => Promise<{ value: Uint8Array versionLastUpdatedAt: bigint } | null> getLatestVersion: () => bigint }; const fastNode = await ndb.getFastNode(key); // If fast node doesn't exist if (fastNode === null) { // For the latest version, fast node absence means the key doesn't exist // because fast nodes represent the live state if (this.version === ndb.getLatestVersion()) { return null; } // For historical versions, fall back to tree traversal const result = await this.root.get(this.ndb, key); return result.value; } // If fast node exists and was updated at or before this tree version, // it's valid for this version if (fastNode.versionLastUpdatedAt <= this.version) { return fastNode.value; } // Fast node was updated after this tree version, fall through to tree traversal } catch (_err) { // If fast node retrieval fails, fall back to tree traversal const result = await this.root.get(this.ndb, key); return result.value; } } // Either skipFastStorageUpgrade is true, or the fast node was updated later // than this tree version. Use tree traversal to avoid staleness. const result = await this.root.get(this.ndb, key); return result.value; } /** * Returns the index and value of the specified key if it exists, or the next index otherwise. * The returned value must not be modified, since it may point to data stored within IAVL. * * The index is the index in the list of leaf nodes sorted lexicographically by key. * The leftmost leaf has index 0, its neighbor has index 1, and so on. * * @param key - The key to look up * @returns Object with index and value (value is null if key doesn't exist) */ async getWithIndex(key: Uint8Array): Promise<{ index: bigint value: Uint8Array | null }> { if (this.root === null) { return { index: 0n, value: null, }; } return await this.root.get(this.ndb, key); } /** * Gets the key and value at the specified index. * Index represents position in the sorted list of keys (0-based). * * @param index - The index to look up (0 = leftmost leaf) * @returns Object with key and value, or null if index is out of bounds */ async getByIndex(index: bigint): Promise<{ key: Uint8Array value: Uint8Array } | null> { if (this.root === null) { return null; } const result = await this.root.getByIndex(this.ndb, index); if (result.key === null || result.value === null) { return null; } return { key: result.key, value: result.value, }; } /** * Creates an iterator over the tree in ascending order. * * @param start - Start key (null to start from beginning) * @param end - End key (null for no limit) * @returns TreeIterator instance */ iterator( start: Uint8Array | null = null, end: Uint8Array | null = null, ): TreeIterator { return new TreeIterator(this, start, end, true, false); } /** * Creates an iterator over the tree in descending order. * * @param start - Start key (null to start from end) * @param end - End key (null for no limit) * @returns TreeIterator instance */ reverseIterator( start: Uint8Array | null = null, end: Uint8Array | null = null, ): TreeIterator { return new TreeIterator(this, start, end, false, false); } /** * Iterates over all keys in the tree, calling a function for each key-value pair. * * Corresponds to Go's ImmutableTree.Iterate() * * @param fn - Function to call for each key-value pair. Return true to stop iteration. * @returns True if iteration was stopped early, false if completed */ async iterate( fn: (key: Uint8Array, value: Uint8Array) => boolean, ): Promise { if (this.root === null) { return false; } const iter = new TreeIterator(this, null, null, true, false); try { // Position iterator at first element await iter.next(); while (iter.valid()) { const stop = fn(iter.key(), iter.value()); if (stop) { return true; } await iter.next(); } return false; } finally { iter.close(); } } /** * Iterates over a range of keys, calling a function for each key-value pair. * End key is exclusive (non-inclusive). * * Corresponds to Go's ImmutableTree.IterateRange() * * @param start - Start key (null to start from beginning) * @param end - End key (exclusive, null for no limit) * @param ascending - True for ascending order, false for descending * @param fn - Function to call for each key-value pair. Return true to stop iteration. * @returns True if iteration was stopped early, false if completed */ async iterateRange( start: Uint8Array | null, end: Uint8Array | null, ascending: boolean, fn: (key: Uint8Array, value: Uint8Array) => boolean, ): Promise { if (this.root === null) { return false; } const iter = new TreeIterator(this, start, end, ascending, false); try { // Position iterator at first element await iter.next(); while (iter.valid()) { const stop = fn(iter.key(), iter.value()); if (stop) { return true; } await iter.next(); } return false; } finally { iter.close(); } } /** * Iterates over a range of keys, calling a function for each key-value-version triple. * End key is inclusive. * * Corresponds to Go's ImmutableTree.IterateRangeInclusive() * * @param start - Start key (null to start from beginning) * @param end - End key (inclusive, null for no limit) * @param ascending - True for ascending order, false for descending * @param fn - Function to call for each key-value-version triple. Return true to stop iteration. * @returns True if iteration was stopped early, false if completed */ async iterateRangeInclusive( start: Uint8Array | null, end: Uint8Array | null, ascending: boolean, fn: (key: Uint8Array, value: Uint8Array, version: bigint) => boolean, ): Promise { if (this.root === null) { return false; } const iter = new TreeIterator(this, start, end, ascending, true); try { // Position iterator at first element await iter.next(); while (iter.valid()) { const stop = fn(iter.key(), iter.value(), iter.version()); if (stop) { return true; } await iter.next(); } return false; } finally { iter.close(); } } /** * Get Membership Proof generates an ICS23 existence proof for a key. * * Returns a CommitmentProof that the given key (and its value) exists in the IAVL tree. * If the key doesn't exist in the tree, this will return an error. * * The proof can be verified by a light client using the ICS23 verification library * with the tree's root hash. * * Based on Go IAVL v1.3.5 proof_ics23.go GetMembershipProof (lines 14-25) * * @param key - The key to generate a proof for * @returns CommitmentProof containing an ExistenceProof * @throws Error if key doesn't exist in the tree */ async getMembershipProof( key: Uint8Array, ): Promise { const exist = await this.createExistenceProof(key); return { exist, nonexist: undefined, batch: undefined, compressed: undefined, }; } /** * Get Non-Membership Proof generates an ICS23 non-existence proof for a key. * * Returns a CommitmentProof that the given key doesn't exist in the IAVL tree. * If the key exists in the tree, this will return an error. * * The proof includes existence proofs for the keys immediately to the left * and right of where the queried key would be if it existed. If the keys * are adjacent and neither equals the queried key, then the queried key * cannot exist. * * Based on Go IAVL v1.3.5 proof_ics23.go GetNonMembershipProof (lines 42-89) * * @param key - The key to generate a non-existence proof for * @returns CommitmentProof containing a NonExistenceProof * @throws Error if key exists in the tree */ async getNonMembershipProof( key: Uint8Array, ): Promise { // GetWithIndex returns the index where key would be (or is) // If key doesn't exist, idx points to the next key to the right const { index: idx, value: val, } = await this.getWithIndex(key); if (val !== null) { throw new Error("cannot create NonExistenceProof when key exists in tree"); } const nonexist: NonExistenceProof = { key, left: undefined, right: undefined, }; // Get left neighbor (key at idx-1) if (idx >= 1n) { const leftResult = await this.getByIndex(idx - 1n); if (leftResult) { nonexist.left = await this.createExistenceProof(leftResult.key); } } // Get right neighbor (key at idx) // idx points to the next key to the right of where our key would be const rightResult = await this.getByIndex(idx); if (rightResult) { nonexist.right = await this.createExistenceProof(rightResult.key); } return { exist: undefined, nonexist, batch: undefined, compressed: undefined, }; } /** * Create Existence Proof generates an ICS23 ExistenceProof for a key. * * This is an internal helper method that: * 1. Calls root.pathToLeaf() to get the proof path * 2. Converts the path to ICS23 format using convertLeafOp/convertInnerOps * 3. Returns an ExistenceProof with the key, value, leaf op, and inner ops * * The returned proof can be used to verify that a key-value pair exists * in the tree by hashing up from the leaf to the root. * * Based on Go IAVL v1.3.5 proof_ics23.go createExistenceProof (lines 100-113) * * @param key - The key to generate a proof for * @returns ExistenceProof for the key * @throws Error if key doesn't exist (returns proof for adjacent key) */ private async createExistenceProof( key: Uint8Array, ): Promise { // Ensure tree is hashed this.hash(); if (!this.root) { throw new Error("cannot create proof for empty tree"); } // Get path from root to leaf const { path, node, } = await this.root.pathToLeaf(this.ndb, key); // Determine the version to use for the leaf // Use node's version if available, otherwise use tree version + 1 const nodeVersion = node.nodeKey?.version ?? (this.version + 1n); // Convert to ICS23 format return { key: node.key!, value: node.value!, leaf: convertLeafOp(nodeVersion), path: convertInnerOps(path), }; } /** * Verify Membership verifies an ICS23 membership proof for a key-value pair. * * Returns true if the proof is valid and proves that the key-value pair exists * in the tree at the committed root hash. * * Based on Go IAVL v1.3.5 proof_ics23.go VerifyMembership (lines 28-36) * * @param proof - The commitment proof to verify * @param key - The key being proven * @returns true if proof is valid, false otherwise */ async verifyMembership( proof: CommitmentProof, key: Uint8Array, ): Promise { // Get value for key const value = await this.get(key); if (value === null) { return false; } // Get root hash const root = this.hash(); if (root === null) { return false; } // Verify using ics23 return verifyMembership(IavlSpec, root, proof, key, value); } /** * Verify Non-Membership verifies an ICS23 non-membership proof for a key. * * Returns true if the proof is valid and proves that the key does not exist * in the tree at the committed root hash. * * Based on Go IAVL v1.3.5 proof_ics23.go VerifyNonMembership (lines 92-96) * * @param proof - The commitment proof to verify * @param key - The key being proven absent * @returns true if proof is valid, false otherwise */ verifyNonMembership( proof: CommitmentProof, key: Uint8Array, ): boolean { // Get root hash const root = this.hash(); if (root === null) { return false; } // Verify using ics23 return verifyNonMembership(IavlSpec, root, proof, key); } /** * Get Proof gets the proof for the given key. * Returns a membership proof if the key exists, or a non-membership proof if it doesn't. * * Based on Go IAVL v1.3.5 proof_ics23.go GetProof (lines 178-192) * * @param key - The key to generate a proof for * @returns CommitmentProof (either membership or non-membership) * @throws Error if root is null */ async getProof(key: Uint8Array): Promise { if (this.root === null) { throw new Error("cannot generate the proof with nil root"); } const exists = await this.has(key); if (exists) { return this.getMembershipProof(key); } return this.getNonMembershipProof(key); } /** * Verify Proof checks if the proof is correct for the given key. * Automatically determines if it's a membership or non-membership proof and verifies accordingly. * * Based on Go IAVL v1.3.5 proof_ics23.go VerifyProof (lines 195-200) * * @param proof - The proof to verify * @param key - The key the proof is for * @returns True if proof is valid, false otherwise */ async verifyProof( proof: CommitmentProof, key: Uint8Array, ): Promise { if (proof.exist !== undefined) { return this.verifyMembership(proof, key); } return this.verifyNonMembership(proof, key); } /** * Export creates an Exporter for this tree. * Exported nodes can be imported into an empty tree with MutableTree.import(). * Nodes are exported depth-first post-order (LRN), this order must be preserved * when importing in order to recreate the same tree structure. * * Based on Go IAVL immutable_tree.go lines 159-161. * * @returns An Exporter that yields nodes in post-order * @throws Error if tree is nil or has no root * * @example * ```typescript * const exporter = tree.export(); * for await (const node of exporter) { * console.log(`Key: ${node.key}, Version: ${node.version}`); * } * ``` */ export(): Exporter { return new Exporter(this); } /** * Create a compressed exporter for this tree. The compressed exporter * applies delta encoding to reduce export size: * - Branch keys are skipped (can be derived during import) * - Leaf keys are delta-encoded compared to previous leaf * - Branch node versions are delta-encoded compared to max version in children * * @returns An async iterable that yields compressed export nodes * * @example * ```typescript * const exporter = tree.exportCompressed(); * for await (const node of exporter) { * // Process compressed node * } * ``` */ async* exportCompressed(): AsyncIterable { const { createCompressExporter, } = await import("./export/compress.js"); const exporter = this.export(); const compressed = createCompressExporter(exporter); for await (const node of compressed) { yield node; } } /** * Traverses state changes between a range of versions. * For each version in the range, extracts the changes from the previous version * and calls the callback function with the version number and the ChangeSet. * * This is useful for extracting a stream of changes across multiple versions, * for example to build a changelog or to replicate state changes. * * Based on Go IAVL v1.3.5 immutable_tree.go TraverseStateChanges * * @param startVersion - First version to extract changes for * @param endVersion - Last version to extract changes for * @param fn - Callback function to receive changes for each version * @returns Promise that resolves when traversal is complete * * @example * ```typescript * await tree.traverseStateChanges(1n, 10n, async (version, changeSet) => { * console.log(`Version ${version}: ${changeSet.pairs.length} changes`); * // Return true to stop iteration * return false; * }); * ``` */ async traverseStateChanges( startVersion: bigint, endVersion: bigint, fn: (version: bigint, changeSet: ChangeSet) => Promise, ): Promise { // Import NodeDB for type checking const { NodeDB, } = await import("./storage/node-db.js"); if (!(this.ndb instanceof NodeDB)) { throw new Error("NodeGetter must be NodeDB to use traverseStateChanges"); } return this.ndb.traverseStateChanges(startVersion, endVersion, fn); } /** * Returns a string representation of all leaves in the tree for debugging. * Format: "Tree{key1: value1, key2: value2, ...}" * * Corresponds to Go's ImmutableTree.String() * * Note: In TypeScript, this must be async because tree traversal requires * database access. This differs from Go where String() is synchronous. * * @returns Promise of string representation showing all key-value pairs */ async toString(): Promise { if (this.root === null) { return "Tree{}"; } const leaves: string[] = []; await this.iterate((key: Uint8Array, value: Uint8Array) => { const keyHex = Buffer.from(key).toString("hex"); const valueHex = Buffer.from(value).toString("hex"); leaves.push(`${keyHex}: ${valueHex}`); return false; // continue iteration }); return `Tree{${leaves.join(", ")}}`; } /** * Returns a visual representation of the tree structure for debugging. * Each line represents a node, with indentation showing depth. * * Corresponds to Go's ImmutableTree.RenderShape() * * @param indent - String to use for each level of indentation (default: " ") * @param encoder - Optional custom encoder function for node IDs * @returns Array of strings representing the tree structure */ async renderShape( indent = " ", encoder?: (id: Uint8Array, depth: number, isLeaf: boolean) => string, ): Promise { const defaultEncoder = (id: Uint8Array, _depth: number, isLeaf: boolean): string => { const prefix = isLeaf ? "* " : "- "; if (id.length === 0) { return `${prefix}`; } return `${prefix}${Buffer.from(id).toString("hex").toUpperCase()}`; }; const nodeEncoder = encoder ?? defaultEncoder; return await this.renderNode(this.root, indent, 0, nodeEncoder); } /** * Recursively renders a node and its children. * Helper for renderShape(). * * @param node - Node to render * @param indent - Indentation string * @param depth - Current depth in tree * @param encoder - Function to encode node IDs * @returns Array of strings for this node and its subtree */ private async renderNode( node: Node | null, indent: string, depth: number, encoder: (id: Uint8Array, depth: number, isLeaf: boolean) => string, ): Promise { const prefix = indent.repeat(depth); // Handle nil node if (node === null) { return [`${prefix}`]; } // Handle leaf node if (node.isLeaf()) { const here = `${prefix}${encoder(node.key!, depth, true)}`; return [here]; } // Handle inner node const nodeHash = node.hash ?? new Uint8Array(0); const here = `${prefix}${encoder(nodeHash, depth, false)}`; // Get child nodes const rightNode = node.rightNodeKey ? await this.ndb.getNode(node.rightNodeKey) : null; const leftNode = node.leftNodeKey ? await this.ndb.getNode(node.leftNodeKey) : null; // Recursively render children const right = await this.renderNode(rightNode, indent, depth + 1, encoder); const result = await this.renderNode(leftNode, indent, depth + 1, encoder); // Build result: left subtree, current node, right subtree result.push(here); result.push(...right); return result; } }