This repository was archived by the owner on Oct 21, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Remove Smt class lock #97
Closed
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,140 +1,59 @@ | ||
| import { DataHash } from '@unicitylabs/commons/lib/hash/DataHash.js'; | ||
| import { LeafInBranchError } from '@unicitylabs/commons/lib/smt/LeafInBranchError.js'; | ||
| import { MerkleTreePath } from '@unicitylabs/commons/lib/smt/MerkleTreePath.js'; | ||
| import { MerkleTreeRootNode } from '@unicitylabs/commons/lib/smt/MerkleTreeRootNode.js'; | ||
| import { SparseMerkleTree } from '@unicitylabs/commons/lib/smt/SparseMerkleTree.js'; | ||
|
|
||
| import logger from '../logger.js'; | ||
|
|
||
|
|
||
| /** | ||
| * Wrapper for SparseMerkleTree that provides concurrency control | ||
| * using a locking mechanism to ensure sequential execution of | ||
| * asynchronous operations. | ||
| */ | ||
| export class Smt { | ||
| private smtUpdateLock: boolean = false; | ||
| private waitingPromises: Array<{ | ||
| resolve: () => void; | ||
| reject: (error: Error) => void; | ||
| timer: NodeJS.Timeout; | ||
| }> = []; | ||
|
|
||
| // Lock timeout in milliseconds (10 seconds) | ||
| private readonly LOCK_TIMEOUT_MS = 10000; | ||
|
|
||
| /** | ||
| * Creates a new SMT wrapper | ||
| * @param smt The SparseMerkleTree to wrap | ||
| * @param _root SparseMerkleTreeRoot representing the current state of the tree | ||
| */ | ||
| private constructor( | ||
| private readonly smt: SparseMerkleTree, | ||
| private _root: MerkleTreeRootNode, | ||
| ) {} | ||
| public constructor(private readonly smt: SparseMerkleTree) {} | ||
|
|
||
| /** | ||
| * Gets the root hash of the tree | ||
| */ | ||
| public get rootHash(): DataHash { | ||
| return this._root.hash; | ||
| } | ||
|
|
||
| public static async create(smt: SparseMerkleTree): Promise<Smt> { | ||
| return new Smt(smt, await smt.calculateRoot()); | ||
| public async rootHash(): Promise<DataHash> { | ||
| const root = await this.smt.calculateRoot(); | ||
| return root.hash; | ||
| } | ||
|
|
||
| /** | ||
| * Adds a leaf to the SMT with locking to prevent concurrent updates | ||
| */ | ||
| public addLeaf(path: bigint, value: Uint8Array): Promise<void> { | ||
|
martti007 marked this conversation as resolved.
|
||
| return this.withSmtLock(async () => { | ||
| await this.smt.addLeaf(path, value); | ||
| this._root = await this.smt.calculateRoot(); | ||
| }); | ||
| return this.smt.addLeaf(path, value); | ||
|
martti007 marked this conversation as resolved.
|
||
| } | ||
|
|
||
| /** | ||
| * Gets a proof path for a leaf with locking to ensure consistent view | ||
| */ | ||
| public getPath(path: bigint): MerkleTreePath { | ||
| return this._root.getPath(path); | ||
| public async getPath(path: bigint): Promise<MerkleTreePath> { | ||
|
martti007 marked this conversation as resolved.
|
||
| const root = await this.smt.calculateRoot(); | ||
| return root.getPath(path); | ||
| } | ||
|
martti007 marked this conversation as resolved.
|
||
|
|
||
| /** | ||
| * Adds multiple leaves atomically with a single lock | ||
| */ | ||
| public addLeaves(leaves: Array<{ path: bigint; value: Uint8Array }>): Promise<void> { | ||
| return this.withSmtLock(async () => { | ||
| await Promise.all( | ||
| leaves.map((leaf) => | ||
| this.smt.addLeaf(leaf.path, leaf.value).catch((error) => { | ||
| if (error instanceof LeafInBranchError) { | ||
| logger.warn(`Leaf already exists in tree for path ${leaf.path} - skipping`); | ||
| } else { | ||
| throw error; | ||
| } | ||
| }), | ||
| ), | ||
| ); | ||
|
|
||
| this._root = await this.smt.calculateRoot(); | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Acquires a lock for SMT updates with a timeout | ||
| * @returns A promise that resolves when the lock is acquired | ||
| */ | ||
| private acquireSmtLock(): Promise<void> { | ||
| if (!this.smtUpdateLock) { | ||
| this.smtUpdateLock = true; | ||
| return Promise.resolve(); | ||
| } | ||
|
|
||
| return new Promise<void>((resolve, reject) => { | ||
| // Create a timeout that will reject the promise if the lock isn't acquired in time | ||
| const timer = setTimeout(() => { | ||
| // Remove this waiting promise from the queue | ||
| const index = this.waitingPromises.findIndex((p) => p.timer === timer); | ||
| if (index !== -1) { | ||
| this.waitingPromises.splice(index, 1); | ||
| } | ||
|
|
||
| reject(new Error(`SMT lock acquisition timed out after ${this.LOCK_TIMEOUT_MS}ms`)); | ||
| }, this.LOCK_TIMEOUT_MS); | ||
|
|
||
| this.waitingPromises.push({ resolve, reject, timer }); | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Releases the SMT update lock and resolves the next waiting promise | ||
| */ | ||
| private releaseSmtLock(): void { | ||
| if (this.waitingPromises.length > 0) { | ||
| const next = this.waitingPromises.shift(); | ||
| // Clear the timeout since we're resolving this promise | ||
| if (next) { | ||
| clearTimeout(next.timer); | ||
| next.resolve(); | ||
| } | ||
| } else { | ||
| this.smtUpdateLock = false; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Executes a function while holding the SMT lock | ||
| * @param fn The function to execute with the lock held | ||
| * @returns The result of the function | ||
| */ | ||
| public async withSmtLock<T>(fn: () => Promise<T>): Promise<T> { | ||
| await this.acquireSmtLock(); | ||
| try { | ||
| return await fn(); | ||
| } finally { | ||
| this.releaseSmtLock(); | ||
| } | ||
| public async addLeaves(leaves: Array<{ path: bigint; value: Uint8Array }>): Promise<void> { | ||
|
martti007 marked this conversation as resolved.
|
||
| await Promise.all( | ||
| leaves.map((leaf) => | ||
| this.smt.addLeaf(leaf.path, leaf.value).catch((error) => { | ||
| if (error instanceof LeafInBranchError) { | ||
| logger.warn(`Leaf already exists in tree for path ${leaf.path} - skipping`); | ||
| } else { | ||
| throw error; | ||
| } | ||
| }), | ||
| ), | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.