@aztec/merkle-tree 0.16.4 → 0.16.5

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