@aztec/merkle-tree 0.23.0 → 0.26.1

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.
@@ -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
+ }
@@ -0,0 +1,215 @@
1
+ import { SiblingPath } from '@aztec/circuit-types';
2
+ import { AztecKVStore, AztecMap } from '@aztec/kv-store';
3
+
4
+ import { TreeBase } from '../tree_base.js';
5
+ import { TreeSnapshot, TreeSnapshotBuilder } from './snapshot_builder.js';
6
+
7
+ /**
8
+ * Metadata for a snapshot, per block
9
+ */
10
+ type SnapshotMetadata = {
11
+ /** The tree root at the time */
12
+ root: Buffer;
13
+ /** The number of filled leaves */
14
+ numLeaves: bigint;
15
+ };
16
+
17
+ /**
18
+ * Builds a full snapshot of a tree. This implementation works for any Merkle tree and stores
19
+ * it in a database in a similar way to how a tree is stored in memory, using pointers.
20
+ *
21
+ * Sharing the same database between versions and trees is recommended as the trees would share
22
+ * structure.
23
+ *
24
+ * Implement the protected method `handleLeaf` to store any additional data you need for each leaf.
25
+ *
26
+ * Complexity:
27
+ * N - count of non-zero nodes in tree
28
+ * M - count of snapshots
29
+ * H - tree height
30
+ * Worst case space complexity: O(N * M)
31
+ * Sibling path access: O(H) database reads
32
+ */
33
+ export abstract class BaseFullTreeSnapshotBuilder<T extends TreeBase, S extends TreeSnapshot>
34
+ implements TreeSnapshotBuilder<S>
35
+ {
36
+ protected nodes: AztecMap<string, [Buffer, Buffer]>;
37
+ protected snapshotMetadata: AztecMap<number, SnapshotMetadata>;
38
+
39
+ constructor(protected db: AztecKVStore, protected tree: T) {
40
+ this.nodes = db.openMap(`full_snapshot:${tree.getName()}:node`);
41
+ this.snapshotMetadata = db.openMap(`full_snapshot:${tree.getName()}:metadata`);
42
+ }
43
+
44
+ snapshot(block: number): Promise<S> {
45
+ return this.db.transaction(() => {
46
+ const snapshotMetadata = this.#getSnapshotMeta(block);
47
+
48
+ if (snapshotMetadata) {
49
+ return this.openSnapshot(snapshotMetadata.root, snapshotMetadata.numLeaves);
50
+ }
51
+
52
+ const root = this.tree.getRoot(false);
53
+ const numLeaves = this.tree.getNumLeaves(false);
54
+ const depth = this.tree.getDepth();
55
+ const queue: [Buffer, number, bigint][] = [[root, 0, 0n]];
56
+
57
+ // walk the tree breadth-first and store each of its nodes in the database
58
+ // for each node we save two keys
59
+ // <node hash>:0 -> <left child's hash>
60
+ // <node hash>:1 -> <right child's hash>
61
+ while (queue.length > 0) {
62
+ const [node, level, i] = queue.shift()!;
63
+ const nodeKey = node.toString('hex');
64
+ // check if the database already has a child for this tree
65
+ // if it does, then we know we've seen the whole subtree below it before
66
+ // and we don't have to traverse it anymore
67
+ // we use the left child here, but it could be anything that shows we've stored the node before
68
+ if (this.nodes.has(nodeKey)) {
69
+ continue;
70
+ }
71
+
72
+ if (level + 1 > depth) {
73
+ // short circuit if we've reached the leaf level
74
+ // otherwise getNode might throw if we ask for the children of a leaf
75
+ this.handleLeaf(i, node);
76
+ continue;
77
+ }
78
+
79
+ const [lhs, rhs] = [this.tree.getNode(level + 1, 2n * i), this.tree.getNode(level + 1, 2n * i + 1n)];
80
+
81
+ // we want the zero hash at the children's level, not the node's level
82
+ const zeroHash = this.tree.getZeroHash(level + 1);
83
+
84
+ void this.nodes.set(nodeKey, [lhs ?? zeroHash, rhs ?? zeroHash]);
85
+ // enqueue the children only if they're not zero hashes
86
+ if (lhs) {
87
+ queue.push([lhs, level + 1, 2n * i]);
88
+ }
89
+
90
+ if (rhs) {
91
+ queue.push([rhs, level + 1, 2n * i + 1n]);
92
+ }
93
+ }
94
+
95
+ void this.snapshotMetadata.set(block, { root, numLeaves });
96
+ return this.openSnapshot(root, numLeaves);
97
+ });
98
+ }
99
+
100
+ protected handleLeaf(_index: bigint, _node: Buffer): void {}
101
+
102
+ getSnapshot(version: number): Promise<S> {
103
+ const snapshotMetadata = this.#getSnapshotMeta(version);
104
+
105
+ if (!snapshotMetadata) {
106
+ return Promise.reject(new Error(`Version ${version} does not exist for tree ${this.tree.getName()}`));
107
+ }
108
+
109
+ return Promise.resolve(this.openSnapshot(snapshotMetadata.root, snapshotMetadata.numLeaves));
110
+ }
111
+
112
+ protected abstract openSnapshot(root: Buffer, numLeaves: bigint): S;
113
+
114
+ #getSnapshotMeta(block: number): SnapshotMetadata | undefined {
115
+ return this.snapshotMetadata.get(block);
116
+ }
117
+ }
118
+
119
+ /**
120
+ * A source of sibling paths from a snapshot tree
121
+ */
122
+ export class BaseFullTreeSnapshot implements TreeSnapshot {
123
+ constructor(
124
+ protected db: AztecMap<string, [Buffer, Buffer]>,
125
+ protected historicRoot: Buffer,
126
+ protected numLeaves: bigint,
127
+ protected tree: TreeBase,
128
+ ) {}
129
+
130
+ getSiblingPath<N extends number>(index: bigint): SiblingPath<N> {
131
+ const siblings: Buffer[] = [];
132
+
133
+ for (const [_node, sibling] of this.pathFromRootToLeaf(index)) {
134
+ siblings.push(sibling);
135
+ }
136
+
137
+ // we got the siblings we were looking for, but they are in root-leaf order
138
+ // reverse them here so we have leaf-root (what SiblingPath expects)
139
+ siblings.reverse();
140
+
141
+ return new SiblingPath<N>(this.tree.getDepth() as N, siblings);
142
+ }
143
+
144
+ getLeafValue(index: bigint): Buffer | undefined {
145
+ let leafNode: Buffer | undefined = undefined;
146
+ for (const [node, _sibling] of this.pathFromRootToLeaf(index)) {
147
+ leafNode = node;
148
+ }
149
+
150
+ return leafNode;
151
+ }
152
+
153
+ getDepth(): number {
154
+ return this.tree.getDepth();
155
+ }
156
+
157
+ getRoot(): Buffer {
158
+ return this.historicRoot;
159
+ }
160
+
161
+ getNumLeaves(): bigint {
162
+ return this.numLeaves;
163
+ }
164
+
165
+ protected *pathFromRootToLeaf(leafIndex: bigint) {
166
+ const root = this.historicRoot;
167
+ const pathFromRoot = this.#getPathFromRoot(leafIndex);
168
+
169
+ let node: Buffer = root;
170
+ for (let i = 0; i < pathFromRoot.length; i++) {
171
+ // get both children. We'll need both anyway (one to keep track of, the other to walk down to)
172
+ const children: [Buffer, Buffer] = this.db.get(node.toString('hex')) ?? [
173
+ this.tree.getZeroHash(i + 1),
174
+ this.tree.getZeroHash(i + 1),
175
+ ];
176
+ const next = children[pathFromRoot[i]];
177
+ const sibling = children[(pathFromRoot[i] + 1) % 2];
178
+
179
+ yield [next, sibling];
180
+
181
+ node = next;
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Calculates the path from the root to the target leaf. Returns an array of 0s and 1s,
187
+ * each 0 represents walking down a left child and each 1 walking down to the child on the right.
188
+ *
189
+ * @param leafIndex - The target leaf
190
+ * @returns An array of 0s and 1s
191
+ */
192
+ #getPathFromRoot(leafIndex: bigint): ReadonlyArray<0 | 1> {
193
+ const path: Array<0 | 1> = [];
194
+ let level = this.tree.getDepth();
195
+ while (level > 0) {
196
+ path.push(leafIndex & 0x01n ? 1 : 0);
197
+ leafIndex >>= 1n;
198
+ level--;
199
+ }
200
+
201
+ path.reverse();
202
+ return path;
203
+ }
204
+
205
+ findLeafIndex(value: Buffer): bigint | undefined {
206
+ const numLeaves = this.getNumLeaves();
207
+ for (let i = 0n; i < numLeaves; i++) {
208
+ const currentValue = this.getLeafValue(i);
209
+ if (currentValue && currentValue.equals(value)) {
210
+ return i;
211
+ }
212
+ }
213
+ return undefined;
214
+ }
215
+ }
@@ -0,0 +1,26 @@
1
+ import { TreeBase } from '../tree_base.js';
2
+ import { BaseFullTreeSnapshot, BaseFullTreeSnapshotBuilder } from './base_full_snapshot.js';
3
+ import { TreeSnapshot, TreeSnapshotBuilder } from './snapshot_builder.js';
4
+
5
+ /**
6
+ * Builds a full snapshot of a tree. This implementation works for any Merkle tree and stores
7
+ * it in a database in a similar way to how a tree is stored in memory, using pointers.
8
+ *
9
+ * Sharing the same database between versions and trees is recommended as the trees would share
10
+ * structure.
11
+ *
12
+ * Complexity:
13
+ * N - count of non-zero nodes in tree
14
+ * M - count of snapshots
15
+ * H - tree height
16
+ * Worst case space complexity: O(N * M)
17
+ * Sibling path access: O(H) database reads
18
+ */
19
+ export class FullTreeSnapshotBuilder
20
+ extends BaseFullTreeSnapshotBuilder<TreeBase, TreeSnapshot>
21
+ implements TreeSnapshotBuilder<TreeSnapshot>
22
+ {
23
+ protected openSnapshot(root: Buffer, numLeaves: bigint): TreeSnapshot {
24
+ return new BaseFullTreeSnapshot(this.nodes, root, numLeaves, this.tree);
25
+ }
26
+ }
@@ -0,0 +1,108 @@
1
+ import { IndexedTreeLeafPreimage } from '@aztec/foundation/trees';
2
+ import { AztecKVStore, AztecMap } from '@aztec/kv-store';
3
+
4
+ import { IndexedTree, PreimageFactory } from '../interfaces/indexed_tree.js';
5
+ import { TreeBase } from '../tree_base.js';
6
+ import { BaseFullTreeSnapshot, BaseFullTreeSnapshotBuilder } from './base_full_snapshot.js';
7
+ import { IndexedTreeSnapshot, TreeSnapshotBuilder } from './snapshot_builder.js';
8
+
9
+ const snapshotLeafValue = (node: Buffer, index: bigint) => 'snapshot:leaf:' + node.toString('hex') + ':' + index;
10
+
11
+ /** a */
12
+ export class IndexedTreeSnapshotBuilder
13
+ extends BaseFullTreeSnapshotBuilder<IndexedTree & TreeBase, IndexedTreeSnapshot>
14
+ implements TreeSnapshotBuilder<IndexedTreeSnapshot>
15
+ {
16
+ leaves: AztecMap<string, Buffer>;
17
+ constructor(store: AztecKVStore, tree: IndexedTree & TreeBase, private leafPreimageBuilder: PreimageFactory) {
18
+ super(store, tree);
19
+ this.leaves = store.openMap('indexed_tree_snapshot:' + tree.getName());
20
+ }
21
+
22
+ protected openSnapshot(root: Buffer, numLeaves: bigint): IndexedTreeSnapshot {
23
+ return new IndexedTreeSnapshotImpl(this.nodes, this.leaves, root, numLeaves, this.tree, this.leafPreimageBuilder);
24
+ }
25
+
26
+ protected handleLeaf(index: bigint, node: Buffer) {
27
+ const leafPreimage = this.tree.getLatestLeafPreimageCopy(index, false);
28
+ if (leafPreimage) {
29
+ void this.leaves.set(snapshotLeafValue(node, index), leafPreimage.toBuffer());
30
+ }
31
+ }
32
+ }
33
+
34
+ /** A snapshot of an indexed tree at a particular point in time */
35
+ class IndexedTreeSnapshotImpl extends BaseFullTreeSnapshot implements IndexedTreeSnapshot {
36
+ constructor(
37
+ db: AztecMap<string, [Buffer, Buffer]>,
38
+ private leaves: AztecMap<string, Buffer>,
39
+ historicRoot: Buffer,
40
+ numLeaves: bigint,
41
+ tree: IndexedTree & TreeBase,
42
+ private leafPreimageBuilder: PreimageFactory,
43
+ ) {
44
+ super(db, historicRoot, numLeaves, tree);
45
+ }
46
+
47
+ getLeafValue(index: bigint): Buffer | undefined {
48
+ const leafPreimage = this.getLatestLeafPreimageCopy(index);
49
+ return leafPreimage?.toBuffer();
50
+ }
51
+
52
+ getLatestLeafPreimageCopy(index: bigint): IndexedTreeLeafPreimage | undefined {
53
+ const leafNode = super.getLeafValue(index);
54
+ const leafValue = this.leaves.get(snapshotLeafValue(leafNode!, index));
55
+ if (leafValue) {
56
+ return this.leafPreimageBuilder.fromBuffer(leafValue);
57
+ } else {
58
+ return undefined;
59
+ }
60
+ }
61
+
62
+ findIndexOfPreviousKey(newValue: bigint): {
63
+ /**
64
+ * The index of the found leaf.
65
+ */
66
+ index: bigint;
67
+ /**
68
+ * A flag indicating if the corresponding leaf's value is equal to `newValue`.
69
+ */
70
+ alreadyPresent: boolean;
71
+ } {
72
+ const numLeaves = this.getNumLeaves();
73
+ const diff: bigint[] = [];
74
+
75
+ for (let i = 0; i < numLeaves; i++) {
76
+ // this is very inefficient
77
+ const storedLeaf = this.getLatestLeafPreimageCopy(BigInt(i))!;
78
+
79
+ // The stored leaf can be undefined if it addresses an empty leaf
80
+ // If the leaf is empty we do the same as if the leaf was larger
81
+ if (storedLeaf === undefined) {
82
+ diff.push(newValue);
83
+ } else if (storedLeaf.getKey() > newValue) {
84
+ diff.push(newValue);
85
+ } else if (storedLeaf.getKey() === newValue) {
86
+ return { index: BigInt(i), alreadyPresent: true };
87
+ } else {
88
+ diff.push(newValue - storedLeaf.getKey());
89
+ }
90
+ }
91
+
92
+ let minIndex = 0;
93
+ for (let i = 1; i < diff.length; i++) {
94
+ if (diff[i] < diff[minIndex]) {
95
+ minIndex = i;
96
+ }
97
+ }
98
+
99
+ return { index: BigInt(minIndex), alreadyPresent: false };
100
+ }
101
+
102
+ findLeafIndex(value: Buffer): bigint | undefined {
103
+ const index = this.tree.findLeafIndex(value, false);
104
+ if (index !== undefined && index < this.getNumLeaves()) {
105
+ return index;
106
+ }
107
+ }
108
+ }
@@ -0,0 +1,84 @@
1
+ import { SiblingPath } from '@aztec/circuit-types';
2
+ import { IndexedTreeLeafPreimage } from '@aztec/foundation/trees';
3
+
4
+ /**
5
+ * An interface for a tree that can record snapshots of its contents.
6
+ */
7
+ export interface TreeSnapshotBuilder<S extends TreeSnapshot = TreeSnapshot> {
8
+ /**
9
+ * Creates a snapshot of the tree at the given version.
10
+ * @param block - The version to snapshot the tree at.
11
+ */
12
+ snapshot(block: number): Promise<S>;
13
+
14
+ /**
15
+ * Returns a snapshot of the tree at the given version.
16
+ * @param block - The version of the snapshot to return.
17
+ */
18
+ getSnapshot(block: number): Promise<S>;
19
+ }
20
+
21
+ /**
22
+ * A tree snapshot
23
+ */
24
+ export interface TreeSnapshot {
25
+ /**
26
+ * Returns the current root of the tree.
27
+ */
28
+ getRoot(): Buffer;
29
+
30
+ /**
31
+ * Returns the number of leaves in the tree.
32
+ */
33
+ getDepth(): number;
34
+
35
+ /**
36
+ * Returns the number of leaves in the tree.
37
+ */
38
+ getNumLeaves(): bigint;
39
+
40
+ /**
41
+ * Returns the value of a leaf at the specified index.
42
+ * @param index - The index of the leaf value to be returned.
43
+ */
44
+ getLeafValue(index: bigint): Buffer | undefined;
45
+
46
+ /**
47
+ * Returns the sibling path for a requested leaf index.
48
+ * @param index - The index of the leaf for which a sibling path is required.
49
+ */
50
+ getSiblingPath<N extends number>(index: bigint): SiblingPath<N>;
51
+
52
+ /**
53
+ * Returns the index of a leaf given its value, or undefined if no leaf with that value is found.
54
+ * @param treeId - The ID of the tree.
55
+ * @param value - The leaf value to look for.
56
+ * @returns The index of the first leaf found with a given value (undefined if not found).
57
+ */
58
+ findLeafIndex(value: Buffer): bigint | undefined;
59
+ }
60
+
61
+ /** A snapshot of an indexed tree */
62
+ export interface IndexedTreeSnapshot extends TreeSnapshot {
63
+ /**
64
+ * Gets the historical data for a leaf
65
+ * @param index - The index of the leaf to get the data for
66
+ */
67
+ getLatestLeafPreimageCopy(index: bigint): IndexedTreeLeafPreimage | undefined;
68
+
69
+ /**
70
+ * Finds the index of the largest leaf whose value is less than or equal to the provided value.
71
+ * @param newValue - The new value to be inserted into the tree.
72
+ * @returns The found leaf index and a flag indicating if the corresponding leaf's value is equal to `newValue`.
73
+ */
74
+ findIndexOfPreviousKey(newValue: bigint): {
75
+ /**
76
+ * The index of the found leaf.
77
+ */
78
+ index: bigint;
79
+ /**
80
+ * A flag indicating if the corresponding leaf's value is equal to `newValue`.
81
+ */
82
+ alreadyPresent: boolean;
83
+ };
84
+ }