@aztec/world-state 0.0.0-test.1 → 0.0.1-commit.1142ef1
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/index.d.ts +1 -1
- package/dest/instrumentation/instrumentation.d.ts +6 -4
- package/dest/instrumentation/instrumentation.d.ts.map +1 -1
- package/dest/instrumentation/instrumentation.js +19 -42
- package/dest/native/bench_metrics.d.ts +23 -0
- package/dest/native/bench_metrics.d.ts.map +1 -0
- package/dest/native/bench_metrics.js +81 -0
- package/dest/native/fork_checkpoint.d.ts +1 -1
- package/dest/native/fork_checkpoint.d.ts.map +1 -1
- package/dest/native/index.d.ts +1 -1
- package/dest/native/merkle_trees_facade.d.ts +19 -7
- package/dest/native/merkle_trees_facade.d.ts.map +1 -1
- package/dest/native/merkle_trees_facade.js +64 -11
- package/dest/native/message.d.ts +72 -51
- package/dest/native/message.d.ts.map +1 -1
- package/dest/native/message.js +61 -61
- package/dest/native/native_world_state.d.ts +28 -20
- package/dest/native/native_world_state.d.ts.map +1 -1
- package/dest/native/native_world_state.js +97 -36
- package/dest/native/native_world_state_instance.d.ts +20 -4
- package/dest/native/native_world_state_instance.d.ts.map +1 -1
- package/dest/native/native_world_state_instance.js +42 -3
- package/dest/native/world_state_ops_queue.d.ts +1 -1
- package/dest/native/world_state_ops_queue.d.ts.map +1 -1
- package/dest/native/world_state_ops_queue.js +1 -1
- package/dest/synchronizer/config.d.ts +12 -2
- package/dest/synchronizer/config.d.ts.map +1 -1
- package/dest/synchronizer/config.js +26 -1
- package/dest/synchronizer/errors.d.ts +4 -0
- package/dest/synchronizer/errors.d.ts.map +1 -0
- package/dest/synchronizer/errors.js +5 -0
- package/dest/synchronizer/factory.d.ts +9 -2
- package/dest/synchronizer/factory.d.ts.map +1 -1
- package/dest/synchronizer/factory.js +9 -4
- package/dest/synchronizer/index.d.ts +1 -1
- package/dest/synchronizer/server_world_state_synchronizer.d.ts +21 -30
- package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -1
- package/dest/synchronizer/server_world_state_synchronizer.js +130 -78
- package/dest/test/index.d.ts +1 -1
- package/dest/test/utils.d.ts +16 -9
- package/dest/test/utils.d.ts.map +1 -1
- package/dest/test/utils.js +56 -49
- package/dest/testing.d.ts +3 -3
- package/dest/testing.d.ts.map +1 -1
- package/dest/testing.js +7 -11
- package/dest/world-state-db/index.d.ts +1 -1
- package/dest/world-state-db/merkle_tree_db.d.ts +14 -11
- package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -1
- package/package.json +24 -24
- package/src/instrumentation/instrumentation.ts +24 -44
- package/src/native/bench_metrics.ts +91 -0
- package/src/native/merkle_trees_facade.ts +73 -17
- package/src/native/message.ts +92 -73
- package/src/native/native_world_state.ts +118 -50
- package/src/native/native_world_state_instance.ts +59 -8
- package/src/native/world_state_ops_queue.ts +1 -1
- package/src/synchronizer/config.ts +47 -2
- package/src/synchronizer/errors.ts +5 -0
- package/src/synchronizer/factory.ts +31 -8
- package/src/synchronizer/server_world_state_synchronizer.ts +160 -105
- package/src/test/utils.ts +94 -84
- package/src/testing.ts +4 -8
- package/src/world-state-db/merkle_tree_db.ts +18 -10
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import
|
|
3
|
-
import {
|
|
1
|
+
import { GENESIS_BLOCK_HEADER_HASH, INITIAL_L2_BLOCK_NUM, INITIAL_L2_CHECKPOINT_NUM } from '@aztec/constants';
|
|
2
|
+
import { BlockNumber } from '@aztec/foundation/branded-types';
|
|
3
|
+
import type { Fr } from '@aztec/foundation/curves/bn254';
|
|
4
|
+
import { type Logger, createLogger } from '@aztec/foundation/log';
|
|
4
5
|
import { promiseWithResolvers } from '@aztec/foundation/promise';
|
|
5
6
|
import { elapsed } from '@aztec/foundation/timer';
|
|
6
|
-
import {
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
L2BlockSource,
|
|
7
|
+
import {
|
|
8
|
+
GENESIS_CHECKPOINT_HEADER_HASH,
|
|
9
|
+
type L2BlockId,
|
|
10
|
+
type L2BlockNew,
|
|
11
|
+
type L2BlockSource,
|
|
12
12
|
L2BlockStream,
|
|
13
|
-
L2BlockStreamEvent,
|
|
14
|
-
L2BlockStreamEventHandler,
|
|
15
|
-
L2BlockStreamLocalDataProvider,
|
|
16
|
-
L2Tips,
|
|
13
|
+
type L2BlockStreamEvent,
|
|
14
|
+
type L2BlockStreamEventHandler,
|
|
15
|
+
type L2BlockStreamLocalDataProvider,
|
|
16
|
+
type L2Tips,
|
|
17
17
|
} from '@aztec/stdlib/block';
|
|
18
18
|
import {
|
|
19
19
|
WorldStateRunningState,
|
|
@@ -22,14 +22,18 @@ import {
|
|
|
22
22
|
type WorldStateSynchronizerStatus,
|
|
23
23
|
} from '@aztec/stdlib/interfaces/server';
|
|
24
24
|
import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
|
|
25
|
+
import type { SnapshotDataKeys } from '@aztec/stdlib/snapshots';
|
|
25
26
|
import type { L2BlockHandledStats } from '@aztec/stdlib/stats';
|
|
26
27
|
import { MerkleTreeId, type MerkleTreeReadOperations, type MerkleTreeWriteOperations } from '@aztec/stdlib/trees';
|
|
27
|
-
import {
|
|
28
|
+
import { getTelemetryClient } from '@aztec/telemetry-client';
|
|
28
29
|
|
|
29
30
|
import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js';
|
|
30
31
|
import type { WorldStateStatusFull } from '../native/message.js';
|
|
31
32
|
import type { MerkleTreeAdminDatabase } from '../world-state-db/merkle_tree_db.js';
|
|
32
33
|
import type { WorldStateConfig } from './config.js';
|
|
34
|
+
import { WorldStateSynchronizerError } from './errors.js';
|
|
35
|
+
|
|
36
|
+
export type { SnapshotDataKeys };
|
|
33
37
|
|
|
34
38
|
/**
|
|
35
39
|
* Synchronizes the world state with the L2 blocks from a L2BlockSource via a block stream.
|
|
@@ -41,20 +45,24 @@ export class ServerWorldStateSynchronizer
|
|
|
41
45
|
{
|
|
42
46
|
private readonly merkleTreeCommitted: MerkleTreeReadOperations;
|
|
43
47
|
|
|
44
|
-
private latestBlockNumberAtStart =
|
|
48
|
+
private latestBlockNumberAtStart = BlockNumber.ZERO;
|
|
45
49
|
private historyToKeep: number | undefined;
|
|
46
50
|
private currentState: WorldStateRunningState = WorldStateRunningState.IDLE;
|
|
47
|
-
private latestBlockHashQuery: { blockNumber:
|
|
51
|
+
private latestBlockHashQuery: { blockNumber: BlockNumber; hash: string | undefined } | undefined = undefined;
|
|
48
52
|
|
|
49
53
|
private syncPromise = promiseWithResolvers<void>();
|
|
50
54
|
protected blockStream: L2BlockStream | undefined;
|
|
51
55
|
|
|
56
|
+
// WorldState doesn't track the proven block number, it only tracks the latest tips of the pending chain and the finalized chain
|
|
57
|
+
// store the proven block number here, in the synchronizer, so that we don't end up spamming the logs with 'chain-proved' events
|
|
58
|
+
private provenBlockNumber: BlockNumber | undefined;
|
|
59
|
+
|
|
52
60
|
constructor(
|
|
53
61
|
private readonly merkleTreeDb: MerkleTreeAdminDatabase,
|
|
54
62
|
private readonly l2BlockSource: L2BlockSource & L1ToL2MessageSource,
|
|
55
63
|
private readonly config: WorldStateConfig,
|
|
56
64
|
private instrumentation = new WorldStateInstrumentation(getTelemetryClient()),
|
|
57
|
-
private readonly log = createLogger('world_state'),
|
|
65
|
+
private readonly log: Logger = createLogger('world_state'),
|
|
58
66
|
) {
|
|
59
67
|
this.merkleTreeCommitted = this.merkleTreeDb.getCommitted();
|
|
60
68
|
this.historyToKeep = config.worldStateBlockHistory < 1 ? undefined : config.worldStateBlockHistory;
|
|
@@ -69,12 +77,20 @@ export class ServerWorldStateSynchronizer
|
|
|
69
77
|
return this.merkleTreeDb.getCommitted();
|
|
70
78
|
}
|
|
71
79
|
|
|
72
|
-
public getSnapshot(blockNumber:
|
|
80
|
+
public getSnapshot(blockNumber: BlockNumber): MerkleTreeReadOperations {
|
|
73
81
|
return this.merkleTreeDb.getSnapshot(blockNumber);
|
|
74
82
|
}
|
|
75
83
|
|
|
76
|
-
public fork(blockNumber?: number): Promise<MerkleTreeWriteOperations> {
|
|
77
|
-
return this.merkleTreeDb.fork(blockNumber);
|
|
84
|
+
public fork(blockNumber?: BlockNumber, opts?: { closeDelayMs?: number }): Promise<MerkleTreeWriteOperations> {
|
|
85
|
+
return this.merkleTreeDb.fork(blockNumber, opts);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
public backupTo(dstPath: string, compact?: boolean): Promise<Record<Exclude<SnapshotDataKeys, 'archiver'>, string>> {
|
|
89
|
+
return this.merkleTreeDb.backupTo(dstPath, compact);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
public clear(): Promise<void> {
|
|
93
|
+
return this.merkleTreeDb.clear();
|
|
78
94
|
}
|
|
79
95
|
|
|
80
96
|
public async start() {
|
|
@@ -86,9 +102,11 @@ export class ServerWorldStateSynchronizer
|
|
|
86
102
|
}
|
|
87
103
|
|
|
88
104
|
// Get the current latest block number
|
|
89
|
-
this.latestBlockNumberAtStart =
|
|
90
|
-
|
|
91
|
-
|
|
105
|
+
this.latestBlockNumberAtStart = BlockNumber(
|
|
106
|
+
await (this.config.worldStateProvenBlocksOnly
|
|
107
|
+
? this.l2BlockSource.getProvenBlockNumber()
|
|
108
|
+
: this.l2BlockSource.getBlockNumber()),
|
|
109
|
+
);
|
|
92
110
|
|
|
93
111
|
const blockToDownloadFrom = (await this.getLatestBlockNumber()) + 1;
|
|
94
112
|
|
|
@@ -110,12 +128,12 @@ export class ServerWorldStateSynchronizer
|
|
|
110
128
|
}
|
|
111
129
|
|
|
112
130
|
protected createBlockStream(): L2BlockStream {
|
|
113
|
-
const tracer = this.instrumentation.telemetry.getTracer('WorldStateL2BlockStream');
|
|
114
131
|
const logger = createLogger('world-state:block_stream');
|
|
115
|
-
return new
|
|
132
|
+
return new L2BlockStream(this.l2BlockSource, this, this, logger, {
|
|
116
133
|
proven: this.config.worldStateProvenBlocksOnly,
|
|
117
134
|
pollIntervalMS: this.config.worldStateBlockCheckIntervalMS,
|
|
118
135
|
batchSize: this.config.worldStateBlockRequestBatchSize,
|
|
136
|
+
ignoreCheckpoints: true,
|
|
119
137
|
});
|
|
120
138
|
}
|
|
121
139
|
|
|
@@ -131,10 +149,10 @@ export class ServerWorldStateSynchronizer
|
|
|
131
149
|
public async status(): Promise<WorldStateSynchronizerStatus> {
|
|
132
150
|
const summary = await this.merkleTreeDb.getStatusSummary();
|
|
133
151
|
const status: WorldStateSyncStatus = {
|
|
134
|
-
latestBlockNumber:
|
|
135
|
-
latestBlockHash: (await this.getL2BlockHash(
|
|
136
|
-
|
|
137
|
-
oldestHistoricBlockNumber:
|
|
152
|
+
latestBlockNumber: summary.unfinalizedBlockNumber,
|
|
153
|
+
latestBlockHash: (await this.getL2BlockHash(summary.unfinalizedBlockNumber)) ?? '',
|
|
154
|
+
finalizedBlockNumber: summary.finalizedBlockNumber,
|
|
155
|
+
oldestHistoricBlockNumber: summary.oldestHistoricalBlock,
|
|
138
156
|
treesAreSynched: summary.treesAreSynched,
|
|
139
157
|
};
|
|
140
158
|
return {
|
|
@@ -144,19 +162,42 @@ export class ServerWorldStateSynchronizer
|
|
|
144
162
|
}
|
|
145
163
|
|
|
146
164
|
public async getLatestBlockNumber() {
|
|
147
|
-
return (await this.getL2Tips()).
|
|
165
|
+
return (await this.getL2Tips()).proposed.number;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
public async stopSync() {
|
|
169
|
+
this.log.debug('Stopping sync...');
|
|
170
|
+
await this.blockStream?.stop();
|
|
171
|
+
this.log.info('Stopped sync');
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
public resumeSync() {
|
|
175
|
+
if (!this.blockStream) {
|
|
176
|
+
throw new Error('Cannot resume sync as block stream is not initialized');
|
|
177
|
+
}
|
|
178
|
+
this.log.debug('Resuming sync...');
|
|
179
|
+
this.blockStream.start();
|
|
180
|
+
this.log.info('Resumed sync');
|
|
148
181
|
}
|
|
149
182
|
|
|
150
183
|
/**
|
|
151
184
|
* Forces an immediate sync.
|
|
152
|
-
* @param targetBlockNumber - The target block number that we must sync to. Will download unproven blocks if needed to reach it.
|
|
185
|
+
* @param targetBlockNumber - The target block number that we must sync to. Will download unproven blocks if needed to reach it.
|
|
186
|
+
* @param skipThrowIfTargetNotReached - Whether to skip throwing if the target block number is not reached.
|
|
153
187
|
* @returns A promise that resolves with the block number the world state was synced to
|
|
154
188
|
*/
|
|
155
|
-
public async syncImmediate(
|
|
156
|
-
|
|
189
|
+
public async syncImmediate(
|
|
190
|
+
targetBlockNumber?: BlockNumber,
|
|
191
|
+
skipThrowIfTargetNotReached?: boolean,
|
|
192
|
+
): Promise<BlockNumber> {
|
|
193
|
+
if (this.currentState !== WorldStateRunningState.RUNNING) {
|
|
157
194
|
throw new Error(`World State is not running. Unable to perform sync.`);
|
|
158
195
|
}
|
|
159
196
|
|
|
197
|
+
if (this.blockStream === undefined) {
|
|
198
|
+
throw new Error('Block stream is not initialized. Unable to perform sync.');
|
|
199
|
+
}
|
|
200
|
+
|
|
160
201
|
// If we have been given a block number to sync to and we have reached that number then return
|
|
161
202
|
const currentBlockNumber = await this.getLatestBlockNumber();
|
|
162
203
|
if (targetBlockNumber !== undefined && targetBlockNumber <= currentBlockNumber) {
|
|
@@ -164,21 +205,40 @@ export class ServerWorldStateSynchronizer
|
|
|
164
205
|
}
|
|
165
206
|
this.log.debug(`World State at ${currentBlockNumber} told to sync to ${targetBlockNumber ?? 'latest'}`);
|
|
166
207
|
|
|
208
|
+
// If the archiver is behind the target block, force an archiver sync
|
|
209
|
+
if (targetBlockNumber) {
|
|
210
|
+
const archiverLatestBlock = BlockNumber(await this.l2BlockSource.getBlockNumber());
|
|
211
|
+
if (archiverLatestBlock < targetBlockNumber) {
|
|
212
|
+
this.log.debug(`Archiver is at ${archiverLatestBlock} behind target block ${targetBlockNumber}.`);
|
|
213
|
+
await this.l2BlockSource.syncImmediate();
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
167
217
|
// Force the block stream to sync against the archiver now
|
|
168
218
|
await this.blockStream.sync();
|
|
169
219
|
|
|
170
220
|
// If we have been given a block number to sync to and we have not reached that number then fail
|
|
171
221
|
const updatedBlockNumber = await this.getLatestBlockNumber();
|
|
172
|
-
if (targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
|
|
173
|
-
throw new
|
|
222
|
+
if (!skipThrowIfTargetNotReached && targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
|
|
223
|
+
throw new WorldStateSynchronizerError(
|
|
224
|
+
`Unable to sync to block number ${targetBlockNumber} (last synced is ${updatedBlockNumber})`,
|
|
225
|
+
{
|
|
226
|
+
cause: {
|
|
227
|
+
reason: 'block_not_available',
|
|
228
|
+
previousBlockNumber: currentBlockNumber,
|
|
229
|
+
updatedBlockNumber,
|
|
230
|
+
targetBlockNumber,
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
);
|
|
174
234
|
}
|
|
175
235
|
|
|
176
236
|
return updatedBlockNumber;
|
|
177
237
|
}
|
|
178
238
|
|
|
179
239
|
/** Returns the L2 block hash for a given number. Used by the L2BlockStream for detecting reorgs. */
|
|
180
|
-
public async getL2BlockHash(number:
|
|
181
|
-
if (number ===
|
|
240
|
+
public async getL2BlockHash(number: BlockNumber): Promise<string | undefined> {
|
|
241
|
+
if (number === BlockNumber.ZERO) {
|
|
182
242
|
return (await this.merkleTreeCommitted.getInitialHeader().hash()).toString();
|
|
183
243
|
}
|
|
184
244
|
if (this.latestBlockHashQuery?.hash === undefined || number !== this.latestBlockHashQuery.blockNumber) {
|
|
@@ -195,35 +255,45 @@ export class ServerWorldStateSynchronizer
|
|
|
195
255
|
/** Returns the latest L2 block number for each tip of the chain (latest, proven, finalized). */
|
|
196
256
|
public async getL2Tips(): Promise<L2Tips> {
|
|
197
257
|
const status = await this.merkleTreeDb.getStatusSummary();
|
|
198
|
-
const
|
|
199
|
-
const latestBlockId: L2BlockId = { number:
|
|
258
|
+
const unfinalizedBlockHash = await this.getL2BlockHash(status.unfinalizedBlockNumber);
|
|
259
|
+
const latestBlockId: L2BlockId = { number: status.unfinalizedBlockNumber, hash: unfinalizedBlockHash! };
|
|
200
260
|
|
|
261
|
+
// World state doesn't track checkpointed blocks or checkpoints themselves.
|
|
262
|
+
// but we use a block stream so we need to provide 'local' L2Tips.
|
|
263
|
+
// We configure the block stream to ignore checkpoints and set checkpoint values to genesis here.
|
|
264
|
+
const genesisCheckpointHeaderHash = GENESIS_CHECKPOINT_HEADER_HASH.toString();
|
|
201
265
|
return {
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
266
|
+
proposed: latestBlockId,
|
|
267
|
+
checkpointed: {
|
|
268
|
+
block: { number: INITIAL_L2_BLOCK_NUM, hash: GENESIS_BLOCK_HEADER_HASH.toString() },
|
|
269
|
+
checkpoint: { number: INITIAL_L2_CHECKPOINT_NUM, hash: genesisCheckpointHeaderHash },
|
|
270
|
+
},
|
|
271
|
+
finalized: {
|
|
272
|
+
block: { number: status.finalizedBlockNumber, hash: '' },
|
|
273
|
+
checkpoint: { number: INITIAL_L2_CHECKPOINT_NUM, hash: genesisCheckpointHeaderHash },
|
|
274
|
+
},
|
|
275
|
+
proven: {
|
|
276
|
+
block: { number: this.provenBlockNumber ?? status.finalizedBlockNumber, hash: '' },
|
|
277
|
+
checkpoint: { number: INITIAL_L2_CHECKPOINT_NUM, hash: genesisCheckpointHeaderHash },
|
|
278
|
+
}, // TODO(palla/reorg): Using finalized as proven for now
|
|
205
279
|
};
|
|
206
280
|
}
|
|
207
281
|
|
|
208
282
|
/** Handles an event emitted by the block stream. */
|
|
209
283
|
public async handleBlockStreamEvent(event: L2BlockStreamEvent): Promise<void> {
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
break;
|
|
224
|
-
}
|
|
225
|
-
} catch (err) {
|
|
226
|
-
this.log.error('Error processing block stream', err);
|
|
284
|
+
switch (event.type) {
|
|
285
|
+
case 'blocks-added':
|
|
286
|
+
await this.handleL2Blocks(event.blocks);
|
|
287
|
+
break;
|
|
288
|
+
case 'chain-pruned':
|
|
289
|
+
await this.handleChainPruned(event.block.number);
|
|
290
|
+
break;
|
|
291
|
+
case 'chain-proven':
|
|
292
|
+
await this.handleChainProven(event.block.number);
|
|
293
|
+
break;
|
|
294
|
+
case 'chain-finalized':
|
|
295
|
+
await this.handleChainFinalized(event.block.number);
|
|
296
|
+
break;
|
|
227
297
|
}
|
|
228
298
|
}
|
|
229
299
|
|
|
@@ -232,22 +302,32 @@ export class ServerWorldStateSynchronizer
|
|
|
232
302
|
* @param l2Blocks - The L2 blocks to handle.
|
|
233
303
|
* @returns Whether the block handled was produced by this same node.
|
|
234
304
|
*/
|
|
235
|
-
private async handleL2Blocks(l2Blocks:
|
|
305
|
+
private async handleL2Blocks(l2Blocks: L2BlockNew[]) {
|
|
236
306
|
this.log.trace(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1)!.number}`);
|
|
237
307
|
|
|
238
|
-
|
|
239
|
-
const
|
|
240
|
-
|
|
308
|
+
// Fetch the L1->L2 messages for the first block in a checkpoint.
|
|
309
|
+
const messagesForBlocks = new Map<BlockNumber, Fr[]>();
|
|
310
|
+
await Promise.all(
|
|
311
|
+
l2Blocks
|
|
312
|
+
.filter(b => b.indexWithinCheckpoint === 0)
|
|
313
|
+
.map(async block => {
|
|
314
|
+
const l1ToL2Messages = await this.l2BlockSource.getL1ToL2Messages(block.checkpointNumber);
|
|
315
|
+
messagesForBlocks.set(block.number, l1ToL2Messages);
|
|
316
|
+
}),
|
|
317
|
+
);
|
|
241
318
|
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
319
|
+
let updateStatus: WorldStateStatusFull | undefined = undefined;
|
|
320
|
+
for (const block of l2Blocks) {
|
|
321
|
+
const [duration, result] = await elapsed(() =>
|
|
322
|
+
this.handleL2Block(block, messagesForBlocks.get(block.number) ?? []),
|
|
323
|
+
);
|
|
324
|
+
this.log.info(`World state updated with L2 block ${block.number}`, {
|
|
245
325
|
eventName: 'l2-block-handled',
|
|
246
326
|
duration,
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
oldestHistoricBlock: result.summary.oldestHistoricalBlock,
|
|
250
|
-
...
|
|
327
|
+
unfinalizedBlockNumber: BigInt(result.summary.unfinalizedBlockNumber),
|
|
328
|
+
finalizedBlockNumber: BigInt(result.summary.finalizedBlockNumber),
|
|
329
|
+
oldestHistoricBlock: BigInt(result.summary.oldestHistoricalBlock),
|
|
330
|
+
...block.getStats(),
|
|
251
331
|
} satisfies L2BlockHandledStats);
|
|
252
332
|
updateStatus = result;
|
|
253
333
|
}
|
|
@@ -263,14 +343,7 @@ export class ServerWorldStateSynchronizer
|
|
|
263
343
|
* @param l1ToL2Messages - The L1 to L2 messages for the block.
|
|
264
344
|
* @returns Whether the block handled was produced by this same node.
|
|
265
345
|
*/
|
|
266
|
-
private async handleL2Block(l2Block:
|
|
267
|
-
// First we check that the L1 to L2 messages hash to the block inHash.
|
|
268
|
-
// Note that we cannot optimize this check by checking the root of the subtree after inserting the messages
|
|
269
|
-
// to the real L1_TO_L2_MESSAGE_TREE (like we do in merkleTreeDb.handleL2BlockAndMessages(...)) because that
|
|
270
|
-
// tree uses pedersen and we don't have access to the converted root.
|
|
271
|
-
await this.verifyMessagesHashToInHash(l1ToL2Messages, l2Block.header.contentCommitment.inHash);
|
|
272
|
-
|
|
273
|
-
// If the above check succeeds, we can proceed to handle the block.
|
|
346
|
+
private async handleL2Block(l2Block: L2BlockNew, l1ToL2Messages: Fr[]): Promise<WorldStateStatusFull> {
|
|
274
347
|
this.log.trace(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
|
|
275
348
|
blockNumber: l2Block.number,
|
|
276
349
|
blockHash: await l2Block.hash().then(h => h.toString()),
|
|
@@ -286,30 +359,32 @@ export class ServerWorldStateSynchronizer
|
|
|
286
359
|
return result;
|
|
287
360
|
}
|
|
288
361
|
|
|
289
|
-
private async handleChainFinalized(blockNumber:
|
|
362
|
+
private async handleChainFinalized(blockNumber: BlockNumber) {
|
|
290
363
|
this.log.verbose(`Finalized chain is now at block ${blockNumber}`);
|
|
291
|
-
const summary = await this.merkleTreeDb.
|
|
364
|
+
const summary = await this.merkleTreeDb.setFinalized(blockNumber);
|
|
292
365
|
if (this.historyToKeep === undefined) {
|
|
293
366
|
return;
|
|
294
367
|
}
|
|
295
|
-
const newHistoricBlock = summary.
|
|
368
|
+
const newHistoricBlock = summary.finalizedBlockNumber - this.historyToKeep + 1;
|
|
296
369
|
if (newHistoricBlock <= 1) {
|
|
297
370
|
return;
|
|
298
371
|
}
|
|
299
372
|
this.log.verbose(`Pruning historic blocks to ${newHistoricBlock}`);
|
|
300
|
-
const status = await this.merkleTreeDb.removeHistoricalBlocks(newHistoricBlock);
|
|
373
|
+
const status = await this.merkleTreeDb.removeHistoricalBlocks(BlockNumber(newHistoricBlock));
|
|
301
374
|
this.log.debug(`World state summary `, status.summary);
|
|
302
375
|
}
|
|
303
376
|
|
|
304
|
-
private handleChainProven(blockNumber:
|
|
377
|
+
private handleChainProven(blockNumber: BlockNumber) {
|
|
378
|
+
this.provenBlockNumber = blockNumber;
|
|
305
379
|
this.log.debug(`Proven chain is now at block ${blockNumber}`);
|
|
306
380
|
return Promise.resolve();
|
|
307
381
|
}
|
|
308
382
|
|
|
309
|
-
private async handleChainPruned(blockNumber:
|
|
383
|
+
private async handleChainPruned(blockNumber: BlockNumber) {
|
|
310
384
|
this.log.warn(`Chain pruned to block ${blockNumber}`);
|
|
311
|
-
const status = await this.merkleTreeDb.unwindBlocks(
|
|
385
|
+
const status = await this.merkleTreeDb.unwindBlocks(blockNumber);
|
|
312
386
|
this.latestBlockHashQuery = undefined;
|
|
387
|
+
this.provenBlockNumber = undefined;
|
|
313
388
|
this.instrumentation.updateWorldStateMetrics(status);
|
|
314
389
|
}
|
|
315
390
|
|
|
@@ -321,24 +396,4 @@ export class ServerWorldStateSynchronizer
|
|
|
321
396
|
this.currentState = newState;
|
|
322
397
|
this.log.debug(`Moved to state ${WorldStateRunningState[this.currentState]}`);
|
|
323
398
|
}
|
|
324
|
-
|
|
325
|
-
/**
|
|
326
|
-
* Verifies that the L1 to L2 messages hash to the block inHash.
|
|
327
|
-
* @param l1ToL2Messages - The L1 to L2 messages for the block.
|
|
328
|
-
* @param inHash - The inHash of the block.
|
|
329
|
-
* @throws If the L1 to L2 messages do not hash to the block inHash.
|
|
330
|
-
*/
|
|
331
|
-
protected async verifyMessagesHashToInHash(l1ToL2Messages: Fr[], inHash: Buffer) {
|
|
332
|
-
const treeCalculator = await MerkleTreeCalculator.create(
|
|
333
|
-
L1_TO_L2_MSG_SUBTREE_HEIGHT,
|
|
334
|
-
Buffer.alloc(32),
|
|
335
|
-
(lhs, rhs) => Promise.resolve(new SHA256Trunc().hash(lhs, rhs)),
|
|
336
|
-
);
|
|
337
|
-
|
|
338
|
-
const root = await treeCalculator.computeTreeRoot(l1ToL2Messages.map(msg => msg.toBuffer()));
|
|
339
|
-
|
|
340
|
-
if (!root.equals(inHash)) {
|
|
341
|
-
throw new Error('Obtained L1 to L2 messages failed to be hashed to the block inHash');
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
399
|
}
|
package/src/test/utils.ts
CHANGED
|
@@ -4,107 +4,100 @@ import {
|
|
|
4
4
|
NULLIFIER_SUBTREE_HEIGHT,
|
|
5
5
|
NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
|
|
6
6
|
} from '@aztec/constants';
|
|
7
|
+
import { asyncMap } from '@aztec/foundation/async-map';
|
|
8
|
+
import { BlockNumber, type CheckpointNumber } from '@aztec/foundation/branded-types';
|
|
7
9
|
import { padArrayEnd } from '@aztec/foundation/collection';
|
|
8
|
-
import { Fr } from '@aztec/foundation/
|
|
9
|
-
import {
|
|
10
|
-
import type {
|
|
10
|
+
import { Fr } from '@aztec/foundation/curves/bn254';
|
|
11
|
+
import { L2BlockNew } from '@aztec/stdlib/block';
|
|
12
|
+
import type {
|
|
13
|
+
IndexedTreeId,
|
|
14
|
+
MerkleTreeReadOperations,
|
|
15
|
+
MerkleTreeWriteOperations,
|
|
16
|
+
} from '@aztec/stdlib/interfaces/server';
|
|
17
|
+
import { mockCheckpointAndMessages, mockL1ToL2Messages } from '@aztec/stdlib/testing';
|
|
11
18
|
import { AppendOnlyTreeSnapshot, MerkleTreeId } from '@aztec/stdlib/trees';
|
|
19
|
+
import { BlockHeader } from '@aztec/stdlib/tx';
|
|
12
20
|
|
|
13
21
|
import type { NativeWorldStateService } from '../native/native_world_state.js';
|
|
14
22
|
|
|
15
|
-
export async function
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
await fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
|
|
25
|
-
|
|
26
|
-
const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
|
|
27
|
-
await fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
// Sync the indexed trees
|
|
31
|
-
{
|
|
32
|
-
// We insert the public data tree leaves with one batch per tx to avoid updating the same key twice
|
|
33
|
-
for (const txEffect of l2Block.body.txEffects) {
|
|
34
|
-
await fork.batchInsert(
|
|
35
|
-
MerkleTreeId.PUBLIC_DATA_TREE,
|
|
36
|
-
txEffect.publicDataWrites.map(write => write.toBuffer()),
|
|
37
|
-
0,
|
|
38
|
-
);
|
|
39
|
-
|
|
40
|
-
const nullifiersPadded = padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX);
|
|
41
|
-
|
|
42
|
-
await fork.batchInsert(
|
|
43
|
-
MerkleTreeId.NULLIFIER_TREE,
|
|
44
|
-
nullifiersPadded.map(nullifier => nullifier.toBuffer()),
|
|
45
|
-
NULLIFIER_SUBTREE_HEIGHT,
|
|
46
|
-
);
|
|
23
|
+
export async function updateBlockState(block: L2BlockNew, l1ToL2Messages: Fr[], fork: MerkleTreeWriteOperations) {
|
|
24
|
+
const insertData = async (
|
|
25
|
+
treeId: IndexedTreeId,
|
|
26
|
+
data: Buffer[][],
|
|
27
|
+
subTreeHeight: number,
|
|
28
|
+
fork: MerkleTreeWriteOperations,
|
|
29
|
+
) => {
|
|
30
|
+
for (const dataBatch of data) {
|
|
31
|
+
await fork.batchInsert(treeId, dataBatch, subTreeHeight);
|
|
47
32
|
}
|
|
48
|
-
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
const publicDataInsert = insertData(
|
|
36
|
+
MerkleTreeId.PUBLIC_DATA_TREE,
|
|
37
|
+
block.body.txEffects.map(txEffect => txEffect.publicDataWrites.map(write => write.toBuffer())),
|
|
38
|
+
0,
|
|
39
|
+
fork,
|
|
40
|
+
);
|
|
41
|
+
const nullifierInsert = insertData(
|
|
42
|
+
MerkleTreeId.NULLIFIER_TREE,
|
|
43
|
+
block.body.txEffects.map(txEffect =>
|
|
44
|
+
padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX).map(nullifier => nullifier.toBuffer()),
|
|
45
|
+
),
|
|
46
|
+
NULLIFIER_SUBTREE_HEIGHT,
|
|
47
|
+
fork,
|
|
48
|
+
);
|
|
49
|
+
const noteHashesPadded = block.body.txEffects.flatMap(txEffect =>
|
|
50
|
+
padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX),
|
|
51
|
+
);
|
|
52
|
+
|
|
53
|
+
const l1ToL2MessagesPadded =
|
|
54
|
+
block.indexWithinCheckpoint === 0
|
|
55
|
+
? padArrayEnd<Fr, number>(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP)
|
|
56
|
+
: l1ToL2Messages;
|
|
57
|
+
|
|
58
|
+
const noteHashInsert = fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
|
|
59
|
+
const messageInsert = fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
|
|
60
|
+
await Promise.all([publicDataInsert, nullifierInsert, noteHashInsert, messageInsert]);
|
|
49
61
|
|
|
50
62
|
const state = await fork.getStateReference();
|
|
51
|
-
|
|
52
|
-
await fork.updateArchive(
|
|
63
|
+
block.header = BlockHeader.from({ ...block.header, state });
|
|
64
|
+
await fork.updateArchive(block.header);
|
|
53
65
|
|
|
54
66
|
const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
|
|
55
67
|
|
|
56
|
-
|
|
68
|
+
block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export async function mockBlock(
|
|
72
|
+
blockNum: BlockNumber,
|
|
73
|
+
size: number,
|
|
74
|
+
fork: MerkleTreeWriteOperations,
|
|
75
|
+
maxEffects: number | undefined = 1000, // Defaults to the maximum tx effects.
|
|
76
|
+
numL1ToL2Messages: number = NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
|
|
77
|
+
isFirstBlockInCheckpoint: boolean = true,
|
|
78
|
+
) {
|
|
79
|
+
const block = await L2BlockNew.random(blockNum, {
|
|
80
|
+
indexWithinCheckpoint: isFirstBlockInCheckpoint ? 0 : 1,
|
|
81
|
+
txsPerBlock: size,
|
|
82
|
+
txOptions: { maxEffects },
|
|
83
|
+
});
|
|
84
|
+
const l1ToL2Messages = mockL1ToL2Messages(numL1ToL2Messages);
|
|
85
|
+
|
|
86
|
+
await updateBlockState(block, l1ToL2Messages, fork);
|
|
57
87
|
|
|
58
88
|
return {
|
|
59
|
-
block
|
|
89
|
+
block,
|
|
60
90
|
messages: l1ToL2Messages,
|
|
61
91
|
};
|
|
62
92
|
}
|
|
63
93
|
|
|
64
|
-
export async function mockEmptyBlock(blockNum:
|
|
65
|
-
const l2Block =
|
|
94
|
+
export async function mockEmptyBlock(blockNum: BlockNumber, fork: MerkleTreeWriteOperations) {
|
|
95
|
+
const l2Block = L2BlockNew.empty();
|
|
66
96
|
const l1ToL2Messages = Array(16).fill(0).map(Fr.zero);
|
|
67
97
|
|
|
68
|
-
l2Block.header.globalVariables.blockNumber =
|
|
98
|
+
l2Block.header.globalVariables.blockNumber = blockNum;
|
|
69
99
|
|
|
70
|
-
|
|
71
|
-
{
|
|
72
|
-
const noteHashesPadded = l2Block.body.txEffects.flatMap(txEffect =>
|
|
73
|
-
padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX),
|
|
74
|
-
);
|
|
75
|
-
await fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
|
|
76
|
-
|
|
77
|
-
const l1ToL2MessagesPadded = padArrayEnd(l1ToL2Messages, Fr.ZERO, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP);
|
|
78
|
-
await fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// Sync the indexed trees
|
|
82
|
-
{
|
|
83
|
-
// We insert the public data tree leaves with one batch per tx to avoid updating the same key twice
|
|
84
|
-
for (const txEffect of l2Block.body.txEffects) {
|
|
85
|
-
await fork.batchInsert(
|
|
86
|
-
MerkleTreeId.PUBLIC_DATA_TREE,
|
|
87
|
-
txEffect.publicDataWrites.map(write => write.toBuffer()),
|
|
88
|
-
0,
|
|
89
|
-
);
|
|
90
|
-
|
|
91
|
-
const nullifiersPadded = padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX);
|
|
92
|
-
|
|
93
|
-
await fork.batchInsert(
|
|
94
|
-
MerkleTreeId.NULLIFIER_TREE,
|
|
95
|
-
nullifiersPadded.map(nullifier => nullifier.toBuffer()),
|
|
96
|
-
NULLIFIER_SUBTREE_HEIGHT,
|
|
97
|
-
);
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
const state = await fork.getStateReference();
|
|
102
|
-
l2Block.header.state = state;
|
|
103
|
-
await fork.updateArchive(l2Block.header);
|
|
104
|
-
|
|
105
|
-
const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
|
|
106
|
-
|
|
107
|
-
l2Block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
|
|
100
|
+
await updateBlockState(l2Block, l1ToL2Messages, fork);
|
|
108
101
|
|
|
109
102
|
return {
|
|
110
103
|
block: l2Block,
|
|
@@ -112,13 +105,18 @@ export async function mockEmptyBlock(blockNum: number, fork: MerkleTreeWriteOper
|
|
|
112
105
|
};
|
|
113
106
|
}
|
|
114
107
|
|
|
115
|
-
export async function mockBlocks(
|
|
116
|
-
|
|
108
|
+
export async function mockBlocks(
|
|
109
|
+
from: BlockNumber,
|
|
110
|
+
count: number,
|
|
111
|
+
numTxs: number,
|
|
112
|
+
worldState: NativeWorldStateService,
|
|
113
|
+
) {
|
|
114
|
+
const tempFork = await worldState.fork(BlockNumber(from - 1));
|
|
117
115
|
|
|
118
116
|
const blocks = [];
|
|
119
117
|
const messagesArray = [];
|
|
120
118
|
for (let blockNumber = from; blockNumber < from + count; blockNumber++) {
|
|
121
|
-
const { block, messages } = await mockBlock(blockNumber, numTxs, tempFork);
|
|
119
|
+
const { block, messages } = await mockBlock(BlockNumber(blockNumber), numTxs, tempFork);
|
|
122
120
|
blocks.push(block);
|
|
123
121
|
messagesArray.push(messages);
|
|
124
122
|
}
|
|
@@ -128,6 +126,18 @@ export async function mockBlocks(from: number, count: number, numTxs: number, wo
|
|
|
128
126
|
return { blocks, messages: messagesArray };
|
|
129
127
|
}
|
|
130
128
|
|
|
129
|
+
export async function mockCheckpoint(
|
|
130
|
+
checkpointNumber: CheckpointNumber,
|
|
131
|
+
fork: MerkleTreeWriteOperations,
|
|
132
|
+
options: Partial<Parameters<typeof mockCheckpointAndMessages>[1]> = {},
|
|
133
|
+
) {
|
|
134
|
+
const { checkpoint, messages } = await mockCheckpointAndMessages(checkpointNumber, options);
|
|
135
|
+
await asyncMap(checkpoint.blocks, async (block, i) => {
|
|
136
|
+
await updateBlockState(block, i === 0 ? messages : [], fork);
|
|
137
|
+
});
|
|
138
|
+
return { checkpoint, messages };
|
|
139
|
+
}
|
|
140
|
+
|
|
131
141
|
export async function assertSameState(forkA: MerkleTreeReadOperations, forkB: MerkleTreeReadOperations) {
|
|
132
142
|
const nativeStateRef = await forkA.getStateReference();
|
|
133
143
|
const nativeArchive = await forkA.getTreeInfo(MerkleTreeId.ARCHIVE);
|