@aztec/merkle-tree 0.23.0 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/merkle-tree",
3
- "version": "0.23.0",
3
+ "version": "0.24.0",
4
4
  "type": "module",
5
5
  "exports": "./dest/index.js",
6
6
  "typedocOptions": {
@@ -32,10 +32,10 @@
32
32
  "testTimeout": 15000
33
33
  },
34
34
  "dependencies": {
35
- "@aztec/circuit-types": "0.23.0",
36
- "@aztec/foundation": "0.23.0",
37
- "@aztec/kv-store": "0.23.0",
38
- "@aztec/types": "0.23.0",
35
+ "@aztec/circuit-types": "0.24.0",
36
+ "@aztec/foundation": "0.24.0",
37
+ "@aztec/kv-store": "0.24.0",
38
+ "@aztec/types": "0.24.0",
39
39
  "sha256": "^0.2.0",
40
40
  "tslib": "^2.4.0"
41
41
  },
@@ -0,0 +1,51 @@
1
+ import { Hasher } from '@aztec/types/interfaces';
2
+
3
+ import { createHistogram, performance } from 'perf_hooks';
4
+
5
+ /**
6
+ * A helper class to track stats for a Hasher
7
+ */
8
+ export class HasherWithStats implements Hasher {
9
+ hashCount = 0;
10
+ hashInputsCount = 0;
11
+ hashHistogram = createHistogram();
12
+ hashInputsHistogram = createHistogram();
13
+
14
+ hash: Hasher['hash'];
15
+ hashInputs: Hasher['hashInputs'];
16
+
17
+ constructor(hasher: Hasher) {
18
+ this.hash = performance.timerify(
19
+ (lhs, rhs) => {
20
+ this.hashCount++;
21
+ return hasher.hash(lhs, rhs);
22
+ },
23
+ { histogram: this.hashHistogram },
24
+ );
25
+ this.hashInputs = performance.timerify(
26
+ (inputs: Buffer[]) => {
27
+ this.hashInputsCount++;
28
+ return hasher.hashInputs(inputs);
29
+ },
30
+ { histogram: this.hashInputsHistogram },
31
+ );
32
+ }
33
+
34
+ stats() {
35
+ return {
36
+ hashCount: this.hashCount,
37
+ // timerify records in ns, convert to ms
38
+ hashDuration: this.hashHistogram.mean / 1e6,
39
+ hashInputsCount: this.hashInputsCount,
40
+ hashInputsDuration: this.hashInputsHistogram.mean / 1e6,
41
+ };
42
+ }
43
+
44
+ reset() {
45
+ this.hashCount = 0;
46
+ this.hashHistogram.reset();
47
+
48
+ this.hashInputsCount = 0;
49
+ this.hashInputsHistogram.reset();
50
+ }
51
+ }
package/src/index.ts ADDED
@@ -0,0 +1,15 @@
1
+ export * from './interfaces/append_only_tree.js';
2
+ export * from './interfaces/indexed_tree.js';
3
+ export * from './interfaces/merkle_tree.js';
4
+ export * from './interfaces/update_only_tree.js';
5
+ export * from './pedersen.js';
6
+ export * from './sparse_tree/sparse_tree.js';
7
+ export { StandardIndexedTree } from './standard_indexed_tree/standard_indexed_tree.js';
8
+ export * from './standard_tree/standard_tree.js';
9
+ export { INITIAL_LEAF, getTreeMeta } from './tree_base.js';
10
+ export { newTree } from './new_tree.js';
11
+ export { loadTree } from './load_tree.js';
12
+ export * from './snapshots/snapshot_builder.js';
13
+ export * from './snapshots/full_snapshot.js';
14
+ export * from './snapshots/append_only_snapshot.js';
15
+ export * from './snapshots/indexed_tree_snapshot.js';
@@ -0,0 +1,13 @@
1
+ import { TreeSnapshotBuilder } from '../snapshots/snapshot_builder.js';
2
+ import { MerkleTree } from './merkle_tree.js';
3
+
4
+ /**
5
+ * A Merkle tree that supports only appending leaves and not updating existing leaves.
6
+ */
7
+ export interface AppendOnlyTree extends MerkleTree, TreeSnapshotBuilder {
8
+ /**
9
+ * Appends a set of leaf values to the tree.
10
+ * @param leaves - The set of leaves to be appended.
11
+ */
12
+ appendLeaves(leaves: Buffer[]): Promise<void>;
13
+ }
@@ -0,0 +1,118 @@
1
+ import { SiblingPath } from '@aztec/circuit-types';
2
+ import { IndexedTreeLeaf, IndexedTreeLeafPreimage } from '@aztec/foundation/trees';
3
+
4
+ import { AppendOnlyTree } from './append_only_tree.js';
5
+
6
+ /**
7
+ * Factory for creating leaf preimages.
8
+ */
9
+ export interface PreimageFactory {
10
+ /**
11
+ * Creates a new preimage from a leaf.
12
+ * @param leaf - Leaf to create a preimage from.
13
+ * @param nextKey - Next key of the leaf.
14
+ * @param nextIndex - Next index of the leaf.
15
+ */
16
+ fromLeaf(leaf: IndexedTreeLeaf, nextKey: bigint, nextIndex: bigint): IndexedTreeLeafPreimage;
17
+ /**
18
+ * Creates a new preimage from a buffer.
19
+ * @param buffer - Buffer to create a preimage from.
20
+ */
21
+ fromBuffer(buffer: Buffer): IndexedTreeLeafPreimage;
22
+ /**
23
+ * Creates an empty preimage.
24
+ */
25
+ empty(): IndexedTreeLeafPreimage;
26
+ /**
27
+ * Creates a copy of a preimage.
28
+ * @param preimage - Preimage to be cloned.
29
+ */
30
+ clone(preimage: IndexedTreeLeafPreimage): IndexedTreeLeafPreimage;
31
+ }
32
+
33
+ /**
34
+ * All of the data to be return during batch insertion.
35
+ */
36
+ export interface LowLeafWitnessData<N extends number> {
37
+ /**
38
+ * Preimage of the low nullifier that proves non membership.
39
+ */
40
+ leafPreimage: IndexedTreeLeafPreimage;
41
+ /**
42
+ * Sibling path to prove membership of low nullifier.
43
+ */
44
+ siblingPath: SiblingPath<N>;
45
+ /**
46
+ * The index of low nullifier.
47
+ */
48
+ index: bigint;
49
+ }
50
+
51
+ /**
52
+ * The result of a batch insertion in an indexed merkle tree.
53
+ */
54
+ export interface BatchInsertionResult<TreeHeight extends number, SubtreeSiblingPathHeight extends number> {
55
+ /**
56
+ * Data for the leaves to be updated when inserting the new ones.
57
+ */
58
+ lowLeavesWitnessData?: LowLeafWitnessData<TreeHeight>[];
59
+ /**
60
+ * Sibling path "pointing to" where the new subtree should be inserted into the tree.
61
+ */
62
+ newSubtreeSiblingPath: SiblingPath<SubtreeSiblingPathHeight>;
63
+ /**
64
+ * The new leaves being inserted in high to low order. This order corresponds with the order of the low leaves witness.
65
+ */
66
+ sortedNewLeaves: Buffer[];
67
+ /**
68
+ * The indexes of the sorted new leaves to the original ones.
69
+ */
70
+ sortedNewLeavesIndexes: number[];
71
+ }
72
+
73
+ /**
74
+ * Indexed merkle tree.
75
+ */
76
+ export interface IndexedTree extends AppendOnlyTree {
77
+ /**
78
+ * Finds the index of the largest leaf whose value is less than or equal to the provided value.
79
+ * @param newValue - The new value to be inserted into the tree.
80
+ * @param includeUncommitted - If true, the uncommitted changes are included in the search.
81
+ * @returns The found leaf index and a flag indicating if the corresponding leaf's value is equal to `newValue`.
82
+ */
83
+ findIndexOfPreviousKey(
84
+ newValue: bigint,
85
+ includeUncommitted: boolean,
86
+ ):
87
+ | {
88
+ /**
89
+ * The index of the found leaf.
90
+ */
91
+ index: bigint;
92
+ /**
93
+ * A flag indicating if the corresponding leaf's value is equal to `newValue`.
94
+ */
95
+ alreadyPresent: boolean;
96
+ }
97
+ | undefined;
98
+
99
+ /**
100
+ * Gets the latest LeafPreimage copy.
101
+ * @param index - Index of the leaf of which to obtain the LeafPreimage copy.
102
+ * @param includeUncommitted - If true, the uncommitted changes are included in the search.
103
+ * @returns A copy of the leaf preimage at the given index or undefined if the leaf was not found.
104
+ */
105
+ getLatestLeafPreimageCopy(index: bigint, includeUncommitted: boolean): IndexedTreeLeafPreimage | undefined;
106
+
107
+ /**
108
+ * Batch insert multiple leaves into the tree.
109
+ * @param leaves - Leaves to insert into the tree.
110
+ * @param subtreeHeight - Height of the subtree.
111
+ * @param includeUncommitted - If true, the uncommitted changes are included in the search.
112
+ */
113
+ batchInsert<TreeHeight extends number, SubtreeHeight extends number, SubtreeSiblingPathHeight extends number>(
114
+ leaves: Buffer[],
115
+ subtreeHeight: SubtreeHeight,
116
+ includeUncommitted: boolean,
117
+ ): Promise<BatchInsertionResult<TreeHeight, SubtreeSiblingPathHeight>>;
118
+ }
@@ -0,0 +1,60 @@
1
+ import { SiblingPath } from '@aztec/circuit-types';
2
+
3
+ /**
4
+ * Defines the interface for a source of sibling paths.
5
+ */
6
+ export interface SiblingPathSource {
7
+ /**
8
+ * Returns the sibling path for a requested leaf index.
9
+ * @param index - The index of the leaf for which a sibling path is required.
10
+ * @param includeUncommitted - Set to true to include uncommitted updates in the sibling path.
11
+ */
12
+ getSiblingPath<N extends number>(index: bigint, includeUncommitted: boolean): Promise<SiblingPath<N>>;
13
+ }
14
+
15
+ /**
16
+ * Defines the interface for a Merkle tree.
17
+ */
18
+ export interface MerkleTree extends SiblingPathSource {
19
+ /**
20
+ * Returns the current root of the tree.
21
+ * @param includeUncommitted - Set to true to include uncommitted updates in the calculated root.
22
+ */
23
+ getRoot(includeUncommitted: boolean): Buffer;
24
+
25
+ /**
26
+ * Returns the number of leaves in the tree.
27
+ * @param includeUncommitted - Set to true to include uncommitted updates in the returned value.
28
+ */
29
+ getNumLeaves(includeUncommitted: boolean): bigint;
30
+
31
+ /**
32
+ * Commit pending updates to the tree.
33
+ */
34
+ commit(): Promise<void>;
35
+
36
+ /**
37
+ * Returns the depth of the tree.
38
+ */
39
+ getDepth(): number;
40
+
41
+ /**
42
+ * Rollback pending update to the tree.
43
+ */
44
+ rollback(): Promise<void>;
45
+
46
+ /**
47
+ * Returns the value of a leaf at the specified index.
48
+ * @param index - The index of the leaf value to be returned.
49
+ * @param includeUncommitted - Set to true to include uncommitted updates in the data set.
50
+ */
51
+ getLeafValue(index: bigint, includeUncommitted: boolean): Buffer | undefined;
52
+
53
+ /**
54
+ * Returns the index of a leaf given its value, or undefined if no leaf with that value is found.
55
+ * @param leaf - The leaf value to look for.
56
+ * @param includeUncommitted - Indicates whether to include uncommitted data.
57
+ * @returns The index of the first leaf found with a given value (undefined if not found).
58
+ */
59
+ findLeafIndex(leaf: Buffer, includeUncommitted: boolean): bigint | undefined;
60
+ }
@@ -0,0 +1,14 @@
1
+ import { TreeSnapshotBuilder } from '../snapshots/snapshot_builder.js';
2
+ import { MerkleTree } from './merkle_tree.js';
3
+
4
+ /**
5
+ * A Merkle tree that supports updates at arbitrary indices but not appending.
6
+ */
7
+ export interface UpdateOnlyTree extends MerkleTree, TreeSnapshotBuilder {
8
+ /**
9
+ * Updates a leaf at a given index in the tree.
10
+ * @param leaf - The leaf value to be updated.
11
+ * @param index - The leaf to be updated.
12
+ */
13
+ updateLeaf(leaf: Buffer, index: bigint): Promise<void>;
14
+ }
@@ -0,0 +1,23 @@
1
+ import { AztecKVStore } from '@aztec/kv-store';
2
+ import { Hasher } from '@aztec/types/interfaces';
3
+
4
+ import { TreeBase, getTreeMeta } from './tree_base.js';
5
+
6
+ /**
7
+ * Creates a new tree and sets its root, depth and size based on the meta data which are associated with the name.
8
+ * @param c - The class of the tree to be instantiated.
9
+ * @param db - A database used to store the Merkle tree data.
10
+ * @param hasher - A hasher used to compute hash paths.
11
+ * @param name - Name of the tree.
12
+ * @returns The newly created tree.
13
+ */
14
+ export function loadTree<T extends TreeBase>(
15
+ c: new (store: AztecKVStore, hasher: Hasher, name: string, depth: number, size: bigint, root: Buffer) => T,
16
+ store: AztecKVStore,
17
+ hasher: Hasher,
18
+ name: string,
19
+ ): Promise<T> {
20
+ const { root, depth, size } = getTreeMeta(store, name);
21
+ const tree = new c(store, hasher, name, depth, size, root);
22
+ return Promise.resolve(tree);
23
+ }
@@ -0,0 +1,27 @@
1
+ import { AztecKVStore } from '@aztec/kv-store';
2
+ import { Hasher } from '@aztec/types/interfaces';
3
+
4
+ import { TreeBase } from './tree_base.js';
5
+
6
+ /**
7
+ * Creates a new tree.
8
+ * @param c - The class of the tree to be instantiated.
9
+ * @param db - A database used to store the Merkle tree data.
10
+ * @param hasher - A hasher used to compute hash paths.
11
+ * @param name - Name of the tree.
12
+ * @param depth - Depth of the tree.
13
+ * @param prefilledSize - A number of leaves that are prefilled with values.
14
+ * @returns The newly created tree.
15
+ */
16
+ export async function newTree<T extends TreeBase>(
17
+ c: new (store: AztecKVStore, hasher: Hasher, name: string, depth: number, size: bigint) => T,
18
+ store: AztecKVStore,
19
+ hasher: Hasher,
20
+ name: string,
21
+ depth: number,
22
+ prefilledSize = 1,
23
+ ): Promise<T> {
24
+ const tree = new c(store, hasher, name, depth, 0n);
25
+ await tree.init(prefilledSize);
26
+ return tree;
27
+ }
@@ -0,0 +1,25 @@
1
+ import { pedersenHash } from '@aztec/foundation/crypto';
2
+ import { Hasher } from '@aztec/types/interfaces';
3
+
4
+ /**
5
+ * A helper class encapsulating Pedersen hash functionality.
6
+ * @deprecated Don't call pedersen directly in production code. Instead, create suitably-named functions for specific
7
+ * purposes.
8
+ */
9
+ export class Pedersen implements Hasher {
10
+ /*
11
+ * @deprecated Don't call pedersen directly in production code. Instead, create suitably-named functions for specific
12
+ * purposes.
13
+ */
14
+ public hash(lhs: Uint8Array, rhs: Uint8Array): Buffer {
15
+ return pedersenHash([Buffer.from(lhs), Buffer.from(rhs)]);
16
+ }
17
+
18
+ /*
19
+ * @deprecated Don't call pedersen directly in production code. Instead, create suitably-named functions for specific
20
+ * purposes.
21
+ */
22
+ public hashInputs(inputs: Buffer[]): Buffer {
23
+ return pedersenHash(inputs);
24
+ }
25
+ }
@@ -0,0 +1,262 @@
1
+ import { SiblingPath } from '@aztec/circuit-types';
2
+ import { AztecKVStore, AztecMap } from '@aztec/kv-store';
3
+ import { Hasher } from '@aztec/types/interfaces';
4
+
5
+ import { AppendOnlyTree } from '../interfaces/append_only_tree.js';
6
+ import { TreeBase } from '../tree_base.js';
7
+ import { TreeSnapshot, TreeSnapshotBuilder } from './snapshot_builder.js';
8
+
9
+ // stores the last block that modified this node
10
+ const nodeModifiedAtBlockKey = (level: number, index: bigint) => `node:${level}:${index}:modifiedAtBlock`;
11
+
12
+ // stores the value of the node at the above block
13
+ const historicalNodeKey = (level: number, index: bigint) => `node:${level}:${index}:value`;
14
+
15
+ /**
16
+ * Metadata for a snapshot, per block
17
+ */
18
+ type SnapshotMetadata = {
19
+ /** The tree root at the time */
20
+ root: Buffer;
21
+ /** The number of filled leaves */
22
+ numLeaves: bigint;
23
+ };
24
+
25
+ /**
26
+ * A more space-efficient way of storing snapshots of AppendOnlyTrees that trades space need for slower
27
+ * sibling path reads.
28
+ *
29
+ * Complexity:
30
+ *
31
+ * N - count of non-zero nodes in tree
32
+ * M - count of snapshots
33
+ * H - tree height
34
+ *
35
+ * Space complexity: O(N + M) (N nodes - stores the last snapshot for each node and M - ints, for each snapshot stores up to which leaf its written to)
36
+ * Sibling path access:
37
+ * Best case: O(H) database reads + O(1) hashes
38
+ * Worst case: O(H) database reads + O(H) hashes
39
+ */
40
+ export class AppendOnlySnapshotBuilder implements TreeSnapshotBuilder {
41
+ #nodeValue: AztecMap<ReturnType<typeof historicalNodeKey>, Buffer>;
42
+ #nodeLastModifiedByBlock: AztecMap<ReturnType<typeof nodeModifiedAtBlockKey>, number>;
43
+ #snapshotMetadata: AztecMap<number, SnapshotMetadata>;
44
+
45
+ constructor(private db: AztecKVStore, private tree: TreeBase & AppendOnlyTree, private hasher: Hasher) {
46
+ const treeName = tree.getName();
47
+ this.#nodeValue = db.openMap(`append_only_snapshot:${treeName}:node`);
48
+ this.#nodeLastModifiedByBlock = db.openMap(`append_ony_snapshot:${treeName}:block`);
49
+ this.#snapshotMetadata = db.openMap(`append_only_snapshot:${treeName}:snapshot_metadata`);
50
+ }
51
+
52
+ getSnapshot(block: number): Promise<TreeSnapshot> {
53
+ const meta = this.#getSnapshotMeta(block);
54
+
55
+ if (typeof meta === 'undefined') {
56
+ return Promise.reject(new Error(`Snapshot for tree ${this.tree.getName()} at block ${block} does not exist`));
57
+ }
58
+
59
+ return Promise.resolve(
60
+ new AppendOnlySnapshot(
61
+ this.#nodeValue,
62
+ this.#nodeLastModifiedByBlock,
63
+ block,
64
+ meta.numLeaves,
65
+ meta.root,
66
+ this.tree,
67
+ this.hasher,
68
+ ),
69
+ );
70
+ }
71
+
72
+ snapshot(block: number): Promise<TreeSnapshot> {
73
+ return this.db.transaction(() => {
74
+ const meta = this.#getSnapshotMeta(block);
75
+ if (typeof meta !== 'undefined') {
76
+ // no-op, we already have a snapshot
77
+ return new AppendOnlySnapshot(
78
+ this.#nodeValue,
79
+ this.#nodeLastModifiedByBlock,
80
+ block,
81
+ meta.numLeaves,
82
+ meta.root,
83
+ this.tree,
84
+ this.hasher,
85
+ );
86
+ }
87
+
88
+ const root = this.tree.getRoot(false);
89
+ const depth = this.tree.getDepth();
90
+ const queue: [Buffer, number, bigint][] = [[root, 0, 0n]];
91
+
92
+ // walk the tree in BF and store latest nodes
93
+ while (queue.length > 0) {
94
+ const [node, level, index] = queue.shift()!;
95
+
96
+ const historicalValue = this.#nodeValue.get(historicalNodeKey(level, index));
97
+ if (!historicalValue || !node.equals(historicalValue)) {
98
+ // we've never seen this node before or it's different than before
99
+ // update the historical tree and tag it with the block that modified it
100
+ void this.#nodeLastModifiedByBlock.set(nodeModifiedAtBlockKey(level, index), block);
101
+ void this.#nodeValue.set(historicalNodeKey(level, index), node);
102
+ } else {
103
+ // if this node hasn't changed, that means, nothing below it has changed either
104
+ continue;
105
+ }
106
+
107
+ if (level + 1 > depth) {
108
+ // short circuit if we've reached the leaf level
109
+ // otherwise getNode might throw if we ask for the children of a leaf
110
+ continue;
111
+ }
112
+
113
+ // these could be undefined because zero hashes aren't stored in the tree
114
+ const [lhs, rhs] = [this.tree.getNode(level + 1, 2n * index), this.tree.getNode(level + 1, 2n * index + 1n)];
115
+
116
+ if (lhs) {
117
+ queue.push([lhs, level + 1, 2n * index]);
118
+ }
119
+
120
+ if (rhs) {
121
+ queue.push([rhs, level + 1, 2n * index + 1n]);
122
+ }
123
+ }
124
+
125
+ const numLeaves = this.tree.getNumLeaves(false);
126
+ void this.#snapshotMetadata.set(block, {
127
+ numLeaves,
128
+ root,
129
+ });
130
+
131
+ return new AppendOnlySnapshot(
132
+ this.#nodeValue,
133
+ this.#nodeLastModifiedByBlock,
134
+ block,
135
+ numLeaves,
136
+ root,
137
+ this.tree,
138
+ this.hasher,
139
+ );
140
+ });
141
+ }
142
+
143
+ #getSnapshotMeta(block: number): SnapshotMetadata | undefined {
144
+ return this.#snapshotMetadata.get(block);
145
+ }
146
+ }
147
+
148
+ /**
149
+ * a
150
+ */
151
+ class AppendOnlySnapshot implements TreeSnapshot {
152
+ constructor(
153
+ private nodes: AztecMap<string, Buffer>,
154
+ private nodeHistory: AztecMap<string, number>,
155
+ private block: number,
156
+ private leafCount: bigint,
157
+ private historicalRoot: Buffer,
158
+ private tree: TreeBase & AppendOnlyTree,
159
+ private hasher: Hasher,
160
+ ) {}
161
+
162
+ public getSiblingPath<N extends number>(index: bigint): SiblingPath<N> {
163
+ const path: Buffer[] = [];
164
+ const depth = this.tree.getDepth();
165
+ let level = depth;
166
+
167
+ while (level > 0) {
168
+ const isRight = index & 0x01n;
169
+ const siblingIndex = isRight ? index - 1n : index + 1n;
170
+
171
+ const sibling = this.#getHistoricalNodeValue(level, siblingIndex);
172
+ path.push(sibling);
173
+
174
+ level -= 1;
175
+ index >>= 1n;
176
+ }
177
+
178
+ return new SiblingPath<N>(depth as N, path);
179
+ }
180
+
181
+ getDepth(): number {
182
+ return this.tree.getDepth();
183
+ }
184
+
185
+ getNumLeaves(): bigint {
186
+ return this.leafCount;
187
+ }
188
+
189
+ getRoot(): Buffer {
190
+ // we could recompute it, but it's way cheaper to just store the root
191
+ return this.historicalRoot;
192
+ }
193
+
194
+ getLeafValue(index: bigint): Buffer | undefined {
195
+ const leafLevel = this.getDepth();
196
+ const blockNumber = this.#getBlockNumberThatModifiedNode(leafLevel, index);
197
+
198
+ // leaf hasn't been set yet
199
+ if (typeof blockNumber === 'undefined') {
200
+ return undefined;
201
+ }
202
+
203
+ // leaf was set some time in the past
204
+ if (blockNumber <= this.block) {
205
+ return this.nodes.get(historicalNodeKey(leafLevel, index));
206
+ }
207
+
208
+ // leaf has been set but in a block in the future
209
+ return undefined;
210
+ }
211
+
212
+ #getHistoricalNodeValue(level: number, index: bigint): Buffer {
213
+ const blockNumber = this.#getBlockNumberThatModifiedNode(level, index);
214
+
215
+ // node has never been set
216
+ if (typeof blockNumber === 'undefined') {
217
+ return this.tree.getZeroHash(level);
218
+ }
219
+
220
+ // node was set some time in the past
221
+ if (blockNumber <= this.block) {
222
+ return this.nodes.get(historicalNodeKey(level, index))!;
223
+ }
224
+
225
+ // the node has been modified since this snapshot was taken
226
+ // because we're working with an AppendOnly tree, historical leaves never change
227
+ // so what we do instead is rebuild this Merkle path up using zero hashes as needed
228
+ // worst case this will do O(H) hashes
229
+ //
230
+ // we first check if this subtree was touched by the block
231
+ // compare how many leaves this block added to the leaf interval of this subtree
232
+ // if they don't intersect then the whole subtree was a hash of zero
233
+ // if they do then we need to rebuild the merkle tree
234
+ const depth = this.tree.getDepth();
235
+ const leafStart = index * 2n ** BigInt(depth - level);
236
+ if (leafStart >= this.leafCount) {
237
+ return this.tree.getZeroHash(level);
238
+ }
239
+
240
+ const [lhs, rhs] = [
241
+ this.#getHistoricalNodeValue(level + 1, 2n * index),
242
+ this.#getHistoricalNodeValue(level + 1, 2n * index + 1n),
243
+ ];
244
+
245
+ return this.hasher.hash(lhs, rhs);
246
+ }
247
+
248
+ #getBlockNumberThatModifiedNode(level: number, index: bigint): number | undefined {
249
+ return this.nodeHistory.get(nodeModifiedAtBlockKey(level, index));
250
+ }
251
+
252
+ findLeafIndex(value: Buffer): bigint | undefined {
253
+ const numLeaves = this.getNumLeaves();
254
+ for (let i = 0n; i < numLeaves; i++) {
255
+ const currentValue = this.getLeafValue(i);
256
+ if (currentValue && currentValue.equals(value)) {
257
+ return i;
258
+ }
259
+ }
260
+ return undefined;
261
+ }
262
+ }