/** * MutableTree is a persistent tree which keeps track of versions. * * THREAD SAFETY NOTE: * - NOT safe for concurrent use. While Node.js is single-threaded, async operations * can interleave, so callers should serialize mutations (e.g., using a promise queue) * if multiple async operations might modify the tree simultaneously. * - An immutable tree at a given version can be returned via getImmutable, which is safe * for concurrent async access (reads only, no modifications). * * Given and returned key/value byte slices must not be modified, since they may point to data * located inside IAVL which would also be modified. * * The inner ImmutableTree should not be used directly by callers. * * Corresponds to Go's MutableTree in mutable_tree.go */ import type { Logger, } from "winston"; import { ChangeTracker, } from "./change-tracker.js"; import type { ExportNode, } from "./export/types.js"; import type { CommitmentProof, } from "./generated/cosmos/ics23/v1/proofs.js"; import { ImmutableTree, } from "./immutable-tree.js"; import { Node, } from "./node.js"; import { FastNode, } from "./storage/fast-node.js"; import type { NodeDB, } from "./storage/node-db.js"; import type { ChangeSet, } from "./types/index.js"; /** * MutableTree is a persistent tree which keeps track of versions. * NOT safe for concurrent mutations - serialize async operations if needed. */ export class MutableTree { /** Logger for diagnostics */ private readonly logger: Logger | null; /** Change tracker for recording modifications */ private readonly changeTracker: ChangeTracker; /** The current working tree (embedded ImmutableTree) */ private workingTree: ImmutableTree; /** The current working root node (mutable) */ private workingRoot: Node | null; /** The current working version */ private workingVersion: bigint; /** The most recently saved tree */ private lastSaved: ImmutableTree; /** FastNodes that have not yet been saved to disk */ private readonly unsavedFastNodeAdditions: Map; /** FastNodes that have not yet been removed from disk */ private readonly unsavedFastNodeRemovals: Map; /** Node database for persistent storage */ private readonly ndb: NodeDB; /** If true, the tree will work like no fast storage and always not upgrade fast storage */ private readonly skipFastStorageUpgrade: boolean; /** Whether initialVersion logic should apply (cleared after first save) */ private initialVersionSet: boolean; /** * Creates a new MutableTree instance. * * @param ndb - Node database for persistent storage * @param workingTree - The current working tree (ImmutableTree) * @param skipFastStorageUpgrade - If true, disable fast storage optimization * @param logger - Optional logger instance * @param enableChangeTracking - If true, enable change tracking (default: false) */ constructor( ndb: NodeDB, workingTree: ImmutableTree, skipFastStorageUpgrade: boolean = false, logger: Logger | null = null, enableChangeTracking: boolean = false, ) { this.ndb = ndb; this.workingTree = workingTree; this.workingRoot = workingTree.getRoot(); this.workingVersion = workingTree.getVersion(); this.skipFastStorageUpgrade = skipFastStorageUpgrade; this.logger = logger; // Clone the working tree as lastSaved this.lastSaved = workingTree.clone(); // Initialize unsaved fast node tracking this.unsavedFastNodeAdditions = new Map(); this.unsavedFastNodeRemovals = new Map(); // Check if initialVersion is set in options const opts = this.ndb.getOptions(); this.initialVersionSet = opts.initialVersion !== undefined; // Initialize change tracker this.changeTracker = new ChangeTracker(enableChangeTracking); } /** * Returns whether the working tree is empty (has no keys). * Only non-empty trees can be saved. * * @returns true if the tree has no keys */ isWorkingTreeEmpty(): boolean { return this.workingRoot === null || this.workingRoot.size === 0n; } /** * Returns the current working tree (for internal use). * * @returns The working ImmutableTree */ getWorkingTree(): ImmutableTree { return this.workingTree; } /** * Returns the root node of the working tree. * * @returns The root node, or null if tree is empty */ getRoot(): Node | null { return this.workingRoot; } /** * Returns the version of the working tree. * * @returns The current version */ getVersion(): bigint { return this.workingVersion; } /** * Returns the working version (version + 1). * This is the version that will be assigned when SaveVersion is called. * * Matches Go's WorkingVersion() with initialVersion support: * - If calculated version is 1 and initialVersion is set, use initialVersion * - Otherwise return workingVersion + 1 * * @returns The working version */ getWorkingVersion(): bigint { let version = this.workingVersion + 1n; // If this would be version 1 and initialVersionSet is true, use initialVersion instead // This allows first save to be version 0 (or other value) when configured // Note: initialVersionSet is cleared after first save (in saveVersion) if (version === 1n && this.initialVersionSet) { const opts = this.ndb.getOptions(); version = BigInt(opts.initialVersion!); } return version; } /** * Sets the initial version number for a new tree. * Can only be called before any versions are saved. * * Corresponds to Go's MutableTree.SetInitialVersion() (iavl/mutable_tree.go:305) * * @param version - The initial version number to use * @throws Error if tree already has saved versions */ setInitialVersion(version: number): void { // Check if tree already has versions if (this.workingVersion !== 0n) { throw new Error("tree already has versions, cannot set initial version"); } // Set the option in NodeDB const opts = this.ndb.getOptions(); opts.initialVersion = version; // Set the flag to indicate initialVersion logic should apply this.initialVersionSet = true; } /** * Returns the hash of the latest saved version of the tree. * If no versions have been saved, returns null. * * @returns The hash, or null if no versions saved */ getHash(): Uint8Array | null { return this.lastSaved.hash(); } /** * Returns the hash of the current working tree. * * @returns The working tree hash, or null if tree is empty */ getWorkingHash(): Uint8Array | null { if (!this.workingRoot) { return null; } // Use computeHashWithDescendants to handle unsaved nodes (nodes without nodeKey) // This recursively computes hashes for all children before computing parent hash return this.workingRoot.computeHashWithDescendants(this.getWorkingVersion()); } /** * Returns the size (number of leaf nodes) in the working tree. * * @returns The tree size */ getSize(): bigint { if (!this.workingRoot) { return 0n; } return this.workingRoot.size; } /** * Gets the NodeDB instance (for internal use by Importer) * @internal */ getNodeDB(): NodeDB { return this.ndb; } /** * Checks if a specific version exists in the tree. * Returns true if the version has been saved, false otherwise. * * Corresponds to Go's MutableTree.VersionExists() * * @param version - Version number to check * @returns True if version exists, false otherwise */ async versionExists(version: bigint): Promise { return await this.ndb.versionExists(version); } /** * Returns the most recent saved version number. * Returns 0n if no versions have been saved. * * Corresponds to Go's MutableTree.GetLatestVersion() * * @returns The latest version number */ getLatestVersion(): bigint { return this.ndb.getLatestVersion(); } /** * Returns an array of all available version numbers in the tree. * Returns empty array if no versions have been saved. * * Corresponds to Go's MutableTree.AvailableVersions() * * @returns Sorted array of all saved version numbers */ async availableVersions(): Promise { return await this.ndb.getVersions(); } /** * Gets the value for a key in the tree. * Checks unsaved additions first, then falls back to tree traversal. * * IMPORTANT: The returned value must not be modified, since it may point to data * stored within IAVL which would also be modified (reference sharing in JavaScript). * * @param key - The key to look up * @returns The value, or null if key doesn't exist */ async get(key: Uint8Array): Promise { // Fast storage optimization: check unsaved changes first // NOTE: Must check before empty tree check, as unsaved additions // may exist even when tree is empty if (!this.skipFastStorageUpgrade) { // Check unsaved additions (new keys not yet persisted) const keyStr = Buffer.from(key).toString("hex"); const fastNode = this.unsavedFastNodeAdditions.get(keyStr); if (fastNode) { // Return value from unsaved addition // NOTE: Returning reference to internal data - caller must not modify return fastNode.value; } // Check unsaved removals (deleted keys not yet removed from disk) if (this.unsavedFastNodeRemovals.has(keyStr)) { // Key was deleted in this working tree return null; } } // Empty tree check (after unsaved checks) if (this.workingRoot === null) { return null; } // Fall back to tree traversal const result = await this.workingRoot.get(this.ndb, key); return result.value; } /** * Sets a key-value pair in the tree. * Returns true if the key already existed (update), false if it's a new key (insert). * * IMPORTANT: The key and value byte arrays must not be modified after this call, * since they may be stored within IAVL (reference sharing in JavaScript). * * @param key - The key to set * @param value - The value to set * @returns true if key was updated, false if newly inserted * @throws Error if value is null */ async set(key: Uint8Array, value: Uint8Array): Promise { if (!value) { throw new Error(`Attempt to store nil value at key '${Buffer.from(key).toString("hex")}'`); } // Track the change if tracking is enabled this.changeTracker.recordSet(key, value); // Empty tree: create root node if (this.workingRoot === null) { if (!this.skipFastStorageUpgrade) { this.addUnsavedAddition(key, new FastNode(key, value, this.getWorkingVersion())); } // Create new root this.workingRoot = Node.newLeafNode(key, value); return false; // New insertion } // Recursively set in existing tree const result = await this.recursiveSet(this.workingRoot, key, value); this.workingRoot = result.newNode; return result.updated; } /** * Helper to add an unsaved fast node addition. * Removes from unsavedFastNodeRemovals if present. * * @param key - The key * @param fastNode - The fast node to add */ private addUnsavedAddition(key: Uint8Array, fastNode: FastNode): void { const keyStr = Buffer.from(key).toString("hex"); this.unsavedFastNodeRemovals.delete(keyStr); this.unsavedFastNodeAdditions.set(keyStr, fastNode); } /** * Recursively sets a key-value pair in the tree. * Implements copy-on-write semantics by cloning nodes on mutation. * * @param node - Current node * @param key - Key to set * @param value - Value to set * @returns Object with new node and whether key was updated */ private async recursiveSet( node: Node, key: Uint8Array, value: Uint8Array, ): Promise<{ newNode: Node updated: boolean }> { if (node.isLeaf()) { return this.recursiveSetLeaf(node, key, value); } // Clone node for copy-on-write const clonedNode = await node.clone(this.ndb); // Compare key to decide left or right subtree const cmp = Buffer.compare(key, node.key!); let updated: boolean; if (cmp < 0) { // Go left const result = await this.recursiveSet(clonedNode.leftNode!, key, value); clonedNode.leftNode = result.newNode; updated = result.updated; } else { // Go right const result = await this.recursiveSet(clonedNode.rightNode!, key, value); clonedNode.rightNode = result.newNode; updated = result.updated; } if (updated) { // Key already existed, just return cloned node return { newNode: clonedNode, updated: true, }; } // New insertion: recalculate height/size and rebalance await clonedNode.calcHeightAndSize(this.ndb); const balanced = await this.balance(clonedNode); return { newNode: balanced, updated: false, }; } /** * Handles setting a key-value pair when current node is a leaf. * Three cases: * 1. key < node.key: Create branch with new key on left * 2. key > node.key: Create branch with new key on right * 3. key == node.key: Replace value (update) * * @param node - Current leaf node * @param key - Key to set * @param value - Value to set * @returns Object with new node and whether key was updated */ private recursiveSetLeaf( node: Node, key: Uint8Array, value: Uint8Array, ): { newNode: Node updated: boolean } { const version = this.getWorkingVersion(); if (!this.skipFastStorageUpgrade) { this.addUnsavedAddition(key, new FastNode(key, value, version)); } const cmp = Buffer.compare(key, node.key!); if (cmp < 0) { // setKey < leafKey: new key goes on left const newLeaf = Node.newLeafNode(key, value); const branch = new Node(); branch.key = node.key; branch.subtreeHeight = 1; branch.size = 2n; branch.nodeKey = null; branch.leftNode = newLeaf; branch.rightNode = node; return { newNode: branch, updated: false, }; } else if (cmp > 0) { // setKey > leafKey: new key goes on right const newLeaf = Node.newLeafNode(key, value); const branch = new Node(); branch.key = key; branch.subtreeHeight = 1; branch.size = 2n; branch.nodeKey = null; branch.leftNode = node; branch.rightNode = newLeaf; return { newNode: branch, updated: false, }; } else { // setKey == leafKey: replace value (update) return { newNode: Node.newLeafNode(key, value), updated: true, }; } } /** * Removes a key from the working tree. * The key should not be modified after this call. * * @param key - The key to remove * @returns Object with removed value and whether removal occurred */ async remove(key: Uint8Array): Promise<{ value: Uint8Array | null removed: boolean }> { if (this.workingRoot === null) { return { value: null, removed: false, }; } const result = await this.recursiveRemove(this.workingRoot, key); if (!result.removed) { return { value: null, removed: false, }; } // Track the removal if tracking is enabled this.changeTracker.recordDelete(key, result.value ?? undefined); if (!this.skipFastStorageUpgrade) { this.addUnsavedRemoval(key); } this.workingRoot = result.newNode; return { value: result.value, removed: true, }; } /** * Iterates over all keys in the tree, calling a callback function for each key-value pair. * Returns true if iteration was stopped early by the callback returning true. * * Corresponds to Go's MutableTree.Iterate() * * @param fn - Callback function called for each key-value pair. Return true to stop iteration. * @returns True if iteration was stopped early, false if iteration completed */ async iterate(fn: (key: Uint8Array, value: Uint8Array) => boolean): Promise { if (this.workingRoot === null) { return false; } const iter = this.iterator(undefined, undefined); 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(); } } /** * Returns an iterator over the mutable tree in ascending order. * CONTRACT: no updates should be made to the tree while an iterator is active. * * Corresponds to Go's MutableTree.Iterator() * * @param start - Start key (inclusive), or undefined for beginning * @param end - End key (exclusive), or undefined for end * @returns Iterator over the tree */ iterator( start: Uint8Array | undefined, end: Uint8Array | undefined, ) { return this.workingTree.iterator(start ?? null, end ?? null); } /** * Returns a reverse iterator over the mutable tree (descending order). * CONTRACT: no updates should be made to the tree while an iterator is active. * * @param start - Start key (inclusive), or undefined for end * @param end - End key (exclusive), or undefined for beginning * @returns Reverse iterator over the tree */ reverseIterator( start: Uint8Array | undefined, end: Uint8Array | undefined, ) { return this.workingTree.reverseIterator(start ?? null, end ?? null); } /** * Helper to add an unsaved fast node removal. * Removes from unsavedFastNodeAdditions if present. * * @param key - The key to mark as removed */ private addUnsavedRemoval(key: Uint8Array): void { const keyStr = Buffer.from(key).toString("hex"); this.unsavedFastNodeAdditions.delete(keyStr); this.unsavedFastNodeRemovals.set(keyStr, true); } /** * Recursively removes a key from the tree. * Implements copy-on-write semantics by cloning nodes on mutation. * * @param node - Current node * @param key - Key to remove * @returns Object with new node, new key (for branch node key updates), removed value, and whether removal occurred */ private async recursiveRemove( node: Node, key: Uint8Array, ): Promise<{ newNode: Node | null newKey: Uint8Array | null value: Uint8Array | null removed: boolean }> { // Base case: leaf node if (node.isLeaf()) { if (Buffer.compare(key, node.key!) === 0) { // Found the key to remove return { newNode: null, newKey: null, value: node.value!, removed: true, }; } // Key not found return { newNode: node, newKey: null, value: null, removed: false, }; } // Clone node for copy-on-write const clonedNode = await node.clone(this.ndb); // Compare key to decide left or right subtree const cmp = Buffer.compare(key, node.key!); if (cmp < 0) { // Go left const result = await this.recursiveRemove(clonedNode.leftNode!, key); if (!result.removed) { // Key not found, return unchanged node return { newNode: clonedNode, newKey: null, value: null, removed: false, }; } if (result.newNode === null) { // Left child was removed, return right child return { newNode: clonedNode.rightNode, newKey: clonedNode.key!, value: result.value, removed: true, }; } // Update left child, recalculate height/size, and rebalance clonedNode.leftNode = result.newNode; await clonedNode.calcHeightAndSize(this.ndb); const balanced = await this.balance(clonedNode); return { newNode: balanced, newKey: result.newKey, value: result.value, removed: true, }; } else { // Go right (cmp >= 0) const result = await this.recursiveRemove(clonedNode.rightNode!, key); if (!result.removed) { // Key not found, return unchanged node return { newNode: clonedNode, newKey: null, value: null, removed: false, }; } if (result.newNode === null) { // Right child was removed, return left child return { newNode: clonedNode.leftNode, newKey: null, value: result.value, removed: true, }; } // Update right child clonedNode.rightNode = result.newNode; // Update branch key if needed (when right child's leftmost key changed) if (result.newKey !== null) { clonedNode.key = result.newKey; } await clonedNode.calcHeightAndSize(this.ndb); const balanced = await this.balance(clonedNode); return { newNode: balanced, newKey: null, value: result.value, removed: true, }; } } /** * Performs a right rotation on the given node. * Used for rebalancing when left subtree is too tall. * * Before: node After: newNode * / \ / \ * left c => a node * / \ / \ * a b b c * * @param node - The node to rotate (will be cloned) * @returns The new root of the rotated subtree */ private async rotateRight(node: Node): Promise { // Check if node has left child before rotating if (!node.leftNode) { throw new Error("Cannot rotate right: node has no left child"); } // Clone the node for copy-on-write const clonedNode = await node.clone(this.ndb); // Clone the left child (will become new root) const newNode = await clonedNode.leftNode!.clone(this.ndb); // Perform rotation clonedNode.leftNode = newNode.rightNode; newNode.rightNode = clonedNode; // Recalculate height and size (only for branch nodes) if (!clonedNode.isLeaf()) { await clonedNode.calcHeightAndSize(this.ndb); } await newNode.calcHeightAndSize(this.ndb); return newNode; } /** * Performs a left rotation on the given node. * Used for rebalancing when right subtree is too tall. * * Before: node After: newNode * / \ / \ * a right => node c * / \ / \ * b c a b * * @param node - The node to rotate (will be cloned) * @returns The new root of the rotated subtree */ private async rotateLeft(node: Node): Promise { // Check if node has right child before rotating if (!node.rightNode) { throw new Error("Cannot rotate left: node has no right child"); } // Clone the node for copy-on-write const clonedNode = await node.clone(this.ndb); // Clone the right child (will become new root) const newNode = await clonedNode.rightNode!.clone(this.ndb); // Perform rotation clonedNode.rightNode = newNode.leftNode; newNode.leftNode = clonedNode; // Recalculate height and size (only for branch nodes) if (!clonedNode.isLeaf()) { await clonedNode.calcHeightAndSize(this.ndb); } await newNode.calcHeightAndSize(this.ndb); return newNode; } /** * Balances an AVL tree node by performing rotations if needed. * Assumes node can be modified (not persisted). * * AVL Balance Cases: * - balance > 1 (left-heavy): * - Left-Left: Single right rotation * - Left-Right: Left rotation on left child, then right rotation on node * - balance < -1 (right-heavy): * - Right-Right: Single left rotation * - Right-Left: Right rotation on right child, then left rotation on node * - -1 <= balance <= 1: Already balanced, no rotation needed * * @param node - The node to balance (must not be persisted) * @returns The new root of the balanced subtree * @throws Error if node is already persisted */ private async balance(node: Node): Promise { // Ensure node hasn't been persisted (can be modified) if (node.nodeKey !== null) { throw new Error("unexpected balance() call on persisted node"); } // Calculate balance factor (left height - right height) const balance = node.getBalanceFactor(); // Left-heavy case (balance > 1) if (balance > 1) { // Check left child's balance to determine rotation type const leftBalance = node.leftNode!.getBalanceFactor(); if (leftBalance >= 0) { // Left-Left Case: Single right rotation const newNode = await this.rotateRight(node); return newNode; } // Left-Right Case: Double rotation // First rotate left child left, then rotate node right node.leftNodeKey = null; // Clear cached key node.leftNode = await this.rotateLeft(node.leftNode!); const newNode = await this.rotateRight(node); return newNode; } // Right-heavy case (balance < -1) if (balance < -1) { // Load right child if needed const rightNode = await node.getRightNode(this.ndb); if (!rightNode) { throw new Error("Right node should exist for right-heavy tree"); } // Check right child's balance to determine rotation type const rightBalance = rightNode.getBalanceFactor(); if (rightBalance <= 0) { // Right-Right Case: Single left rotation const newNode = await this.rotateLeft(node); return newNode; } // Right-Left Case: Double rotation // First rotate right child right, then rotate node left node.rightNodeKey = null; // Clear cached key node.rightNode = await this.rotateRight(rightNode); const newNode = await this.rotateLeft(node); return newNode; } // Already balanced (-1 <= balance <= 1) return node; } /** * SaveVersion saves a new tree version to disk and returns the hash. * * Steps: * 1. Check if version already exists (idempotent check) * 2. Save fast storage nodes (if not skipped) * 3. Save new tree nodes with assigned node keys * 4. Commit changes to storage * 5. Update version and reset working state * * @returns Object with hash and version number * @throws Error if version already exists with different hash */ async saveVersion(): Promise<{ hash: Uint8Array | null version: bigint }> { // Check if no changes since last save (idempotent) // Only applies if we've saved at least once (workingVersion was updated by a save) // For fresh trees, workingVersion equals lastSaved version (both from initial ImmutableTree) // After first save, workingVersion is updated to the saved version const hasSavedBefore = await this.ndb.versionExists(this.workingVersion); if (hasSavedBefore && this.workingRoot === this.lastSaved.getRoot()) { // No changes since last save - return the last saved version return { hash: this.lastSaved.hash(), version: this.workingVersion, }; } const version = this.getWorkingVersion(); // Clear initialVersionSet after first save (matches Go behavior) this.initialVersionSet = false; // Check if version already exists if (await this.ndb.versionExists(version)) { // If version exists, verify it's the same hash (idempotent) const existingNodeKey = await this.ndb.getRoot(version); let existingRoot: Node | null = null; if (existingNodeKey !== null) { existingRoot = await this.ndb.getNode(existingNodeKey); } const newHash = this.workingHash(); // If both null or same hash, it's idempotent const existingHash = existingRoot?.hash ?? null; const hashesMatch = (existingHash === null && newHash === null) || (existingHash !== null && newHash !== null && Buffer.from(existingHash).equals(Buffer.from(newHash))); if ( (existingRoot === null && this.workingRoot === null) || hashesMatch ) { // Update internal state to match saved version this.workingVersion = version; this.workingRoot = existingRoot; const newWorkingTree = this.workingTree.clone(); this.lastSaved = newWorkingTree.clone(); return { hash: newHash, version, }; } // Version exists with different hash - error throw new Error( `version ${version} was already saved to different hash ` + `(existing: ${existingHash ? Buffer.from(existingHash).toString("hex") : "null"}, ` + `new: ${newHash ? Buffer.from(newHash).toString("hex") : "null"})`, ); } this.logger?.debug("SAVE TREE", { version: version.toString(), }); // Save fast storage nodes if (!this.skipFastStorageUpgrade) { await this.saveFastNodeVersion(version); } // Save tree nodes if (this.workingRoot === null) { await this.ndb.saveEmptyRoot(version); } else { if (this.workingRoot.nodeKey !== null) { // No updated nodes - just save root reference await this.ndb.saveRoot(version, this.workingRoot.nodeKey.toBytes()); // Handle legacy nodes if (this.workingRoot.isLegacy) { this.workingRoot.isLegacy = false; await this.ndb.saveNode(this.workingRoot); } } else { // Save all new nodes await this.saveNewNodes(version); } } // Mark committing to prevent async pruning interference this.ndb.setCommitting(); try { // Commit to storage await this.ndb.commit(); // Update version tracking this.ndb.resetLatestVersion(version); } finally { // Always unset committing flag this.ndb.unsetCommitting(); } this.workingVersion = version; // Set new working tree - create new ImmutableTree with saved state // This creates a snapshot of what was just saved this.workingTree = new ImmutableTree( this.workingRoot, this.ndb, version, this.skipFastStorageUpgrade, ); this.lastSaved = this.workingTree.clone(); // Clear unsaved fast node maps if (!this.skipFastStorageUpgrade) { this.unsavedFastNodeAdditions.clear(); this.unsavedFastNodeRemovals.clear(); } // Clear change tracker after successful save this.changeTracker.clear(); // Return hash from the saved tree (matches Go's tree.Hash()) return { hash: this.lastSaved.hash(), version, }; } /** * SaveChangeSet applies a ChangeSet (set of key-value changes) to the tree and saves a new version. * * The method will: * 1. Check for uncommitted changes (returns error if any exist) * 2. Apply all changes in the changeset (set/delete operations) * 3. Save the version * 4. Return the new version number * * Corresponds to Go's MutableTree.SaveChangeSet() (iavl/mutable_tree.go:622) * * @param changeSet - The set of changes to apply * @returns The new version number * @throws Error if there are uncommitted changes * @throws Error if attempting to delete a non-existent key * @throws Error on any set/remove operation failure */ async saveChangeSet(changeSet: ChangeSet): Promise { // Check for uncommitted changes if (this.workingRoot !== null && this.workingRoot.nodeKey === null) { throw new Error("cannot save changeset with uncommitted changes"); } // Apply all changes for (const pair of changeSet.pairs) { if (pair.delete) { // For deletes, error if key doesn't exist (matching Go behavior) const result = await this.remove(pair.key); if (!result.removed) { throw new Error(`attempted to remove non-existent key ${Buffer.from(pair.key).toString("hex")}`); } } else { // For sets, just set the value await this.set(pair.key, pair.value); } } // Save version and return version number const result = await this.saveVersion(); return result.version; } /** * LoadVersion loads a specific version of the tree into the working state. * Returns the latest version available in the database. * * If targetVersion is 0 or negative, loads the latest version. * If targetVersion doesn't exist, returns an error. * * @param targetVersion - The version to load (0 or negative for latest) * @returns The latest version number available in the database * @throws Error if version doesn't exist or is invalid */ async loadVersion(targetVersion: bigint): Promise { const firstVersion = this.ndb.getFirstVersion(); const latestVersion = this.ndb.getLatestVersion(); // Check if initialVersion is set and conflicts with firstVersion const opts = this.ndb.getOptions(); if (firstVersion > 0n && opts.initialVersion !== undefined && firstVersion < BigInt(opts.initialVersion)) { throw new Error( `initial version set to ${opts.initialVersion}, but found earlier version ${firstVersion}`, ); } // Check if any versions exist if (latestVersion === 0n) { if (targetVersion <= 0n) { // No versions saved yet - this is ok for an empty tree // Handle fast storage upgrade if needed if (!this.skipFastStorageUpgrade) { await this.enableFastStorageAndCommitIfNotEnabled(); } return 0n; } throw new Error(`no versions found while trying to load ${targetVersion}`); } // If targetVersion is 0 or negative, load latest if (targetVersion <= 0n) { targetVersion = latestVersion; } // Check if target version is too high if (latestVersion < targetVersion) { throw new Error( `wanted to load target ${targetVersion} but only found up to ${latestVersion}`, ); } // Check if version exists if (!await this.ndb.versionExists(targetVersion)) { throw new Error(`version ${targetVersion} does not exist`); } // Load root node key for target version const rootNodeKey = await this.ndb.getRoot(targetVersion); // Load root node if it exists let rootNode: Node | null = null; if (rootNodeKey !== null) { rootNode = await this.ndb.getNode(rootNodeKey); if (rootNode === null) { throw new Error(`root node not found for version ${targetVersion}`); } } // Create new ImmutableTree for this version const iTree = new ImmutableTree( rootNode, this.ndb, targetVersion, this.skipFastStorageUpgrade, ); // Update working tree to loaded version this.workingTree = iTree; this.workingRoot = iTree.getRoot(); this.workingVersion = targetVersion; this.lastSaved = iTree.clone(); // Clear unsaved changes this.unsavedFastNodeAdditions.clear(); this.unsavedFastNodeRemovals.clear(); // Handle fast storage upgrade if needed if (!this.skipFastStorageUpgrade) { await this.enableFastStorageAndCommitIfNotEnabled(); } return latestVersion; } /** * LoadVersionForOverwriting loads a version and allows overwriting it. * This deletes all versions after the target version, preparing the tree for overwriting history. * * Corresponds to Go's MutableTree.LoadVersionForOverwriting() (iavl/mutable_tree.go:266) * * Use case: Rolling back to a previous state and creating a new branch of history. * * @param targetVersion - The version to load (all versions after this will be deleted) * @returns The latest version number available in the database * @throws Error if version doesn't exist or deletion fails */ async loadVersionForOverwriting(targetVersion: bigint): Promise { // Load the target version const loadedVersion = await this.loadVersion(targetVersion); // Delete all versions after this one await this.deleteVersionsFrom(targetVersion + 1n); // Commit the deletion await this.ndb.commit(); // Handle fast storage upgrade if needed if (!this.skipFastStorageUpgrade) { // This will repopulate the fast node index because of version mismatch await this.enableFastStorageAndCommitIfNotEnabled(); } return loadedVersion; } /** * GetImmutable loads an ImmutableTree at a given version for querying. * The returned tree is safe for concurrent access (read-only), provided the * version is not deleted via DeleteVersion(). * * This method loads the version from the database and creates a new ImmutableTree * instance. It does NOT return the current working tree or lastSaved tree, * ensuring consistency with the persisted state. * * @param version - The version to load * @returns ImmutableTree at the specified version * @throws Error if version doesn't exist or loading fails */ async getImmutable(version: bigint): Promise { // Check if version exists const exists = await this.ndb.versionExists(version); if (!exists) { throw new Error(`version ${version} does not exist`); } // Load root node key for the version const rootNodeKey = await this.ndb.getRoot(version); // Load root node if it exists let rootNode: Node | null = null; if (rootNodeKey !== null) { rootNode = await this.ndb.getNode(rootNodeKey); if (rootNode === null) { throw new Error(`root node not found for version ${version}`); } } // Create and return new ImmutableTree instance return new ImmutableTree( rootNode, this.ndb, version, this.skipFastStorageUpgrade, ); } /** * Get Versioned gets the value at the specified key and version. * The returned value must not be modified, since it may point to data stored within IAVL. * * Based on Go IAVL v1.3.5 mutable_tree.go GetVersioned (lines 665-695) * * @param key - The key to look up * @param version - The version to query * @returns The value at the key for the specified version, or null if not found */ async getVersioned( key: Uint8Array, version: bigint, ): Promise { const exists = await this.ndb.versionExists(version); if (!exists) { return null; } // Fast storage optimization: try to use fast storage if available // This is only applicable when fast storage is enabled if (!this.skipFastStorageUpgrade) { // Check if fast storage can be used // Fast storage is only usable for the latest version const latestVersion = this.ndb.getLatestVersion(); const isLatestVersion = version === latestVersion; const hasFastStorage = this.ndb.hasUpgradedToFastStorage(); if (isLatestVersion && hasFastStorage) { // Try to get from fast storage const fastNode = await this.ndb.getFastNode(key); // If no fast node and this is the latest version, key doesn't exist if (!fastNode && version === latestVersion) { return null; } // If fast node exists and was last updated at or before the requested version, // return its value if (fastNode && fastNode.versionLastUpdatedAt <= version) { return fastNode.value; } } } // Fall back to regular tree traversal const tree = await this.getImmutable(version); return tree.get(key); } /** * Get Versioned Proof gets the proof for the given key at the specified version. * Returns either a membership or non-membership proof depending on whether the key exists. * * Based on Go IAVL v1.3.5 proof_ics23.go GetVersionedProof (lines 203-212) * * @param key - The key to generate a proof for * @param version - The version to generate the proof at * @returns CommitmentProof for the key at the specified version * @throws Error if version doesn't exist */ async getVersionedProof( key: Uint8Array, version: bigint, ): Promise { const exists = await this.ndb.versionExists(version); if (!exists) { throw new Error(`version ${version} does not exist`); } const tree = await this.getImmutable(version); return tree.getProof(key); } /** * Rollback resets the working tree to the latest saved version, discarding * any unsaved modifications. * * This is useful when you want to abandon uncommitted changes and return to * the last saved state. After rollback: * - Working tree is restored to lastSaved state * - All unsaved mutations are discarded * - Unsaved fast node additions/removals are cleared * * If no versions have been saved yet (version === 0), rollback creates a * fresh empty tree. */ rollback(): void { if (this.workingVersion > 0n) { // Restore to last saved version this.workingTree = this.lastSaved.clone(); this.workingRoot = this.workingTree.getRoot(); } else { // No versions saved yet, create empty tree this.workingTree = new ImmutableTree( null, this.ndb, 0n, this.skipFastStorageUpgrade, ); this.workingRoot = null; } // Clear unsaved changes if (!this.skipFastStorageUpgrade) { this.unsavedFastNodeAdditions.clear(); this.unsavedFastNodeRemovals.clear(); } // Clear change tracker on rollback this.changeTracker.clear(); } /** * Deletes a specific version from the tree. * The version must exist and cannot be the latest version. * * Note: This is a simplified implementation. Full orphan node cleanup * will be added when orphan tracking is implemented. * * @param version - Version to delete * @throws Error if version doesn't exist or is the latest version */ async deleteVersion(version: bigint): Promise { await this.ndb.deleteVersion(version); await this.ndb.commit(); } /** * Deletes all versions from the first version up to and including toVersion. * This is useful for pruning old versions to reclaim space. * * After deletion, the first available version will be toVersion + 1. * * @param toVersion - Delete all versions up to and including this (inclusive) * @throws Error if toVersion is invalid or versions have active readers */ async deleteVersionsTo(toVersion: bigint): Promise { await this.ndb.deleteVersionsTo(toVersion); await this.ndb.commit(); } /** * Deletes all versions from fromVersion upwards (including fromVersion). * This effectively "rewinds" the tree to an earlier state. * * After deletion, the latest version will be fromVersion-1. * * @param fromVersion - Delete all versions from this onwards (inclusive) * @throws Error if fromVersion is invalid or versions have active readers */ async deleteVersionsFrom(fromVersion: bigint): Promise { await this.ndb.deleteVersionsFrom(fromVersion); await this.ndb.commit(); } /** * Enables fast storage and commits if not already enabled. * This is called after loading versions to ensure fast storage is upgraded. * @returns true if fast storage was enabled, false if already enabled */ private async enableFastStorageAndCommitIfNotEnabled(): Promise { // TODO: Implement fast storage upgrade in a future item // For now, return false (already enabled/not needed) return false; } /** * Returns the hash of the current working tree. * Uses workingRoot since it's kept up-to-date with mutations. * Uses recursive hash computation to handle unsaved nodes. * @returns Hash of working tree, or null if empty */ private workingHash(): Uint8Array | null { if (!this.workingRoot) { return null; } // Compute hash recursively to handle unsaved nodes this.workingRoot.computeHashWithDescendants(this.getWorkingVersion()); return this.workingRoot.hash; } /** * Saves fast storage nodes for a version. * @param version - Version number to save fast nodes for */ private async saveFastNodeVersion(version: bigint): Promise { await this.saveFastNodeAdditions(); await this.saveFastNodeRemovals(); await this.ndb.setFastStorageVersionToBatch(version); } /** * Saves all unsaved fast node additions to storage. */ private async saveFastNodeAdditions(): Promise { // Sort keys for deterministic order const keys = Array.from(this.unsavedFastNodeAdditions.keys()).sort(); for (const key of keys) { const node = this.unsavedFastNodeAdditions.get(key); if (node) { await this.ndb.saveFastNode(node); } } } /** * Saves all unsaved fast node removals to storage. */ private async saveFastNodeRemovals(): Promise { // Sort keys for deterministic order const keys = Array.from(this.unsavedFastNodeRemovals.keys()).sort(); for (const key of keys) { await this.ndb.deleteFastNode(Buffer.from(key, "hex")); } } /** * Saves all new nodes recursively, assigning node keys. * @param version - Version number for node keys */ private async saveNewNodes(version: bigint): Promise { let nonce = 0; const newNodes: Node[] = []; // Recursive function to assign keys to nodes const recursiveAssignKey = async (node: Node): Promise => { if (node.nodeKey !== null) { return node.nodeKey.toBytes(); } nonce++; // Import NodeKey class const { NodeKey, } = await import("./node-key.js"); node.nodeKey = new NodeKey(version, nonce); // For inner nodes, recursively assign keys to children if (node.subtreeHeight > 0) { if (node.leftNode) { node.leftNodeKey = await recursiveAssignKey(node.leftNode); } if (node.rightNode) { node.rightNodeKey = await recursiveAssignKey(node.rightNode); } } // Hash the node with its version node.computeHash(version); newNodes.push(node); return node.nodeKey.toBytes(); }; // Assign keys starting from root if (this.workingRoot) { await recursiveAssignKey(this.workingRoot); } // Save all nodes and clear references for (const node of newNodes) { await this.ndb.saveNode(node); // Clear child references to free memory node.leftNode = null; node.rightNode = null; } // Note: We do NOT call saveRoot here (unlike when root.nodeKey !== null) // The root node is saved directly via SaveNode above, and getRoot() handles // the "implicit root" case where a node exists at GetRootKey(version). // Calling saveRoot here would create a self-reference and overwrite the node data. // Matches Go IAVL mutable_tree.go saveNewNodes() which does not call SaveRoot. } /** * Import imports nodes from an Exporter into this tree. * The tree must be empty and the database must have no existing versions. * Nodes must be provided in the same order as exported (post-order LRN). * * Based on Go IAVL mutable_tree.go Import method. * * @param exporter - The Exporter to import nodes from * @param version - The version to import as * @throws Error if tree is not empty or version is invalid * * @example * ```typescript * const sourceTree = await MutableTree.create(sourceDb); * await sourceTree.set(str("a"), str("1")); * await sourceTree.saveVersion(); * * const exporter = sourceTree.getWorkingTree().export(); * * const targetTree = await MutableTree.create(targetDb); * await targetTree.import(exporter, 1n); * ``` */ async import( exporter: AsyncIterableIterator, version: bigint, ): Promise { const { Importer, } = await import("./import/importer.js"); const importer = new Importer(this, version); try { for await (const node of exporter) { await importer.add(node); } await importer.commit(); } catch (error) { importer.close(); throw error; } } /** * Import compressed nodes into an empty tree from a compressed exporter. * The compressed exporter uses delta encoding to reduce size. * * @param exporter - Async iterator that yields compressed ExportNodes * @param version - The version to import (must match export version) * @throws Error if tree is not empty or import fails * * @example * ```typescript * const sourceTree = await MutableTree.create(sourceDb); * await sourceTree.set(str("a"), str("1")); * await sourceTree.saveVersion(); * * const exporter = sourceTree.getWorkingTree().exportCompressed(); * * const targetTree = await MutableTree.create(targetDb); * await targetTree.importCompressed(exporter, 1n); * ``` */ async importCompressed( exporter: AsyncIterable, version: bigint, ): Promise { const { Importer, } = await import("./import/importer.js"); const { CompressImporter, } = await import("./export/compress.js"); // Import the type separately const baseImporter = new Importer(this, version); // Create adapter for the importer interface const importerAdapter = { async add(node: ExportNode): Promise { await baseImporter.add(node); }, }; const decompressor = new CompressImporter(importerAdapter); try { for await (const node of exporter) { await decompressor.add(node); } await baseImporter.commit(); } catch (error) { baseImporter.close(); throw error; } } /** * 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 a convenience method that delegates to the NodeDB. * Based on Go IAVL v1.3.5 mutable_tree.go (though Go has it on ImmutableTree) * * @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 */ async traverseStateChanges( startVersion: bigint, endVersion: bigint, fn: (version: bigint, changeSet: ChangeSet) => Promise, ): Promise { return this.ndb.traverseStateChanges(startVersion, endVersion, fn); } /** * Checks if the tree storage format can be upgraded. * In our TypeScript implementation, we already use the latest format, * so this always returns false (no upgrade needed/possible). * * Corresponds to Go's MutableTree.IsUpgradeable() * * @returns false - TypeScript implementation uses latest format */ isUpgradeable(): boolean { // In the Go implementation, this checks if fast storage upgrade is needed. // In our TS implementation, we always use the latest format from the start, // so there's nothing to upgrade. return false; } /** * Returns a string representation of the tree for debugging. * Shows the current version, size, and root hash. * * Corresponds to Go's MutableTree.String() * * @returns String representation of the tree */ toString(): string { const hash = this.workingHash(); const hashHex = hash ? Buffer.from(hash).toString("hex").substring(0, 16) : "null"; const size = this.workingRoot?.size ?? 0n; return `MutableTree{version=${this.workingVersion}, size=${size}, hash=${hashHex}...}`; } // === Change Tracking Methods === /** * Enable or disable change tracking. * When enabled, the tree tracks all set and remove operations. * * @param enabled - Whether to enable change tracking */ setChangeTracking(enabled: boolean): void { this.changeTracker.setEnabled(enabled); } /** * Check if change tracking is enabled. * * @returns True if change tracking is enabled */ isChangeTrackingEnabled(): boolean { return this.changeTracker.isEnabled(); } /** * Get the current change set containing all modifications since the last save. * Returns a copy of the change set to prevent external modifications. * * @returns The current change set */ getChangeSet(): ChangeSet { return this.changeTracker.getChangeSet(); } /** * Get the number of changes tracked since the last save. * * @returns Number of tracked changes */ getChangeCount(): number { return this.changeTracker.size(); } /** * Clear the current change set. * This is automatically called after saveVersion() and rollback(). */ clearChangeSet(): void { this.changeTracker.clear(); } /** * Get statistics about the current change tracking. * * @returns Change tracking statistics */ getChangeStats(): { total: number sets: number deletes: number enabled: boolean maxChanges: number } { return this.changeTracker.getStats(); } /** * Check if a specific key has been changed since the last save. * * @param key - The key to check * @returns True if the key has been modified */ hasChange(key: Uint8Array): boolean { return this.changeTracker.hasChange(key); } /** * Apply a change set to the tree. * This applies all changes in the set (sets and deletes) to the current tree. * Note: This does not save the tree - call saveVersion() after to persist. * * @param changeSet - The change set to apply */ async applyChangeSet(changeSet: ChangeSet): Promise { for (const pair of changeSet.pairs) { if (pair.delete) { await this.remove(pair.key); } else { await this.set(pair.key, pair.value); } } } /** * Serialize the current change set to protobuf bytes. * Useful for network transmission or storage. * * @returns Serialized change set */ serializeChangeSet(): Uint8Array { return this.changeTracker.serialize(); } }