@aztec/world-state 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.
- package/dest/synchronizer/server_world_state_synchronizer.d.ts +3 -3
- package/dest/synchronizer/server_world_state_synchronizer.js +3 -3
- package/dest/world-state-db/merkle_tree_operations.d.ts +1 -1
- package/dest/world-state-db/merkle_tree_operations_facade.d.ts +1 -1
- package/dest/world-state-db/merkle_tree_operations_facade.js +1 -1
- package/dest/world-state-db/merkle_trees.d.ts +1 -1
- package/dest/world-state-db/merkle_trees.d.ts.map +1 -1
- package/dest/world-state-db/merkle_trees.js +12 -11
- package/package.json +7 -7
- package/src/index.ts +3 -0
- package/src/synchronizer/config.ts +27 -0
- package/src/synchronizer/index.ts +2 -0
- package/src/synchronizer/server_world_state_synchronizer.ts +215 -0
- package/src/synchronizer/world_state_synchronizer.ts +73 -0
- package/src/world-state-db/index.ts +3 -0
- package/src/world-state-db/merkle_tree_db.ts +50 -0
- package/src/world-state-db/merkle_tree_operations.ts +178 -0
- package/src/world-state-db/merkle_tree_operations_facade.ts +182 -0
- package/src/world-state-db/merkle_tree_snapshot_operations_facade.ts +157 -0
- package/src/world-state-db/merkle_trees.ts +577 -0
|
@@ -0,0 +1,577 @@
|
|
|
1
|
+
import { L2Block, MerkleTreeId, SiblingPath } from '@aztec/circuit-types';
|
|
2
|
+
import {
|
|
3
|
+
ARCHIVE_HEIGHT,
|
|
4
|
+
AppendOnlyTreeSnapshot,
|
|
5
|
+
CONTRACT_TREE_HEIGHT,
|
|
6
|
+
ContentCommitment,
|
|
7
|
+
Fr,
|
|
8
|
+
GlobalVariables,
|
|
9
|
+
Header,
|
|
10
|
+
L1_TO_L2_MSG_TREE_HEIGHT,
|
|
11
|
+
MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX,
|
|
12
|
+
NOTE_HASH_TREE_HEIGHT,
|
|
13
|
+
NULLIFIER_SUBTREE_HEIGHT,
|
|
14
|
+
NULLIFIER_TREE_HEIGHT,
|
|
15
|
+
NullifierLeaf,
|
|
16
|
+
NullifierLeafPreimage,
|
|
17
|
+
PUBLIC_DATA_SUBTREE_HEIGHT,
|
|
18
|
+
PUBLIC_DATA_TREE_HEIGHT,
|
|
19
|
+
PartialStateReference,
|
|
20
|
+
PublicDataTreeLeaf,
|
|
21
|
+
PublicDataTreeLeafPreimage,
|
|
22
|
+
StateReference,
|
|
23
|
+
} from '@aztec/circuits.js';
|
|
24
|
+
import { SerialQueue } from '@aztec/foundation/fifo';
|
|
25
|
+
import { DebugLogger, createDebugLogger } from '@aztec/foundation/log';
|
|
26
|
+
import { IndexedTreeLeafPreimage } from '@aztec/foundation/trees';
|
|
27
|
+
import { AztecKVStore } from '@aztec/kv-store';
|
|
28
|
+
import {
|
|
29
|
+
AppendOnlyTree,
|
|
30
|
+
BatchInsertionResult,
|
|
31
|
+
IndexedTree,
|
|
32
|
+
Pedersen,
|
|
33
|
+
StandardIndexedTree,
|
|
34
|
+
StandardTree,
|
|
35
|
+
UpdateOnlyTree,
|
|
36
|
+
getTreeMeta,
|
|
37
|
+
loadTree,
|
|
38
|
+
newTree,
|
|
39
|
+
} from '@aztec/merkle-tree';
|
|
40
|
+
import { Hasher } from '@aztec/types/interfaces';
|
|
41
|
+
|
|
42
|
+
import { INITIAL_NULLIFIER_TREE_SIZE, INITIAL_PUBLIC_DATA_TREE_SIZE, MerkleTreeDb } from './merkle_tree_db.js';
|
|
43
|
+
import { HandleL2BlockResult, IndexedTreeId, MerkleTreeOperations, TreeInfo } from './merkle_tree_operations.js';
|
|
44
|
+
import { MerkleTreeOperationsFacade } from './merkle_tree_operations_facade.js';
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* The nullifier tree is an indexed tree.
|
|
48
|
+
*/
|
|
49
|
+
class NullifierTree extends StandardIndexedTree {
|
|
50
|
+
constructor(store: AztecKVStore, hasher: Hasher, name: string, depth: number, size: bigint = 0n, root?: Buffer) {
|
|
51
|
+
super(store, hasher, name, depth, size, NullifierLeafPreimage, NullifierLeaf, root);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The public data tree is an indexed tree.
|
|
57
|
+
*/
|
|
58
|
+
class PublicDataTree extends StandardIndexedTree {
|
|
59
|
+
constructor(store: AztecKVStore, hasher: Hasher, name: string, depth: number, size: bigint = 0n, root?: Buffer) {
|
|
60
|
+
super(store, hasher, name, depth, size, PublicDataTreeLeafPreimage, PublicDataTreeLeaf, root);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* A convenience class for managing multiple merkle trees.
|
|
66
|
+
*/
|
|
67
|
+
export class MerkleTrees implements MerkleTreeDb {
|
|
68
|
+
private trees: (AppendOnlyTree | UpdateOnlyTree)[] = [];
|
|
69
|
+
private jobQueue = new SerialQueue();
|
|
70
|
+
|
|
71
|
+
private constructor(private store: AztecKVStore, private log: DebugLogger) {}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Method to asynchronously create and initialize a MerkleTrees instance.
|
|
75
|
+
* @param store - The db instance to use for data persistance.
|
|
76
|
+
* @returns - A fully initialized MerkleTrees instance.
|
|
77
|
+
*/
|
|
78
|
+
public static async new(store: AztecKVStore, log = createDebugLogger('aztec:merkle_trees')) {
|
|
79
|
+
const merkleTrees = new MerkleTrees(store, log);
|
|
80
|
+
await merkleTrees.#init();
|
|
81
|
+
return merkleTrees;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Initializes the collection of Merkle Trees.
|
|
86
|
+
*/
|
|
87
|
+
async #init() {
|
|
88
|
+
const fromDb = this.#isDbPopulated();
|
|
89
|
+
const initializeTree = fromDb ? loadTree : newTree;
|
|
90
|
+
|
|
91
|
+
const hasher = new Pedersen();
|
|
92
|
+
const contractTree: AppendOnlyTree = await initializeTree(
|
|
93
|
+
StandardTree,
|
|
94
|
+
this.store,
|
|
95
|
+
hasher,
|
|
96
|
+
`${MerkleTreeId[MerkleTreeId.CONTRACT_TREE]}`,
|
|
97
|
+
CONTRACT_TREE_HEIGHT,
|
|
98
|
+
);
|
|
99
|
+
const nullifierTree = await initializeTree(
|
|
100
|
+
NullifierTree,
|
|
101
|
+
this.store,
|
|
102
|
+
hasher,
|
|
103
|
+
`${MerkleTreeId[MerkleTreeId.NULLIFIER_TREE]}`,
|
|
104
|
+
NULLIFIER_TREE_HEIGHT,
|
|
105
|
+
INITIAL_NULLIFIER_TREE_SIZE,
|
|
106
|
+
);
|
|
107
|
+
const noteHashTree: AppendOnlyTree = await initializeTree(
|
|
108
|
+
StandardTree,
|
|
109
|
+
this.store,
|
|
110
|
+
hasher,
|
|
111
|
+
`${MerkleTreeId[MerkleTreeId.NOTE_HASH_TREE]}`,
|
|
112
|
+
NOTE_HASH_TREE_HEIGHT,
|
|
113
|
+
);
|
|
114
|
+
const publicDataTree = await initializeTree(
|
|
115
|
+
PublicDataTree,
|
|
116
|
+
this.store,
|
|
117
|
+
hasher,
|
|
118
|
+
`${MerkleTreeId[MerkleTreeId.PUBLIC_DATA_TREE]}`,
|
|
119
|
+
PUBLIC_DATA_TREE_HEIGHT,
|
|
120
|
+
INITIAL_PUBLIC_DATA_TREE_SIZE,
|
|
121
|
+
);
|
|
122
|
+
const l1Tol2MessageTree: AppendOnlyTree = await initializeTree(
|
|
123
|
+
StandardTree,
|
|
124
|
+
this.store,
|
|
125
|
+
hasher,
|
|
126
|
+
`${MerkleTreeId[MerkleTreeId.L1_TO_L2_MESSAGE_TREE]}`,
|
|
127
|
+
L1_TO_L2_MSG_TREE_HEIGHT,
|
|
128
|
+
);
|
|
129
|
+
const archive: AppendOnlyTree = await initializeTree(
|
|
130
|
+
StandardTree,
|
|
131
|
+
this.store,
|
|
132
|
+
hasher,
|
|
133
|
+
`${MerkleTreeId[MerkleTreeId.ARCHIVE]}`,
|
|
134
|
+
ARCHIVE_HEIGHT,
|
|
135
|
+
);
|
|
136
|
+
this.trees = [contractTree, nullifierTree, noteHashTree, publicDataTree, l1Tol2MessageTree, archive];
|
|
137
|
+
|
|
138
|
+
this.jobQueue.start();
|
|
139
|
+
|
|
140
|
+
if (!fromDb) {
|
|
141
|
+
// We are not initializing from db so we need to populate the first leaf of the archive tree which is a hash of
|
|
142
|
+
// the initial header.
|
|
143
|
+
const initialHeder = await this.buildInitialHeader(true);
|
|
144
|
+
await this.#updateArchive(initialHeder, true);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
await this.#commit();
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
public async buildInitialHeader(includeUncommitted: boolean): Promise<Header> {
|
|
151
|
+
const state = await this.getStateReference(includeUncommitted);
|
|
152
|
+
return new Header(AppendOnlyTreeSnapshot.zero(), ContentCommitment.empty(), state, GlobalVariables.empty());
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Stops the job queue (waits for all jobs to finish).
|
|
157
|
+
*/
|
|
158
|
+
public async stop() {
|
|
159
|
+
await this.jobQueue.end();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Gets a view of this db that returns uncommitted data.
|
|
164
|
+
* @returns - A facade for this instance.
|
|
165
|
+
*/
|
|
166
|
+
public asLatest(): MerkleTreeOperations {
|
|
167
|
+
return new MerkleTreeOperationsFacade(this, true);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* Gets a view of this db that returns committed data only.
|
|
172
|
+
* @returns - A facade for this instance.
|
|
173
|
+
*/
|
|
174
|
+
public asCommitted(): MerkleTreeOperations {
|
|
175
|
+
return new MerkleTreeOperationsFacade(this, false);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Updates the archive with the new block/header hash.
|
|
180
|
+
* @param header - The header whose hash to insert into the archive.
|
|
181
|
+
* @param includeUncommitted - Indicates whether to include uncommitted data.
|
|
182
|
+
*/
|
|
183
|
+
public async updateArchive(header: Header, includeUncommitted: boolean) {
|
|
184
|
+
await this.synchronize(() => this.#updateArchive(header, includeUncommitted));
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Gets the tree info for the specified tree.
|
|
189
|
+
* @param treeId - Id of the tree to get information from.
|
|
190
|
+
* @param includeUncommitted - Indicates whether to include uncommitted data.
|
|
191
|
+
* @returns The tree info for the specified tree.
|
|
192
|
+
*/
|
|
193
|
+
public async getTreeInfo(treeId: MerkleTreeId, includeUncommitted: boolean): Promise<TreeInfo> {
|
|
194
|
+
return await this.synchronize(() => this.#getTreeInfo(treeId, includeUncommitted));
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Get the current state reference
|
|
199
|
+
* @param includeUncommitted - Indicates whether to include uncommitted data.
|
|
200
|
+
* @returns The current state reference
|
|
201
|
+
*/
|
|
202
|
+
public getStateReference(includeUncommitted: boolean): Promise<StateReference> {
|
|
203
|
+
const getAppendOnlyTreeSnapshot = (treeId: MerkleTreeId) => {
|
|
204
|
+
const tree = this.trees[treeId] as AppendOnlyTree;
|
|
205
|
+
return new AppendOnlyTreeSnapshot(
|
|
206
|
+
Fr.fromBuffer(tree.getRoot(includeUncommitted)),
|
|
207
|
+
Number(tree.getNumLeaves(includeUncommitted)),
|
|
208
|
+
);
|
|
209
|
+
};
|
|
210
|
+
|
|
211
|
+
const state = new StateReference(
|
|
212
|
+
getAppendOnlyTreeSnapshot(MerkleTreeId.L1_TO_L2_MESSAGE_TREE),
|
|
213
|
+
new PartialStateReference(
|
|
214
|
+
getAppendOnlyTreeSnapshot(MerkleTreeId.NOTE_HASH_TREE),
|
|
215
|
+
getAppendOnlyTreeSnapshot(MerkleTreeId.NULLIFIER_TREE),
|
|
216
|
+
getAppendOnlyTreeSnapshot(MerkleTreeId.CONTRACT_TREE),
|
|
217
|
+
getAppendOnlyTreeSnapshot(MerkleTreeId.PUBLIC_DATA_TREE),
|
|
218
|
+
),
|
|
219
|
+
);
|
|
220
|
+
return Promise.resolve(state);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Gets the value at the given index.
|
|
225
|
+
* @param treeId - The ID of the tree to get the leaf value from.
|
|
226
|
+
* @param index - The index of the leaf.
|
|
227
|
+
* @param includeUncommitted - Indicates whether to include uncommitted changes.
|
|
228
|
+
* @returns Leaf value at the given index (undefined if not found).
|
|
229
|
+
*/
|
|
230
|
+
public async getLeafValue(
|
|
231
|
+
treeId: MerkleTreeId,
|
|
232
|
+
index: bigint,
|
|
233
|
+
includeUncommitted: boolean,
|
|
234
|
+
): Promise<Buffer | undefined> {
|
|
235
|
+
return await this.synchronize(() => Promise.resolve(this.trees[treeId].getLeafValue(index, includeUncommitted)));
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Gets the sibling path for a leaf in a tree.
|
|
240
|
+
* @param treeId - The ID of the tree.
|
|
241
|
+
* @param index - The index of the leaf.
|
|
242
|
+
* @param includeUncommitted - Indicates whether the sibling path should include uncommitted data.
|
|
243
|
+
* @returns The sibling path for the leaf.
|
|
244
|
+
*/
|
|
245
|
+
public async getSiblingPath<N extends number>(
|
|
246
|
+
treeId: MerkleTreeId,
|
|
247
|
+
index: bigint,
|
|
248
|
+
includeUncommitted: boolean,
|
|
249
|
+
): Promise<SiblingPath<N>> {
|
|
250
|
+
return await this.synchronize(() => this.trees[treeId].getSiblingPath<N>(index, includeUncommitted));
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Appends leaves to a tree.
|
|
255
|
+
* @param treeId - The ID of the tree.
|
|
256
|
+
* @param leaves - The leaves to append.
|
|
257
|
+
* @returns Empty promise.
|
|
258
|
+
*/
|
|
259
|
+
public async appendLeaves(treeId: MerkleTreeId, leaves: Buffer[]): Promise<void> {
|
|
260
|
+
return await this.synchronize(() => this.#appendLeaves(treeId, leaves));
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Commits all pending updates.
|
|
265
|
+
* @returns Empty promise.
|
|
266
|
+
*/
|
|
267
|
+
public async commit(): Promise<void> {
|
|
268
|
+
return await this.synchronize(() => this.#commit());
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Rolls back all pending updates.
|
|
273
|
+
* @returns Empty promise.
|
|
274
|
+
*/
|
|
275
|
+
public async rollback(): Promise<void> {
|
|
276
|
+
return await this.synchronize(() => this.#rollback());
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/**
|
|
280
|
+
* Finds the index of the largest leaf whose value is less than or equal to the provided value.
|
|
281
|
+
* @param treeId - The ID of the tree to search.
|
|
282
|
+
* @param value - The value to be inserted into the tree.
|
|
283
|
+
* @param includeUncommitted - If true, the uncommitted changes are included in the search.
|
|
284
|
+
* @returns The found leaf index and a flag indicating if the corresponding leaf's value is equal to `newValue`.
|
|
285
|
+
*/
|
|
286
|
+
public async getPreviousValueIndex(
|
|
287
|
+
treeId: IndexedTreeId,
|
|
288
|
+
value: bigint,
|
|
289
|
+
includeUncommitted: boolean,
|
|
290
|
+
): Promise<
|
|
291
|
+
| {
|
|
292
|
+
/**
|
|
293
|
+
* The index of the found leaf.
|
|
294
|
+
*/
|
|
295
|
+
index: bigint;
|
|
296
|
+
/**
|
|
297
|
+
* A flag indicating if the corresponding leaf's value is equal to `newValue`.
|
|
298
|
+
*/
|
|
299
|
+
alreadyPresent: boolean;
|
|
300
|
+
}
|
|
301
|
+
| undefined
|
|
302
|
+
> {
|
|
303
|
+
return await this.synchronize(() =>
|
|
304
|
+
Promise.resolve(this.#getIndexedTree(treeId).findIndexOfPreviousKey(value, includeUncommitted)),
|
|
305
|
+
);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Gets the leaf data at a given index and tree.
|
|
310
|
+
* @param treeId - The ID of the tree get the leaf from.
|
|
311
|
+
* @param index - The index of the leaf to get.
|
|
312
|
+
* @param includeUncommitted - Indicates whether to include uncommitted data.
|
|
313
|
+
* @returns Leaf preimage.
|
|
314
|
+
*/
|
|
315
|
+
public async getLeafPreimage(
|
|
316
|
+
treeId: IndexedTreeId,
|
|
317
|
+
index: bigint,
|
|
318
|
+
includeUncommitted: boolean,
|
|
319
|
+
): Promise<IndexedTreeLeafPreimage | undefined> {
|
|
320
|
+
return await this.synchronize(() =>
|
|
321
|
+
Promise.resolve(this.#getIndexedTree(treeId).getLatestLeafPreimageCopy(index, includeUncommitted)),
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Returns the index of a leaf given its value, or undefined if no leaf with that value is found.
|
|
327
|
+
* @param treeId - The ID of the tree.
|
|
328
|
+
* @param value - The leaf value to look for.
|
|
329
|
+
* @param includeUncommitted - Indicates whether to include uncommitted data.
|
|
330
|
+
* @returns The index of the first leaf found with a given value (undefined if not found).
|
|
331
|
+
*/
|
|
332
|
+
public async findLeafIndex(
|
|
333
|
+
treeId: MerkleTreeId,
|
|
334
|
+
value: Buffer,
|
|
335
|
+
includeUncommitted: boolean,
|
|
336
|
+
): Promise<bigint | undefined> {
|
|
337
|
+
return await this.synchronize(() => {
|
|
338
|
+
const tree = this.trees[treeId];
|
|
339
|
+
return Promise.resolve(tree.findLeafIndex(value, includeUncommitted));
|
|
340
|
+
});
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/**
|
|
344
|
+
* Updates a leaf in a tree at a given index.
|
|
345
|
+
* @param treeId - The ID of the tree.
|
|
346
|
+
* @param leaf - The new leaf value.
|
|
347
|
+
* @param index - The index to insert into.
|
|
348
|
+
* @returns Empty promise.
|
|
349
|
+
*/
|
|
350
|
+
public async updateLeaf(treeId: IndexedTreeId, leaf: Buffer, index: bigint): Promise<void> {
|
|
351
|
+
return await this.synchronize(() => this.#updateLeaf(treeId, leaf, index));
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Handles a single L2 block (i.e. Inserts the new note hashes into the merkle tree).
|
|
356
|
+
* @param block - The L2 block to handle.
|
|
357
|
+
* @returns Whether the block handled was produced by this same node.
|
|
358
|
+
*/
|
|
359
|
+
public async handleL2Block(block: L2Block): Promise<HandleL2BlockResult> {
|
|
360
|
+
return await this.synchronize(() => this.#handleL2Block(block));
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/**
|
|
364
|
+
* Batch insert multiple leaves into the tree.
|
|
365
|
+
* @param treeId - The ID of the tree.
|
|
366
|
+
* @param leaves - Leaves to insert into the tree.
|
|
367
|
+
* @param subtreeHeight - Height of the subtree.
|
|
368
|
+
* @returns The data for the leaves to be updated when inserting the new ones.
|
|
369
|
+
*/
|
|
370
|
+
public async batchInsert<
|
|
371
|
+
TreeHeight extends number,
|
|
372
|
+
SubtreeHeight extends number,
|
|
373
|
+
SubtreeSiblingPathHeight extends number,
|
|
374
|
+
>(
|
|
375
|
+
treeId: MerkleTreeId,
|
|
376
|
+
leaves: Buffer[],
|
|
377
|
+
subtreeHeight: SubtreeHeight,
|
|
378
|
+
): Promise<BatchInsertionResult<TreeHeight, SubtreeSiblingPathHeight>> {
|
|
379
|
+
const tree = this.trees[treeId] as StandardIndexedTree;
|
|
380
|
+
if (!('batchInsert' in tree)) {
|
|
381
|
+
throw new Error('Tree does not support `batchInsert` method');
|
|
382
|
+
}
|
|
383
|
+
return await this.synchronize(() => tree.batchInsert(leaves, subtreeHeight));
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Waits for all jobs to finish before executing the given function.
|
|
388
|
+
* @param fn - The function to execute.
|
|
389
|
+
* @returns Promise containing the result of the function.
|
|
390
|
+
*/
|
|
391
|
+
private async synchronize<T>(fn: () => Promise<T>): Promise<T> {
|
|
392
|
+
return await this.jobQueue.put(fn);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async #updateArchive(header: Header, includeUncommitted: boolean) {
|
|
396
|
+
const state = await this.getStateReference(includeUncommitted);
|
|
397
|
+
|
|
398
|
+
// This method should be called only when the block builder already updated the state so we sanity check that it's
|
|
399
|
+
// the case here.
|
|
400
|
+
if (!state.toBuffer().equals(header.state.toBuffer())) {
|
|
401
|
+
throw new Error('State in header does not match current state');
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const blockHash = header.hash();
|
|
405
|
+
await this.#appendLeaves(MerkleTreeId.ARCHIVE, [blockHash.toBuffer()]);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Returns the tree info for the specified tree id.
|
|
410
|
+
* @param treeId - Id of the tree to get information from.
|
|
411
|
+
* @param includeUncommitted - Indicates whether to include uncommitted data.
|
|
412
|
+
* @returns The tree info for the specified tree.
|
|
413
|
+
*/
|
|
414
|
+
#getTreeInfo(treeId: MerkleTreeId, includeUncommitted: boolean): Promise<TreeInfo> {
|
|
415
|
+
const treeInfo = {
|
|
416
|
+
treeId,
|
|
417
|
+
root: this.trees[treeId].getRoot(includeUncommitted),
|
|
418
|
+
size: this.trees[treeId].getNumLeaves(includeUncommitted),
|
|
419
|
+
depth: this.trees[treeId].getDepth(),
|
|
420
|
+
} as TreeInfo;
|
|
421
|
+
return Promise.resolve(treeInfo);
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
/**
|
|
425
|
+
* Returns an instance of an indexed tree.
|
|
426
|
+
* @param treeId - Id of the tree to get an instance of.
|
|
427
|
+
* @returns The indexed tree for the specified tree id.
|
|
428
|
+
*/
|
|
429
|
+
#getIndexedTree(treeId: IndexedTreeId): IndexedTree {
|
|
430
|
+
return this.trees[treeId] as IndexedTree;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* Appends leaves to a tree.
|
|
435
|
+
* @param treeId - Id of the tree to append leaves to.
|
|
436
|
+
* @param leaves - Leaves to append.
|
|
437
|
+
* @returns Empty promise.
|
|
438
|
+
*/
|
|
439
|
+
async #appendLeaves(treeId: MerkleTreeId, leaves: Buffer[]): Promise<void> {
|
|
440
|
+
const tree = this.trees[treeId];
|
|
441
|
+
if (!('appendLeaves' in tree)) {
|
|
442
|
+
throw new Error('Tree does not support `appendLeaves` method');
|
|
443
|
+
}
|
|
444
|
+
return await tree.appendLeaves(leaves);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
async #updateLeaf(treeId: IndexedTreeId, leaf: Buffer, index: bigint): Promise<void> {
|
|
448
|
+
const tree = this.trees[treeId];
|
|
449
|
+
if (!('updateLeaf' in tree)) {
|
|
450
|
+
throw new Error('Tree does not support `updateLeaf` method');
|
|
451
|
+
}
|
|
452
|
+
return await tree.updateLeaf(leaf, index);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* Commits all pending updates.
|
|
457
|
+
* @returns Empty promise.
|
|
458
|
+
*/
|
|
459
|
+
async #commit(): Promise<void> {
|
|
460
|
+
for (const tree of this.trees) {
|
|
461
|
+
await tree.commit();
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Rolls back all pending updates.
|
|
467
|
+
* @returns Empty promise.
|
|
468
|
+
*/
|
|
469
|
+
async #rollback(): Promise<void> {
|
|
470
|
+
for (const tree of this.trees) {
|
|
471
|
+
await tree.rollback();
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
public getSnapshot(blockNumber: number) {
|
|
476
|
+
return Promise.all(this.trees.map(tree => tree.getSnapshot(blockNumber)));
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
async #snapshot(blockNumber: number): Promise<void> {
|
|
480
|
+
for (const tree of this.trees) {
|
|
481
|
+
await tree.snapshot(blockNumber);
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/**
|
|
486
|
+
* Handles a single L2 block (i.e. Inserts the new note hashes into the merkle tree).
|
|
487
|
+
* @param l2Block - The L2 block to handle.
|
|
488
|
+
*/
|
|
489
|
+
async #handleL2Block(l2Block: L2Block): Promise<HandleL2BlockResult> {
|
|
490
|
+
const treeRootWithIdPairs = [
|
|
491
|
+
[l2Block.header.state.partial.contractTree.root, MerkleTreeId.CONTRACT_TREE],
|
|
492
|
+
[l2Block.header.state.partial.nullifierTree.root, MerkleTreeId.NULLIFIER_TREE],
|
|
493
|
+
[l2Block.header.state.partial.noteHashTree.root, MerkleTreeId.NOTE_HASH_TREE],
|
|
494
|
+
[l2Block.header.state.partial.publicDataTree.root, MerkleTreeId.PUBLIC_DATA_TREE],
|
|
495
|
+
[l2Block.header.state.l1ToL2MessageTree.root, MerkleTreeId.L1_TO_L2_MESSAGE_TREE],
|
|
496
|
+
[l2Block.archive.root, MerkleTreeId.ARCHIVE],
|
|
497
|
+
] as const;
|
|
498
|
+
const compareRoot = (root: Fr, treeId: MerkleTreeId) => {
|
|
499
|
+
const treeRoot = this.trees[treeId].getRoot(true);
|
|
500
|
+
return treeRoot.equals(root.toBuffer());
|
|
501
|
+
};
|
|
502
|
+
const ourBlock = treeRootWithIdPairs.every(([root, id]) => compareRoot(root, id));
|
|
503
|
+
if (ourBlock) {
|
|
504
|
+
this.log(`Block ${l2Block.number} is ours, committing world state`);
|
|
505
|
+
await this.#commit();
|
|
506
|
+
} else {
|
|
507
|
+
this.log(`Block ${l2Block.number} is not ours, rolling back world state and committing state from chain`);
|
|
508
|
+
await this.#rollback();
|
|
509
|
+
|
|
510
|
+
// Sync the append only trees
|
|
511
|
+
for (const [tree, leaves] of [
|
|
512
|
+
[MerkleTreeId.CONTRACT_TREE, l2Block.body.txEffects.flatMap(txEffect => txEffect.contractLeaves)],
|
|
513
|
+
[MerkleTreeId.NOTE_HASH_TREE, l2Block.body.txEffects.flatMap(txEffect => txEffect.noteHashes)],
|
|
514
|
+
[MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l2Block.body.l1ToL2Messages],
|
|
515
|
+
] as const) {
|
|
516
|
+
await this.#appendLeaves(
|
|
517
|
+
tree,
|
|
518
|
+
leaves.map(fr => fr.toBuffer()),
|
|
519
|
+
);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// Sync the indexed trees
|
|
523
|
+
await (this.trees[MerkleTreeId.NULLIFIER_TREE] as StandardIndexedTree).batchInsert(
|
|
524
|
+
l2Block.body.txEffects.flatMap(txEffect => txEffect.nullifiers.map(nullifier => nullifier.toBuffer())),
|
|
525
|
+
NULLIFIER_SUBTREE_HEIGHT,
|
|
526
|
+
);
|
|
527
|
+
|
|
528
|
+
const publicDataTree = this.trees[MerkleTreeId.PUBLIC_DATA_TREE] as StandardIndexedTree;
|
|
529
|
+
|
|
530
|
+
const publicDataWrites = l2Block.body.txEffects.flatMap(txEffect => txEffect.publicDataWrites);
|
|
531
|
+
|
|
532
|
+
// We insert the public data tree leaves with one batch per tx to avoid updating the same key twice
|
|
533
|
+
for (let i = 0; i < publicDataWrites.length / MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX; i++) {
|
|
534
|
+
await publicDataTree.batchInsert(
|
|
535
|
+
publicDataWrites
|
|
536
|
+
.slice(MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX * i, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX * (i + 1))
|
|
537
|
+
.map(write => new PublicDataTreeLeaf(write.leafIndex, write.newValue).toBuffer()),
|
|
538
|
+
PUBLIC_DATA_SUBTREE_HEIGHT,
|
|
539
|
+
);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// The last thing remaining is to update the archive
|
|
543
|
+
await this.#updateArchive(l2Block.header, true);
|
|
544
|
+
|
|
545
|
+
await this.#commit();
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
for (const [root, treeId] of treeRootWithIdPairs) {
|
|
549
|
+
const treeName = MerkleTreeId[treeId];
|
|
550
|
+
const info = await this.#getTreeInfo(treeId, false);
|
|
551
|
+
const syncedStr = '0x' + info.root.toString('hex');
|
|
552
|
+
const rootStr = root.toString();
|
|
553
|
+
// Sanity check that the rebuilt trees match the roots published by the L2 block
|
|
554
|
+
if (!info.root.equals(root.toBuffer())) {
|
|
555
|
+
throw new Error(
|
|
556
|
+
`Synced tree root ${treeName} does not match published L2 block root: ${syncedStr} != ${rootStr}`,
|
|
557
|
+
);
|
|
558
|
+
} else {
|
|
559
|
+
this.log(`Tree ${treeName} synched with size ${info.size} root ${rootStr}`);
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
await this.#snapshot(l2Block.number);
|
|
563
|
+
|
|
564
|
+
return { isBlockOurs: ourBlock };
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
#isDbPopulated(): boolean {
|
|
568
|
+
try {
|
|
569
|
+
getTreeMeta(this.store, MerkleTreeId[MerkleTreeId.NULLIFIER_TREE]);
|
|
570
|
+
// Tree meta was found --> db is populated
|
|
571
|
+
return true;
|
|
572
|
+
} catch (e) {
|
|
573
|
+
// Tree meta was not found --> db is not populated
|
|
574
|
+
return false;
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|