import { ChangeSet } from "./generated/changeset.js"; import { ExportNode } from "./export/types.js"; import { CommitmentProof } from "./generated/cosmos/ics23/v1/proofs.js"; import { TreeIterator } from "./iterator/iterator.js"; import { Node } from "./node.js"; import { ImmutableTree } from "./immutable-tree.js"; import { NodeDB } from "./storage/node-db.js"; import { Logger } from "winston"; //#region src/mutable-tree.d.ts /** * MutableTree is a persistent tree which keeps track of versions. * NOT safe for concurrent mutations - serialize async operations if needed. */ declare class MutableTree { /** Logger for diagnostics */ private readonly logger; /** Change tracker for recording modifications */ private readonly changeTracker; /** The current working tree (embedded ImmutableTree) */ private workingTree; /** The current working root node (mutable) */ private workingRoot; /** The current working version */ private workingVersion; /** The most recently saved tree */ private lastSaved; /** FastNodes that have not yet been saved to disk */ private readonly unsavedFastNodeAdditions; /** FastNodes that have not yet been removed from disk */ private readonly unsavedFastNodeRemovals; /** Node database for persistent storage */ private readonly ndb; /** If true, the tree will work like no fast storage and always not upgrade fast storage */ private readonly skipFastStorageUpgrade; /** Whether initialVersion logic should apply (cleared after first save) */ private initialVersionSet; /** * 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, logger?: Logger | null, enableChangeTracking?: boolean); /** * 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; /** * Returns the current working tree (for internal use). * * @returns The working ImmutableTree */ getWorkingTree(): ImmutableTree; /** * Returns the root node of the working tree. * * @returns The root node, or null if tree is empty */ getRoot(): Node | null; /** * Returns the version of the working tree. * * @returns The current version */ getVersion(): bigint; /** * 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; /** * 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; /** * 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; /** * Returns the hash of the current working tree. * * @returns The working tree hash, or null if tree is empty */ getWorkingHash(): Uint8Array | null; /** * Returns the size (number of leaf nodes) in the working tree. * * @returns The tree size */ getSize(): bigint; /** * Gets the NodeDB instance (for internal use by Importer) * @internal */ getNodeDB(): NodeDB; /** * 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 */ versionExists(version: bigint): Promise; /** * 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; /** * 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 */ availableVersions(): Promise; /** * 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 */ get(key: Uint8Array): Promise; /** * 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 */ set(key: Uint8Array, value: Uint8Array): Promise; /** * 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; /** * 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 recursiveSet; /** * 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; /** * 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 */ remove(key: Uint8Array): Promise<{ value: Uint8Array | null; removed: boolean; }>; /** * 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 */ iterate(fn: (key: Uint8Array, value: Uint8Array) => boolean): Promise; /** * 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): TreeIterator; /** * 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): TreeIterator; /** * Helper to add an unsaved fast node removal. * Removes from unsavedFastNodeAdditions if present. * * @param key - The key to mark as removed */ private addUnsavedRemoval; /** * 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 recursiveRemove; /** * 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 rotateRight; /** * 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 rotateLeft; /** * 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 balance; /** * 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 */ saveVersion(): Promise<{ hash: Uint8Array | null; version: bigint; }>; /** * 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 */ saveChangeSet(changeSet: ChangeSet): Promise; /** * 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 */ loadVersion(targetVersion: bigint): Promise; /** * 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 */ loadVersionForOverwriting(targetVersion: bigint): Promise; /** * 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 */ getImmutable(version: bigint): Promise; /** * 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 */ getVersioned(key: Uint8Array, version: bigint): Promise; /** * 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 */ getVersionedProof(key: Uint8Array, version: bigint): Promise; /** * 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; /** * 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 */ deleteVersion(version: bigint): Promise; /** * 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 */ deleteVersionsTo(toVersion: bigint): Promise; /** * 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 */ deleteVersionsFrom(fromVersion: bigint): Promise; /** * 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 enableFastStorageAndCommitIfNotEnabled; /** * 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; /** * Saves fast storage nodes for a version. * @param version - Version number to save fast nodes for */ private saveFastNodeVersion; /** * Saves all unsaved fast node additions to storage. */ private saveFastNodeAdditions; /** * Saves all unsaved fast node removals to storage. */ private saveFastNodeRemovals; /** * Saves all new nodes recursively, assigning node keys. * @param version - Version number for node keys */ private saveNewNodes; /** * 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); * ``` */ import(exporter: AsyncIterableIterator, version: bigint): Promise; /** * 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); * ``` */ importCompressed(exporter: AsyncIterable, version: bigint): Promise; /** * 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 */ traverseStateChanges(startVersion: bigint, endVersion: bigint, fn: (version: bigint, changeSet: ChangeSet) => Promise): Promise; /** * 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; /** * 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; /** * 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; /** * Check if change tracking is enabled. * * @returns True if change tracking is enabled */ isChangeTrackingEnabled(): boolean; /** * 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; /** * Get the number of changes tracked since the last save. * * @returns Number of tracked changes */ getChangeCount(): number; /** * Clear the current change set. * This is automatically called after saveVersion() and rollback(). */ clearChangeSet(): void; /** * Get statistics about the current change tracking. * * @returns Change tracking statistics */ getChangeStats(): { total: number; sets: number; deletes: number; enabled: boolean; maxChanges: number; }; /** * 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; /** * 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 */ applyChangeSet(changeSet: ChangeSet): Promise; /** * Serialize the current change set to protobuf bytes. * Useful for network transmission or storage. * * @returns Serialized change set */ serializeChangeSet(): Uint8Array; } //#endregion export { MutableTree }; //# sourceMappingURL=mutable-tree.d.ts.map