@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.
- package/package.json +3 -3
- package/src/index.ts +0 -15
- package/src/interfaces/append_only_tree.ts +0 -13
- package/src/interfaces/indexed_tree.ts +0 -92
- package/src/interfaces/merkle_tree.ts +0 -60
- package/src/interfaces/update_only_tree.ts +0 -14
- package/src/load_tree.ts +0 -26
- package/src/new_tree.ts +0 -28
- package/src/pedersen.ts +0 -25
- package/src/snapshots/append_only_snapshot.ts +0 -243
- package/src/snapshots/base_full_snapshot.ts +0 -232
- package/src/snapshots/full_snapshot.ts +0 -26
- package/src/snapshots/indexed_tree_snapshot.ts +0 -108
- package/src/snapshots/snapshot_builder.ts +0 -84
- package/src/snapshots/snapshot_builder_test_suite.ts +0 -218
- package/src/sparse_tree/sparse_tree.ts +0 -48
- package/src/standard_indexed_tree/standard_indexed_tree.ts +0 -612
- package/src/standard_indexed_tree/test/standard_indexed_tree_with_append.ts +0 -66
- package/src/standard_tree/standard_tree.ts +0 -37
- package/src/tree_base.ts +0 -311
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aztec/merkle-tree",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.5",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": "./dest/index.js",
|
|
6
6
|
"typedocOptions": {
|
|
@@ -32,8 +32,8 @@
|
|
|
32
32
|
"testTimeout": 15000
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"@aztec/foundation": "0.16.
|
|
36
|
-
"@aztec/types": "0.16.
|
|
35
|
+
"@aztec/foundation": "0.16.5",
|
|
36
|
+
"@aztec/types": "0.16.5",
|
|
37
37
|
"levelup": "^5.1.1",
|
|
38
38
|
"memdown": "^6.1.1",
|
|
39
39
|
"sha256": "^0.2.0",
|
package/src/index.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
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 } 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';
|
|
@@ -1,13 +0,0 @@
|
|
|
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
|
-
}
|
|
@@ -1,92 +0,0 @@
|
|
|
1
|
-
import { IndexedTreeLeafPreimage } from '@aztec/foundation/trees';
|
|
2
|
-
import { SiblingPath } from '@aztec/types';
|
|
3
|
-
|
|
4
|
-
import { AppendOnlyTree } from './append_only_tree.js';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* All of the data to be return during batch insertion.
|
|
8
|
-
*/
|
|
9
|
-
export interface LowLeafWitnessData<N extends number> {
|
|
10
|
-
/**
|
|
11
|
-
* Preimage of the low nullifier that proves non membership.
|
|
12
|
-
*/
|
|
13
|
-
leafPreimage: IndexedTreeLeafPreimage;
|
|
14
|
-
/**
|
|
15
|
-
* Sibling path to prove membership of low nullifier.
|
|
16
|
-
*/
|
|
17
|
-
siblingPath: SiblingPath<N>;
|
|
18
|
-
/**
|
|
19
|
-
* The index of low nullifier.
|
|
20
|
-
*/
|
|
21
|
-
index: bigint;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/**
|
|
25
|
-
* The result of a batch insertion in an indexed merkle tree.
|
|
26
|
-
*/
|
|
27
|
-
export interface BatchInsertionResult<TreeHeight extends number, SubtreeSiblingPathHeight extends number> {
|
|
28
|
-
/**
|
|
29
|
-
* Data for the leaves to be updated when inserting the new ones.
|
|
30
|
-
*/
|
|
31
|
-
lowLeavesWitnessData?: LowLeafWitnessData<TreeHeight>[];
|
|
32
|
-
/**
|
|
33
|
-
* Sibling path "pointing to" where the new subtree should be inserted into the tree.
|
|
34
|
-
*/
|
|
35
|
-
newSubtreeSiblingPath: SiblingPath<SubtreeSiblingPathHeight>;
|
|
36
|
-
/**
|
|
37
|
-
* The new leaves being inserted in high to low order. This order corresponds with the order of the low leaves witness.
|
|
38
|
-
*/
|
|
39
|
-
sortedNewLeaves: Buffer[];
|
|
40
|
-
/**
|
|
41
|
-
* The indexes of the sorted new leaves to the original ones.
|
|
42
|
-
*/
|
|
43
|
-
sortedNewLeavesIndexes: number[];
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Indexed merkle tree.
|
|
48
|
-
*/
|
|
49
|
-
export interface IndexedTree extends AppendOnlyTree {
|
|
50
|
-
/**
|
|
51
|
-
* Finds the index of the largest leaf whose value is less than or equal to the provided value.
|
|
52
|
-
* @param newValue - The new value to be inserted into the tree.
|
|
53
|
-
* @param includeUncommitted - If true, the uncommitted changes are included in the search.
|
|
54
|
-
* @returns The found leaf index and a flag indicating if the corresponding leaf's value is equal to `newValue`.
|
|
55
|
-
*/
|
|
56
|
-
findIndexOfPreviousKey(
|
|
57
|
-
newValue: bigint,
|
|
58
|
-
includeUncommitted: boolean,
|
|
59
|
-
): Promise<
|
|
60
|
-
| {
|
|
61
|
-
/**
|
|
62
|
-
* The index of the found leaf.
|
|
63
|
-
*/
|
|
64
|
-
index: bigint;
|
|
65
|
-
/**
|
|
66
|
-
* A flag indicating if the corresponding leaf's value is equal to `newValue`.
|
|
67
|
-
*/
|
|
68
|
-
alreadyPresent: boolean;
|
|
69
|
-
}
|
|
70
|
-
| undefined
|
|
71
|
-
>;
|
|
72
|
-
|
|
73
|
-
/**
|
|
74
|
-
* Gets the latest LeafPreimage copy.
|
|
75
|
-
* @param index - Index of the leaf of which to obtain the LeafPreimage copy.
|
|
76
|
-
* @param includeUncommitted - If true, the uncommitted changes are included in the search.
|
|
77
|
-
* @returns A copy of the leaf preimage at the given index or undefined if the leaf was not found.
|
|
78
|
-
*/
|
|
79
|
-
getLatestLeafPreimageCopy(index: bigint, includeUncommitted: boolean): Promise<IndexedTreeLeafPreimage | undefined>;
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* Batch insert multiple leaves into the tree.
|
|
83
|
-
* @param leaves - Leaves to insert into the tree.
|
|
84
|
-
* @param subtreeHeight - Height of the subtree.
|
|
85
|
-
* @param includeUncommitted - If true, the uncommitted changes are included in the search.
|
|
86
|
-
*/
|
|
87
|
-
batchInsert<TreeHeight extends number, SubtreeHeight extends number, SubtreeSiblingPathHeight extends number>(
|
|
88
|
-
leaves: Buffer[],
|
|
89
|
-
subtreeHeight: SubtreeHeight,
|
|
90
|
-
includeUncommitted: boolean,
|
|
91
|
-
): Promise<BatchInsertionResult<TreeHeight, SubtreeSiblingPathHeight>>;
|
|
92
|
-
}
|
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
import { SiblingPath } from '@aztec/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): Promise<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): Promise<bigint | undefined>;
|
|
60
|
-
}
|
|
@@ -1,14 +0,0 @@
|
|
|
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
|
-
}
|
package/src/load_tree.ts
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
import { Hasher } from '@aztec/types';
|
|
2
|
-
|
|
3
|
-
import { LevelUp } from 'levelup';
|
|
4
|
-
|
|
5
|
-
import { TreeBase, decodeMeta } from './tree_base.js';
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Creates a new tree and sets its root, depth and size based on the meta data which are associated with the name.
|
|
9
|
-
* @param c - The class of the tree to be instantiated.
|
|
10
|
-
* @param db - A database used to store the Merkle tree data.
|
|
11
|
-
* @param hasher - A hasher used to compute hash paths.
|
|
12
|
-
* @param name - Name of the tree.
|
|
13
|
-
* @returns The newly created tree.
|
|
14
|
-
*/
|
|
15
|
-
export async function loadTree<T extends TreeBase>(
|
|
16
|
-
c: new (db: LevelUp, hasher: Hasher, name: string, depth: number, size: bigint, root: Buffer) => T,
|
|
17
|
-
db: LevelUp,
|
|
18
|
-
hasher: Hasher,
|
|
19
|
-
name: string,
|
|
20
|
-
): Promise<T> {
|
|
21
|
-
const meta: Buffer = await db.get(name);
|
|
22
|
-
const { root, depth, size } = decodeMeta(meta);
|
|
23
|
-
|
|
24
|
-
const tree = new c(db, hasher, name, depth, size, root);
|
|
25
|
-
return tree;
|
|
26
|
-
}
|
package/src/new_tree.ts
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { Hasher } from '@aztec/types';
|
|
2
|
-
|
|
3
|
-
import { LevelUp } from 'levelup';
|
|
4
|
-
|
|
5
|
-
import { TreeBase } from './tree_base.js';
|
|
6
|
-
|
|
7
|
-
/**
|
|
8
|
-
* Creates a new tree.
|
|
9
|
-
* @param c - The class of the tree to be instantiated.
|
|
10
|
-
* @param db - A database used to store the Merkle tree data.
|
|
11
|
-
* @param hasher - A hasher used to compute hash paths.
|
|
12
|
-
* @param name - Name of the tree.
|
|
13
|
-
* @param depth - Depth of the tree.
|
|
14
|
-
* @param prefilledSize - A number of leaves that are prefilled with values.
|
|
15
|
-
* @returns The newly created tree.
|
|
16
|
-
*/
|
|
17
|
-
export async function newTree<T extends TreeBase>(
|
|
18
|
-
c: new (db: LevelUp, hasher: Hasher, name: string, depth: number, size: bigint) => T,
|
|
19
|
-
db: LevelUp,
|
|
20
|
-
hasher: Hasher,
|
|
21
|
-
name: string,
|
|
22
|
-
depth: number,
|
|
23
|
-
prefilledSize = 1,
|
|
24
|
-
): Promise<T> {
|
|
25
|
-
const tree = new c(db, hasher, name, depth, 0n);
|
|
26
|
-
await tree.init(prefilledSize);
|
|
27
|
-
return tree;
|
|
28
|
-
}
|
package/src/pedersen.ts
DELETED
|
@@ -1,25 +0,0 @@
|
|
|
1
|
-
import { pedersenHash } from '@aztec/foundation/crypto';
|
|
2
|
-
import { Hasher } from '@aztec/types';
|
|
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
|
-
}
|
|
@@ -1,243 +0,0 @@
|
|
|
1
|
-
import { Hasher, SiblingPath } from '@aztec/types';
|
|
2
|
-
|
|
3
|
-
import { LevelUp } from 'levelup';
|
|
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 = (treeName: string, level: number, index: bigint) =>
|
|
11
|
-
`snapshot:node:${treeName}:${level}:${index}:block`;
|
|
12
|
-
|
|
13
|
-
// stores the value of the node at the above block
|
|
14
|
-
const historicalNodeKey = (treeName: string, level: number, index: bigint) =>
|
|
15
|
-
`snapshot:node:${treeName}:${level}:${index}:value`;
|
|
16
|
-
|
|
17
|
-
// metadata for a snapshot
|
|
18
|
-
const snapshotRootKey = (treeName: string, block: number) => `snapshot:root:${treeName}:${block}`;
|
|
19
|
-
const snapshotNumLeavesKey = (treeName: string, block: number) => `snapshot:numLeaves:${treeName}:${block}`;
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* A more space-efficient way of storing snapshots of AppendOnlyTrees that trades space need for slower
|
|
23
|
-
* sibling path reads.
|
|
24
|
-
*
|
|
25
|
-
* Complexity:
|
|
26
|
-
*
|
|
27
|
-
* N - count of non-zero nodes in tree
|
|
28
|
-
* M - count of snapshots
|
|
29
|
-
* H - tree height
|
|
30
|
-
*
|
|
31
|
-
* 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)
|
|
32
|
-
* Sibling path access:
|
|
33
|
-
* Best case: O(H) database reads + O(1) hashes
|
|
34
|
-
* Worst case: O(H) database reads + O(H) hashes
|
|
35
|
-
*/
|
|
36
|
-
export class AppendOnlySnapshotBuilder implements TreeSnapshotBuilder {
|
|
37
|
-
constructor(private db: LevelUp, private tree: TreeBase & AppendOnlyTree, private hasher: Hasher) {}
|
|
38
|
-
async getSnapshot(block: number): Promise<TreeSnapshot> {
|
|
39
|
-
const meta = await this.#getSnapshotMeta(block);
|
|
40
|
-
|
|
41
|
-
if (typeof meta === 'undefined') {
|
|
42
|
-
throw new Error(`Snapshot for tree ${this.tree.getName()} at block ${block} does not exist`);
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
return new AppendOnlySnapshot(this.db, block, meta.numLeaves, meta.root, this.tree, this.hasher);
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
async snapshot(block: number): Promise<TreeSnapshot> {
|
|
49
|
-
const meta = await this.#getSnapshotMeta(block);
|
|
50
|
-
if (typeof meta !== 'undefined') {
|
|
51
|
-
// no-op, we already have a snapshot
|
|
52
|
-
return new AppendOnlySnapshot(this.db, block, meta.numLeaves, meta.root, this.tree, this.hasher);
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
const batch = this.db.batch();
|
|
56
|
-
const root = this.tree.getRoot(false);
|
|
57
|
-
const depth = this.tree.getDepth();
|
|
58
|
-
const treeName = this.tree.getName();
|
|
59
|
-
const queue: [Buffer, number, bigint][] = [[root, 0, 0n]];
|
|
60
|
-
|
|
61
|
-
// walk the tree in BF and store latest nodes
|
|
62
|
-
while (queue.length > 0) {
|
|
63
|
-
const [node, level, index] = queue.shift()!;
|
|
64
|
-
|
|
65
|
-
const historicalValue = await this.db.get(historicalNodeKey(treeName, level, index)).catch(() => undefined);
|
|
66
|
-
if (!historicalValue || !node.equals(historicalValue)) {
|
|
67
|
-
// we've never seen this node before or it's different than before
|
|
68
|
-
// update the historical tree and tag it with the block that modified it
|
|
69
|
-
batch.put(nodeModifiedAtBlockKey(treeName, level, index), String(block));
|
|
70
|
-
batch.put(historicalNodeKey(treeName, level, index), node);
|
|
71
|
-
} else {
|
|
72
|
-
// if this node hasn't changed, that means, nothing below it has changed either
|
|
73
|
-
continue;
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
if (level + 1 > depth) {
|
|
77
|
-
// short circuit if we've reached the leaf level
|
|
78
|
-
// otherwise getNode might throw if we ask for the children of a leaf
|
|
79
|
-
continue;
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// these could be undefined because zero hashes aren't stored in the tree
|
|
83
|
-
const [lhs, rhs] = await Promise.all([
|
|
84
|
-
this.tree.getNode(level + 1, 2n * index),
|
|
85
|
-
this.tree.getNode(level + 1, 2n * index + 1n),
|
|
86
|
-
]);
|
|
87
|
-
|
|
88
|
-
if (lhs) {
|
|
89
|
-
queue.push([lhs, level + 1, 2n * index]);
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
if (rhs) {
|
|
93
|
-
queue.push([rhs, level + 1, 2n * index + 1n]);
|
|
94
|
-
}
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const numLeaves = this.tree.getNumLeaves(false);
|
|
98
|
-
batch.put(snapshotNumLeavesKey(treeName, block), String(numLeaves));
|
|
99
|
-
batch.put(snapshotRootKey(treeName, block), root);
|
|
100
|
-
await batch.write();
|
|
101
|
-
|
|
102
|
-
return new AppendOnlySnapshot(this.db, block, numLeaves, root, this.tree, this.hasher);
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
async #getSnapshotMeta(block: number): Promise<
|
|
106
|
-
| {
|
|
107
|
-
/** The root of the tree snapshot */
|
|
108
|
-
root: Buffer;
|
|
109
|
-
/** The number of leaves in the tree snapshot */
|
|
110
|
-
numLeaves: bigint;
|
|
111
|
-
}
|
|
112
|
-
| undefined
|
|
113
|
-
> {
|
|
114
|
-
try {
|
|
115
|
-
const treeName = this.tree.getName();
|
|
116
|
-
const root = await this.db.get(snapshotRootKey(treeName, block));
|
|
117
|
-
const numLeaves = BigInt(await this.db.get(snapshotNumLeavesKey(treeName, block)));
|
|
118
|
-
return { root, numLeaves };
|
|
119
|
-
} catch (err) {
|
|
120
|
-
return undefined;
|
|
121
|
-
}
|
|
122
|
-
}
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
/**
|
|
126
|
-
* a
|
|
127
|
-
*/
|
|
128
|
-
class AppendOnlySnapshot implements TreeSnapshot {
|
|
129
|
-
constructor(
|
|
130
|
-
private db: LevelUp,
|
|
131
|
-
private block: number,
|
|
132
|
-
private leafCount: bigint,
|
|
133
|
-
private historicalRoot: Buffer,
|
|
134
|
-
private tree: TreeBase & AppendOnlyTree,
|
|
135
|
-
private hasher: Hasher,
|
|
136
|
-
) {}
|
|
137
|
-
|
|
138
|
-
public async getSiblingPath<N extends number>(index: bigint): Promise<SiblingPath<N>> {
|
|
139
|
-
const path: Buffer[] = [];
|
|
140
|
-
const depth = this.tree.getDepth();
|
|
141
|
-
let level = depth;
|
|
142
|
-
|
|
143
|
-
while (level > 0) {
|
|
144
|
-
const isRight = index & 0x01n;
|
|
145
|
-
const siblingIndex = isRight ? index - 1n : index + 1n;
|
|
146
|
-
|
|
147
|
-
const sibling = await this.#getHistoricalNodeValue(level, siblingIndex);
|
|
148
|
-
path.push(sibling);
|
|
149
|
-
|
|
150
|
-
level -= 1;
|
|
151
|
-
index >>= 1n;
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
return new SiblingPath<N>(depth as N, path);
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
getDepth(): number {
|
|
158
|
-
return this.tree.getDepth();
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
getNumLeaves(): bigint {
|
|
162
|
-
return this.leafCount;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
getRoot(): Buffer {
|
|
166
|
-
// we could recompute it, but it's way cheaper to just store the root
|
|
167
|
-
return this.historicalRoot;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
async getLeafValue(index: bigint): Promise<Buffer | undefined> {
|
|
171
|
-
const leafLevel = this.getDepth();
|
|
172
|
-
const blockNumber = await this.#getBlockNumberThatModifiedNode(leafLevel, index);
|
|
173
|
-
|
|
174
|
-
// leaf hasn't been set yet
|
|
175
|
-
if (typeof blockNumber === 'undefined') {
|
|
176
|
-
return undefined;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
// leaf was set some time in the past
|
|
180
|
-
if (blockNumber <= this.block) {
|
|
181
|
-
return this.db.get(historicalNodeKey(this.tree.getName(), leafLevel, index));
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
// leaf has been set but in a block in the future
|
|
185
|
-
return undefined;
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
async #getHistoricalNodeValue(level: number, index: bigint): Promise<Buffer> {
|
|
189
|
-
const blockNumber = await this.#getBlockNumberThatModifiedNode(level, index);
|
|
190
|
-
|
|
191
|
-
// node has never been set
|
|
192
|
-
if (typeof blockNumber === 'undefined') {
|
|
193
|
-
return this.tree.getZeroHash(level);
|
|
194
|
-
}
|
|
195
|
-
|
|
196
|
-
// node was set some time in the past
|
|
197
|
-
if (blockNumber <= this.block) {
|
|
198
|
-
return this.db.get(historicalNodeKey(this.tree.getName(), level, index));
|
|
199
|
-
}
|
|
200
|
-
|
|
201
|
-
// the node has been modified since this snapshot was taken
|
|
202
|
-
// because we're working with an AppendOnly tree, historical leaves never change
|
|
203
|
-
// so what we do instead is rebuild this Merkle path up using zero hashes as needed
|
|
204
|
-
// worst case this will do O(H) hashes
|
|
205
|
-
//
|
|
206
|
-
// we first check if this subtree was touched by the block
|
|
207
|
-
// compare how many leaves this block added to the leaf interval of this subtree
|
|
208
|
-
// if they don't intersect then the whole subtree was a hash of zero
|
|
209
|
-
// if they do then we need to rebuild the merkle tree
|
|
210
|
-
const depth = this.tree.getDepth();
|
|
211
|
-
const leafStart = index * 2n ** BigInt(depth - level);
|
|
212
|
-
if (leafStart >= this.leafCount) {
|
|
213
|
-
return this.tree.getZeroHash(level);
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
const [lhs, rhs] = await Promise.all([
|
|
217
|
-
this.#getHistoricalNodeValue(level + 1, 2n * index),
|
|
218
|
-
this.#getHistoricalNodeValue(level + 1, 2n * index + 1n),
|
|
219
|
-
]);
|
|
220
|
-
|
|
221
|
-
return this.hasher.hash(lhs, rhs);
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
async #getBlockNumberThatModifiedNode(level: number, index: bigint): Promise<number | undefined> {
|
|
225
|
-
try {
|
|
226
|
-
const value: Buffer | string = await this.db.get(nodeModifiedAtBlockKey(this.tree.getName(), level, index));
|
|
227
|
-
return parseInt(value.toString(), 10);
|
|
228
|
-
} catch (err) {
|
|
229
|
-
return undefined;
|
|
230
|
-
}
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
async findLeafIndex(value: Buffer): Promise<bigint | undefined> {
|
|
234
|
-
const numLeaves = this.getNumLeaves();
|
|
235
|
-
for (let i = 0n; i < numLeaves; i++) {
|
|
236
|
-
const currentValue = await this.getLeafValue(i);
|
|
237
|
-
if (currentValue && currentValue.equals(value)) {
|
|
238
|
-
return i;
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
return undefined;
|
|
242
|
-
}
|
|
243
|
-
}
|