@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.
@@ -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
+ }
@@ -0,0 +1,218 @@
1
+ import { TreeBase } from '../tree_base.js';
2
+ import { TreeSnapshotBuilder } from './snapshot_builder.js';
3
+
4
+ /** Creates a test suit for snapshots */
5
+ export function describeSnapshotBuilderTestSuite<T extends TreeBase, S extends TreeSnapshotBuilder>(
6
+ getTree: () => T,
7
+ getSnapshotBuilder: () => S,
8
+ modifyTree: (tree: T) => Promise<void>,
9
+ ) {
10
+ describe('SnapshotBuilder', () => {
11
+ let tree: T;
12
+ let snapshotBuilder: S;
13
+ let leaves: bigint[];
14
+
15
+ beforeEach(() => {
16
+ tree = getTree();
17
+ snapshotBuilder = getSnapshotBuilder();
18
+
19
+ leaves = Array.from({ length: 4 }).map(() => BigInt(Math.floor(Math.random() * 2 ** tree.getDepth())));
20
+ });
21
+
22
+ describe('snapshot', () => {
23
+ it('takes snapshots', async () => {
24
+ await modifyTree(tree);
25
+ await tree.commit();
26
+ await expect(snapshotBuilder.snapshot(1)).resolves.toBeDefined();
27
+ });
28
+
29
+ it('is idempotent', async () => {
30
+ await modifyTree(tree);
31
+ await tree.commit();
32
+
33
+ const block = 1;
34
+ const snapshot = await snapshotBuilder.snapshot(block);
35
+ await expect(snapshotBuilder.snapshot(block)).resolves.toEqual(snapshot);
36
+ });
37
+
38
+ it('returns the same path if tree has not diverged', async () => {
39
+ await modifyTree(tree);
40
+ await tree.commit();
41
+ const snapshot = await snapshotBuilder.snapshot(1);
42
+
43
+ const historicPaths = await Promise.all(leaves.map(leaf => snapshot.getSiblingPath(leaf)));
44
+ const expectedPaths = await Promise.all(leaves.map(leaf => tree.getSiblingPath(leaf, false)));
45
+
46
+ for (const [index, path] of historicPaths.entries()) {
47
+ expect(path).toEqual(expectedPaths[index]);
48
+ }
49
+ });
50
+
51
+ it('returns historic paths if tree has diverged and no new snapshots have been taken', async () => {
52
+ await modifyTree(tree);
53
+ await tree.commit();
54
+ const snapshot = await snapshotBuilder.snapshot(1);
55
+
56
+ const expectedPaths = await Promise.all(leaves.map(leaf => tree.getSiblingPath(leaf, false)));
57
+
58
+ await modifyTree(tree);
59
+ await tree.commit();
60
+
61
+ const historicPaths = await Promise.all(leaves.map(leaf => snapshot.getSiblingPath(leaf)));
62
+
63
+ for (const [index, path] of historicPaths.entries()) {
64
+ expect(path).toEqual(expectedPaths[index]);
65
+ }
66
+ });
67
+
68
+ it('retains old snapshots even if new one are created', async () => {
69
+ await modifyTree(tree);
70
+ await tree.commit();
71
+
72
+ const expectedPaths = await Promise.all(leaves.map(leaf => tree.getSiblingPath(leaf, false)));
73
+
74
+ const snapshot = await snapshotBuilder.snapshot(1);
75
+
76
+ await modifyTree(tree);
77
+ await tree.commit();
78
+
79
+ await snapshotBuilder.snapshot(2);
80
+
81
+ // check that snapshot 2 has not influenced snapshot(1) at all
82
+ const historicPaths = await Promise.all(leaves.map(leaf => snapshot.getSiblingPath(leaf)));
83
+
84
+ for (const [index, path] of historicPaths.entries()) {
85
+ expect(path).toEqual(expectedPaths[index]);
86
+ }
87
+ });
88
+
89
+ it('retains old snapshots even if new one are created and the tree diverges', async () => {
90
+ await modifyTree(tree);
91
+ await tree.commit();
92
+
93
+ const expectedPaths = await Promise.all(leaves.map(leaf => tree.getSiblingPath(leaf, false)));
94
+
95
+ const snapshot = await snapshotBuilder.snapshot(1);
96
+
97
+ await modifyTree(tree);
98
+ await tree.commit();
99
+
100
+ await snapshotBuilder.snapshot(2);
101
+
102
+ await modifyTree(tree);
103
+ await tree.commit();
104
+
105
+ // check that snapshot 2 has not influenced snapshot(1) at all
106
+ // and that the diverging tree does not influence the old snapshot
107
+ const historicPaths = await Promise.all(leaves.map(leaf => snapshot.getSiblingPath(leaf)));
108
+
109
+ for (const [index, path] of historicPaths.entries()) {
110
+ expect(path).toEqual(expectedPaths[index]);
111
+ }
112
+ });
113
+ });
114
+
115
+ describe('getSnapshot', () => {
116
+ it('returns old snapshots', async () => {
117
+ await modifyTree(tree);
118
+ await tree.commit();
119
+ const expectedPaths = await Promise.all(leaves.map(leaf => tree.getSiblingPath(leaf, false)));
120
+ await snapshotBuilder.snapshot(1);
121
+
122
+ for (let i = 2; i < 5; i++) {
123
+ await modifyTree(tree);
124
+ await tree.commit();
125
+ await snapshotBuilder.snapshot(i);
126
+ }
127
+
128
+ const firstSnapshot = await snapshotBuilder.getSnapshot(1);
129
+ const historicPaths = await Promise.all(leaves.map(leaf => firstSnapshot.getSiblingPath(leaf)));
130
+
131
+ for (const [index, path] of historicPaths.entries()) {
132
+ expect(path).toEqual(expectedPaths[index]);
133
+ }
134
+ });
135
+
136
+ it('throws if an unknown snapshot is requested', async () => {
137
+ await modifyTree(tree);
138
+ await tree.commit();
139
+ await snapshotBuilder.snapshot(1);
140
+
141
+ await expect(snapshotBuilder.getSnapshot(2)).rejects.toThrow();
142
+ });
143
+ });
144
+
145
+ describe('getRoot', () => {
146
+ it('returns the historical root of the tree when the snapshot was taken', async () => {
147
+ await modifyTree(tree);
148
+ await tree.commit();
149
+ const snapshot = await snapshotBuilder.snapshot(1);
150
+ const historicalRoot = tree.getRoot(false);
151
+
152
+ await modifyTree(tree);
153
+ await tree.commit();
154
+
155
+ expect(snapshot.getRoot()).toEqual(historicalRoot);
156
+ expect(snapshot.getRoot()).not.toEqual(tree.getRoot(false));
157
+ });
158
+ });
159
+
160
+ describe('getDepth', () => {
161
+ it('returns the same depth as the tree', async () => {
162
+ await modifyTree(tree);
163
+ await tree.commit();
164
+ const snapshot = await snapshotBuilder.snapshot(1);
165
+ expect(snapshot.getDepth()).toEqual(tree.getDepth());
166
+ });
167
+ });
168
+
169
+ describe('getNumLeaves', () => {
170
+ it('returns the historical leaves count when the snapshot was taken', async () => {
171
+ await modifyTree(tree);
172
+ await tree.commit();
173
+ const snapshot = await snapshotBuilder.snapshot(1);
174
+ const historicalNumLeaves = tree.getNumLeaves(false);
175
+
176
+ await modifyTree(tree);
177
+ await tree.commit();
178
+
179
+ expect(snapshot.getNumLeaves()).toEqual(historicalNumLeaves);
180
+ });
181
+ });
182
+
183
+ describe('getLeafValue', () => {
184
+ it('returns the historical leaf value when the snapshot was taken', async () => {
185
+ await modifyTree(tree);
186
+ await tree.commit();
187
+ const snapshot = await snapshotBuilder.snapshot(1);
188
+ const historicalLeafValue = tree.getLeafValue(0n, false);
189
+ expect(snapshot.getLeafValue(0n)).toEqual(historicalLeafValue);
190
+
191
+ await modifyTree(tree);
192
+ await tree.commit();
193
+
194
+ expect(snapshot.getLeafValue(0n)).toEqual(historicalLeafValue);
195
+ });
196
+ });
197
+
198
+ describe('findLeafIndex', () => {
199
+ it('returns the historical leaf index when the snapshot was taken', async () => {
200
+ await modifyTree(tree);
201
+ await tree.commit();
202
+ const snapshot = await snapshotBuilder.snapshot(1);
203
+
204
+ const initialLastLeafIndex = tree.getNumLeaves(false) - 1n;
205
+ let lastLeaf = tree.getLeafValue(initialLastLeafIndex, false);
206
+ expect(snapshot.findLeafIndex(lastLeaf!)).toBe(initialLastLeafIndex);
207
+
208
+ await modifyTree(tree);
209
+ await tree.commit();
210
+
211
+ const newLastLeafIndex = tree.getNumLeaves(false) - 1n;
212
+ lastLeaf = tree.getLeafValue(newLastLeafIndex, false);
213
+
214
+ expect(snapshot.findLeafIndex(lastLeaf!)).toBe(undefined);
215
+ });
216
+ });
217
+ });
218
+ }
@@ -0,0 +1,49 @@
1
+ import { UpdateOnlyTree } from '../interfaces/update_only_tree.js';
2
+ import { FullTreeSnapshotBuilder } from '../snapshots/full_snapshot.js';
3
+ import { TreeSnapshot } from '../snapshots/snapshot_builder.js';
4
+ import { INITIAL_LEAF, TreeBase } from '../tree_base.js';
5
+
6
+ /**
7
+ * A Merkle tree implementation that uses a LevelDB database to store the tree.
8
+ */
9
+ export class SparseTree extends TreeBase implements UpdateOnlyTree {
10
+ #snapshotBuilder = new FullTreeSnapshotBuilder(this.store, this);
11
+ /**
12
+ * Updates a leaf in the tree.
13
+ * @param leaf - New contents of the leaf.
14
+ * @param index - Index of the leaf to be updated.
15
+ */
16
+ public updateLeaf(leaf: Buffer, index: bigint): Promise<void> {
17
+ if (index > this.maxIndex) {
18
+ throw Error(`Index out of bounds. Index ${index}, max index: ${this.maxIndex}.`);
19
+ }
20
+
21
+ const insertingZeroElement = leaf.equals(INITIAL_LEAF);
22
+ const originallyZeroElement = this.getLeafValue(index, true)?.equals(INITIAL_LEAF);
23
+ if (insertingZeroElement && originallyZeroElement) {
24
+ return Promise.resolve();
25
+ }
26
+ this.addLeafToCacheAndHashToRoot(leaf, index);
27
+ if (insertingZeroElement) {
28
+ // Deleting element (originally non-zero and new value is zero)
29
+ this.cachedSize = (this.cachedSize ?? this.size) - 1n;
30
+ } else if (originallyZeroElement) {
31
+ // Inserting new element (originally zero and new value is non-zero)
32
+ this.cachedSize = (this.cachedSize ?? this.size) + 1n;
33
+ }
34
+
35
+ return Promise.resolve();
36
+ }
37
+
38
+ public snapshot(block: number): Promise<TreeSnapshot> {
39
+ return this.#snapshotBuilder.snapshot(block);
40
+ }
41
+
42
+ public getSnapshot(block: number): Promise<TreeSnapshot> {
43
+ return this.#snapshotBuilder.getSnapshot(block);
44
+ }
45
+
46
+ public findLeafIndex(_value: Buffer, _includeUncommitted: boolean): bigint | undefined {
47
+ throw new Error('Finding leaf index is not supported for sparse trees');
48
+ }
49
+ }