Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cache completed subtrees #4276

Merged
merged 1 commit into from
May 19, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions packages/utils/src/helpers/merkle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,14 +136,18 @@ export class SparseMerkleTree {
// Get the subtree down the opposite path of the one to the target.
const nodes = await this.getSubtreeNodes(depth + 1, siblingPath);

// TODO: @jakek verify that removing this check doesn't break anything.
// Sanity check: nodes were returned (if not, then our starting depth was likely incorrect).
// if (!nodes.length) {
// throw new Error("No nodes...?");
// }

// The sibling at this depth will be the root of that subtree.
siblings[depth] = this.getSubtreeRoot(depth + 1, nodes);
// Use cached root for path if available
const cachedRoot = await this.db.getRoot(siblingPath);
if (cachedRoot) {
siblings[depth] = cachedRoot;
} else {
// The sibling at this depth will be the root of that subtree.
siblings[depth] = this.getSubtreeRoot(depth + 1, nodes);

// Cache the subtree in the DB once we have solved for root.
const expectedNodeCount = 2 ** (this.height - (depth + 1));
if (expectedNodeCount - nodes.length === 0) await this.db.putRoot(siblingPath, siblings[depth]);
}
}

// Get the last sibling node.
Expand Down Expand Up @@ -201,9 +205,6 @@ export class SparseMerkleTree {

// Get root from (sub)array of base layer nodes
private getSubtreeRoot(depth: number, nodes: string[]): string {
// TODO: Check to see if we have the given subtree cached!
// const cached = await this.db.getSubtreeRoot()

// TODO: There's probably a faster way to fill out empty subtrees... i.e. using KNOWN zero hashes.
// Determine the expected number of nodes in this subtree given the current depth.
// At a depth of 0, this should be the whole tree (e.g. for a tree of 16-depth: 65,536 nodes).
Expand Down Expand Up @@ -248,7 +249,6 @@ export class SparseMerkleTree {
}

return roots[0];
// TODO: Cache the subtree in the DB once we have solved for root.
}

private async getStartingDepth(_count?: number): Promise<number> {
Expand Down