@aztec-labs/world-state 6.0.0-nightly.20260829
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/README.md +40 -0
- package/dest/index.d.ts +6 -0
- package/dest/index.d.ts.map +1 -0
- package/dest/index.js +5 -0
- package/dest/instrumentation/instrumentation.d.ts +25 -0
- package/dest/instrumentation/instrumentation.d.ts.map +1 -0
- package/dest/instrumentation/instrumentation.js +96 -0
- 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 +16 -0
- package/dest/native/fork_checkpoint.d.ts.map +1 -0
- package/dest/native/fork_checkpoint.js +38 -0
- package/dest/native/index.d.ts +4 -0
- package/dest/native/index.d.ts.map +1 -0
- package/dest/native/index.js +3 -0
- package/dest/native/ipc_world_state_instance.d.ts +91 -0
- package/dest/native/ipc_world_state_instance.d.ts.map +1 -0
- package/dest/native/ipc_world_state_instance.js +672 -0
- package/dest/native/merkle_trees_facade.d.ts +58 -0
- package/dest/native/merkle_trees_facade.d.ts.map +1 -0
- package/dest/native/merkle_trees_facade.js +250 -0
- package/dest/native/message.d.ts +145 -0
- package/dest/native/message.d.ts.map +1 -0
- package/dest/native/message.js +150 -0
- package/dest/native/native_world_state.d.ts +77 -0
- package/dest/native/native_world_state.d.ts.map +1 -0
- package/dest/native/native_world_state.js +350 -0
- package/dest/native/native_world_state_instance.d.ts +63 -0
- package/dest/native/native_world_state_instance.d.ts.map +1 -0
- package/dest/native/native_world_state_instance.js +1 -0
- package/dest/native/world_state_operation.d.ts +7 -0
- package/dest/native/world_state_operation.d.ts.map +1 -0
- package/dest/native/world_state_operation.js +5 -0
- package/dest/synchronizer/config.d.ts +31 -0
- package/dest/synchronizer/config.d.ts.map +1 -0
- package/dest/synchronizer/config.js +61 -0
- package/dest/synchronizer/errors.d.ts +11 -0
- package/dest/synchronizer/errors.d.ts.map +1 -0
- package/dest/synchronizer/errors.js +12 -0
- package/dest/synchronizer/factory.d.ts +20 -0
- package/dest/synchronizer/factory.d.ts.map +1 -0
- package/dest/synchronizer/factory.js +30 -0
- package/dest/synchronizer/index.d.ts +4 -0
- package/dest/synchronizer/index.d.ts.map +1 -0
- package/dest/synchronizer/index.js +3 -0
- package/dest/synchronizer/server_world_state_synchronizer.d.ts +83 -0
- package/dest/synchronizer/server_world_state_synchronizer.d.ts.map +1 -0
- package/dest/synchronizer/server_world_state_synchronizer.js +434 -0
- package/dest/test/index.d.ts +2 -0
- package/dest/test/index.d.ts.map +1 -0
- package/dest/test/index.js +1 -0
- package/dest/test/utils.d.ts +35 -0
- package/dest/test/utils.d.ts.map +1 -0
- package/dest/test/utils.js +118 -0
- package/dest/testing.d.ts +11 -0
- package/dest/testing.d.ts.map +1 -0
- package/dest/testing.js +48 -0
- package/dest/world-state-db/index.d.ts +3 -0
- package/dest/world-state-db/index.d.ts.map +1 -0
- package/dest/world-state-db/index.js +1 -0
- package/dest/world-state-db/merkle_tree_db.d.ts +65 -0
- package/dest/world-state-db/merkle_tree_db.d.ts.map +1 -0
- package/dest/world-state-db/merkle_tree_db.js +17 -0
- package/package.json +98 -0
- package/src/index.ts +5 -0
- package/src/instrumentation/instrumentation.ts +150 -0
- package/src/native/bench_metrics.ts +91 -0
- package/src/native/fork_checkpoint.ts +46 -0
- package/src/native/index.ts +3 -0
- package/src/native/ipc_world_state_instance.ts +849 -0
- package/src/native/merkle_trees_facade.ts +375 -0
- package/src/native/message.ts +287 -0
- package/src/native/native_world_state.ts +435 -0
- package/src/native/native_world_state_instance.ts +104 -0
- package/src/native/world_state_operation.ts +33 -0
- package/src/synchronizer/config.ts +106 -0
- package/src/synchronizer/errors.ts +13 -0
- package/src/synchronizer/factory.ts +83 -0
- package/src/synchronizer/index.ts +3 -0
- package/src/synchronizer/server_world_state_synchronizer.ts +525 -0
- package/src/test/index.ts +1 -0
- package/src/test/utils.ts +184 -0
- package/src/testing.ts +65 -0
- package/src/world-state-db/index.ts +3 -0
- package/src/world-state-db/merkle_tree_db.ts +80 -0
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
import { INITIAL_L2_BLOCK_NUM } from '@aztec-labs/constants';
|
|
2
|
+
import { BlockNumber, CheckpointNumber } from '@aztec-labs/foundation/branded-types';
|
|
3
|
+
import { createLogger } from '@aztec-labs/foundation/log';
|
|
4
|
+
import { promiseWithResolvers } from '@aztec-labs/foundation/promise';
|
|
5
|
+
import { elapsed } from '@aztec-labs/foundation/timer';
|
|
6
|
+
import { EventDrivenL2BlockStream } from '@aztec-labs/stdlib/block';
|
|
7
|
+
import { WorldStateRunningState } from '@aztec-labs/stdlib/interfaces/server';
|
|
8
|
+
import { MerkleTreeId } from '@aztec-labs/stdlib/trees';
|
|
9
|
+
import { getTelemetryClient } from '@aztec-labs/telemetry-client';
|
|
10
|
+
import { WorldStateInstrumentation } from '../instrumentation/instrumentation.js';
|
|
11
|
+
import { WorldStateSynchronizerError } from './errors.js';
|
|
12
|
+
/**
|
|
13
|
+
* Synchronizes the world state with the L2 blocks from a L2BlockSource via a block stream.
|
|
14
|
+
* The synchronizer will download the L2 blocks from the L2BlockSource and update the merkle trees.
|
|
15
|
+
* Handles chain reorgs via the L2BlockStream.
|
|
16
|
+
*/ export class ServerWorldStateSynchronizer {
|
|
17
|
+
merkleTreeDb;
|
|
18
|
+
l2BlockSource;
|
|
19
|
+
config;
|
|
20
|
+
instrumentation;
|
|
21
|
+
log;
|
|
22
|
+
merkleTreeCommitted;
|
|
23
|
+
latestBlockNumberAtStart;
|
|
24
|
+
historyToKeep;
|
|
25
|
+
currentState;
|
|
26
|
+
syncPromise;
|
|
27
|
+
blockStream;
|
|
28
|
+
// WorldState doesn't track the proven block number, it only tracks the latest tips of the pending chain and the finalized chain
|
|
29
|
+
// store the proven block number here, in the synchronizer, so that we don't end up spamming the logs with 'chain-proved' events
|
|
30
|
+
provenBlockNumber;
|
|
31
|
+
constructor(merkleTreeDb, l2BlockSource, config, instrumentation = new WorldStateInstrumentation(getTelemetryClient()), log = createLogger('world_state')){
|
|
32
|
+
this.merkleTreeDb = merkleTreeDb;
|
|
33
|
+
this.l2BlockSource = l2BlockSource;
|
|
34
|
+
this.config = config;
|
|
35
|
+
this.instrumentation = instrumentation;
|
|
36
|
+
this.log = log;
|
|
37
|
+
this.latestBlockNumberAtStart = BlockNumber.ZERO;
|
|
38
|
+
this.currentState = WorldStateRunningState.IDLE;
|
|
39
|
+
this.syncPromise = promiseWithResolvers();
|
|
40
|
+
this.merkleTreeCommitted = this.merkleTreeDb.getCommitted();
|
|
41
|
+
this.historyToKeep = config.worldStateCheckpointHistory < 1 ? undefined : config.worldStateCheckpointHistory;
|
|
42
|
+
this.log.info(`Created world state synchroniser with block history of ${this.historyToKeep === undefined ? 'infinity' : this.historyToKeep}`);
|
|
43
|
+
}
|
|
44
|
+
getCommitted() {
|
|
45
|
+
return this.merkleTreeDb.getCommitted();
|
|
46
|
+
}
|
|
47
|
+
getSnapshot(blockNumber) {
|
|
48
|
+
return this.merkleTreeDb.getSnapshot(blockNumber);
|
|
49
|
+
}
|
|
50
|
+
async getVerifiedSnapshot(blockNumber, blockHash) {
|
|
51
|
+
const snapshot = this.merkleTreeDb.getSnapshot(blockNumber);
|
|
52
|
+
// Block 0's snapshot is the pre-genesis archive view (size 0), so archive leaf 0 is not visible from it;
|
|
53
|
+
// verify against the initial header hash instead. For later blocks, read archive leaf `blockNumber` from the
|
|
54
|
+
// snapshot's own view so the exact handle we return is validated against the requested fork.
|
|
55
|
+
const actualHash = blockNumber === BlockNumber.ZERO ? (await this.merkleTreeCommitted.getInitialHeader().hash()).toString() : (await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber)))?.toString();
|
|
56
|
+
if (actualHash === undefined) {
|
|
57
|
+
// A missing archive leaf means either the block's history has been pruned away (permanent: the block predates
|
|
58
|
+
// the oldest historical block kept by world state) or a reorg flipped the fork between the sync and this read
|
|
59
|
+
// (transient). Only the latter is worth retrying, so it alone surfaces as WorldStateSynchronizerError.
|
|
60
|
+
const { oldestHistoricalBlock } = await this.merkleTreeDb.getStatusSummary();
|
|
61
|
+
if (blockNumber < oldestHistoricalBlock) {
|
|
62
|
+
throw new Error(`Unable to find leaf for block ${blockNumber} in the archive tree: world state history has been pruned to block ${oldestHistoricalBlock}`);
|
|
63
|
+
}
|
|
64
|
+
throw new WorldStateSynchronizerError(`Unable to read block hash at block ${blockNumber} to verify snapshot`, {
|
|
65
|
+
cause: {
|
|
66
|
+
reason: 'block_not_available',
|
|
67
|
+
targetBlockNumber: blockNumber
|
|
68
|
+
}
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
if (actualHash !== blockHash.toString()) {
|
|
72
|
+
throw new WorldStateSynchronizerError(`Block hash mismatch at block ${blockNumber} (expected ${blockHash} but got ${actualHash})`, {
|
|
73
|
+
cause: {
|
|
74
|
+
reason: 'block_hash_mismatch',
|
|
75
|
+
targetBlockNumber: blockNumber,
|
|
76
|
+
expectedHash: blockHash.toString(),
|
|
77
|
+
actualHash
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return snapshot;
|
|
82
|
+
}
|
|
83
|
+
fork(blockNumber, opts) {
|
|
84
|
+
return this.merkleTreeDb.fork(blockNumber, opts);
|
|
85
|
+
}
|
|
86
|
+
backupTo(dstPath, compact) {
|
|
87
|
+
return this.merkleTreeDb.backupTo(dstPath, compact);
|
|
88
|
+
}
|
|
89
|
+
clear() {
|
|
90
|
+
return this.merkleTreeDb.clear();
|
|
91
|
+
}
|
|
92
|
+
async start() {
|
|
93
|
+
if (this.currentState === WorldStateRunningState.STOPPED) {
|
|
94
|
+
throw new Error('Synchronizer already stopped');
|
|
95
|
+
}
|
|
96
|
+
if (this.currentState !== WorldStateRunningState.IDLE) {
|
|
97
|
+
return this.syncPromise;
|
|
98
|
+
}
|
|
99
|
+
// Get the current latest block number
|
|
100
|
+
this.latestBlockNumberAtStart = BlockNumber(await this.l2BlockSource.getBlockNumber());
|
|
101
|
+
const blockToDownloadFrom = await this.getLatestBlockNumber() + 1;
|
|
102
|
+
if (blockToDownloadFrom <= this.latestBlockNumberAtStart) {
|
|
103
|
+
// If there are blocks to be retrieved, go to a synching state
|
|
104
|
+
this.setCurrentState(WorldStateRunningState.SYNCHING);
|
|
105
|
+
this.log.verbose(`Starting sync from ${blockToDownloadFrom} to latest block ${this.latestBlockNumberAtStart}`);
|
|
106
|
+
} else {
|
|
107
|
+
// If no blocks to be retrieved, go straight to running
|
|
108
|
+
this.setCurrentState(WorldStateRunningState.RUNNING);
|
|
109
|
+
this.syncPromise.resolve();
|
|
110
|
+
this.log.debug(`Next block ${blockToDownloadFrom} already beyond latest block ${this.latestBlockNumberAtStart}`);
|
|
111
|
+
}
|
|
112
|
+
this.blockStream = this.createBlockStream();
|
|
113
|
+
this.blockStream.start();
|
|
114
|
+
this.log.info(`Started world state synchronizer from block ${blockToDownloadFrom}`);
|
|
115
|
+
return this.syncPromise.promise;
|
|
116
|
+
}
|
|
117
|
+
createBlockStream() {
|
|
118
|
+
const logger = createLogger('world-state:block_stream');
|
|
119
|
+
return new EventDrivenL2BlockStream(this.l2BlockSource, this, this, logger, {
|
|
120
|
+
pollIntervalMS: this.config.worldStateBlockCheckIntervalMS,
|
|
121
|
+
batchSize: this.config.worldStateBlockRequestBatchSize,
|
|
122
|
+
ignoreCheckpoints: true
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
async stop() {
|
|
126
|
+
this.log.debug('Stopping block stream...');
|
|
127
|
+
await this.blockStream?.stop();
|
|
128
|
+
this.log.debug('Stopping merkle trees...');
|
|
129
|
+
await this.merkleTreeDb.close();
|
|
130
|
+
this.setCurrentState(WorldStateRunningState.STOPPED);
|
|
131
|
+
this.log.info(`Stopped world state synchronizer`);
|
|
132
|
+
}
|
|
133
|
+
async status() {
|
|
134
|
+
const summary = await this.merkleTreeDb.getStatusSummary();
|
|
135
|
+
const status = {
|
|
136
|
+
latestBlockNumber: summary.unfinalizedBlockNumber,
|
|
137
|
+
latestBlockHash: await this.getL2BlockHash(summary.unfinalizedBlockNumber) ?? '',
|
|
138
|
+
finalizedBlockNumber: summary.finalizedBlockNumber,
|
|
139
|
+
oldestHistoricBlockNumber: summary.oldestHistoricalBlock,
|
|
140
|
+
treesAreSynched: summary.treesAreSynched
|
|
141
|
+
};
|
|
142
|
+
return {
|
|
143
|
+
syncSummary: status,
|
|
144
|
+
state: this.currentState
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
async getLatestBlockNumber() {
|
|
148
|
+
return (await this.getL2Tips()).proposed.number;
|
|
149
|
+
}
|
|
150
|
+
async stopSync() {
|
|
151
|
+
this.log.debug('Stopping sync...');
|
|
152
|
+
await this.blockStream?.stop();
|
|
153
|
+
this.log.info('Stopped sync');
|
|
154
|
+
}
|
|
155
|
+
resumeSync() {
|
|
156
|
+
if (!this.blockStream) {
|
|
157
|
+
throw new Error('Cannot resume sync as block stream is not initialized');
|
|
158
|
+
}
|
|
159
|
+
this.log.debug('Resuming sync...');
|
|
160
|
+
this.blockStream.start();
|
|
161
|
+
this.log.info('Resumed sync');
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Forces an immediate sync.
|
|
165
|
+
* @param targetBlockNumber - The target block number that we must sync to. Will download unproven blocks if needed to reach it.
|
|
166
|
+
* @param blockHash - If provided, verifies the block at targetBlockNumber matches this hash. On mismatch, triggers a resync (reorg detection).
|
|
167
|
+
* @returns A promise that resolves with the block number the world state was synced to
|
|
168
|
+
*/ async syncImmediate(targetBlockNumber, blockHash) {
|
|
169
|
+
if (this.currentState !== WorldStateRunningState.RUNNING) {
|
|
170
|
+
throw new Error(`World State is not running. Unable to perform sync.`);
|
|
171
|
+
}
|
|
172
|
+
if (this.blockStream === undefined) {
|
|
173
|
+
throw new Error('Block stream is not initialized. Unable to perform sync.');
|
|
174
|
+
}
|
|
175
|
+
// If we have been given a block number to sync to and we have reached that number then return
|
|
176
|
+
const currentBlockNumber = await this.getLatestBlockNumber();
|
|
177
|
+
if (targetBlockNumber !== undefined && targetBlockNumber <= currentBlockNumber) {
|
|
178
|
+
if (blockHash === undefined) {
|
|
179
|
+
return currentBlockNumber;
|
|
180
|
+
}
|
|
181
|
+
// If a block hash was provided, verify we're on the expected fork
|
|
182
|
+
const currentHash = await this.getL2BlockHash(targetBlockNumber);
|
|
183
|
+
if (currentHash === blockHash.toString()) {
|
|
184
|
+
return currentBlockNumber;
|
|
185
|
+
}
|
|
186
|
+
// Hash mismatch: a reorg may have occurred, fall through to trigger sync
|
|
187
|
+
this.log.debug(`World state block hash mismatch at ${targetBlockNumber} (expected ${blockHash}, got ${currentHash}). Triggering resync.`);
|
|
188
|
+
}
|
|
189
|
+
this.log.debug(`World State at ${currentBlockNumber} told to sync to ${targetBlockNumber ?? 'latest'}`);
|
|
190
|
+
// If the archiver is behind the target block, force an archiver sync
|
|
191
|
+
if (targetBlockNumber) {
|
|
192
|
+
const archiverLatestBlock = BlockNumber(await this.l2BlockSource.getBlockNumber());
|
|
193
|
+
if (archiverLatestBlock < targetBlockNumber) {
|
|
194
|
+
this.log.debug(`Archiver is at ${archiverLatestBlock} behind target block ${targetBlockNumber}.`);
|
|
195
|
+
await this.l2BlockSource.syncImmediate();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
// Force the block stream to sync against the archiver now
|
|
199
|
+
await this.blockStream.sync();
|
|
200
|
+
// If we have been given a block number to sync to and we have not reached that number then fail
|
|
201
|
+
const updatedBlockNumber = await this.getLatestBlockNumber();
|
|
202
|
+
if (targetBlockNumber !== undefined && targetBlockNumber > updatedBlockNumber) {
|
|
203
|
+
throw new WorldStateSynchronizerError(`Unable to sync to block number ${targetBlockNumber} (last synced is ${updatedBlockNumber})`, {
|
|
204
|
+
cause: {
|
|
205
|
+
reason: 'block_not_available',
|
|
206
|
+
previousBlockNumber: currentBlockNumber,
|
|
207
|
+
updatedBlockNumber,
|
|
208
|
+
targetBlockNumber
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
// If a block hash was provided, verify we're on the expected fork after syncing, throw otherwise
|
|
213
|
+
if (blockHash !== undefined && targetBlockNumber !== undefined) {
|
|
214
|
+
const updatedHash = await this.getL2BlockHash(targetBlockNumber);
|
|
215
|
+
if (updatedHash !== blockHash.toString()) {
|
|
216
|
+
throw new WorldStateSynchronizerError(`Block hash mismatch at block ${targetBlockNumber} (expected ${blockHash} but got ${updatedHash})`, {
|
|
217
|
+
cause: {
|
|
218
|
+
reason: 'block_hash_mismatch',
|
|
219
|
+
targetBlockNumber,
|
|
220
|
+
expectedHash: blockHash.toString(),
|
|
221
|
+
actualHash: updatedHash
|
|
222
|
+
}
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return updatedBlockNumber;
|
|
227
|
+
}
|
|
228
|
+
/** Returns the L2 block hash for a given number. Used by the L2BlockStream for detecting reorgs. */ async getL2BlockHash(number) {
|
|
229
|
+
if (number === BlockNumber.ZERO) {
|
|
230
|
+
return (await this.merkleTreeCommitted.getInitialHeader().hash()).toString();
|
|
231
|
+
}
|
|
232
|
+
return this.merkleTreeCommitted.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(number)).then((leaf)=>leaf?.toString());
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Returns the proposed, proven, and finalized block tips of the chain. World state drives its block stream with
|
|
236
|
+
* `ignoreCheckpoints`, so it does not track checkpointed blocks or checkpoints and omits `checkpointed` from the tips
|
|
237
|
+
* it reports.
|
|
238
|
+
*/ async getL2Tips() {
|
|
239
|
+
const status = await this.merkleTreeDb.getStatusSummary();
|
|
240
|
+
const unfinalizedBlockHashPromise = this.getL2BlockHash(status.unfinalizedBlockNumber);
|
|
241
|
+
const finalizedBlockHashPromise = this.getL2BlockHash(status.finalizedBlockNumber);
|
|
242
|
+
const provenBlockNumber = this.provenBlockNumber ?? status.finalizedBlockNumber;
|
|
243
|
+
const provenBlockHashPromise = this.provenBlockNumber === undefined ? finalizedBlockHashPromise : this.getL2BlockHash(this.provenBlockNumber);
|
|
244
|
+
const [unfinalizedBlockHash, finalizedBlockHash, provenBlockHash] = await Promise.all([
|
|
245
|
+
unfinalizedBlockHashPromise,
|
|
246
|
+
finalizedBlockHashPromise,
|
|
247
|
+
provenBlockHashPromise
|
|
248
|
+
]);
|
|
249
|
+
return {
|
|
250
|
+
proposed: {
|
|
251
|
+
number: status.unfinalizedBlockNumber,
|
|
252
|
+
hash: unfinalizedBlockHash
|
|
253
|
+
},
|
|
254
|
+
finalized: {
|
|
255
|
+
block: {
|
|
256
|
+
number: status.finalizedBlockNumber,
|
|
257
|
+
hash: finalizedBlockHash
|
|
258
|
+
}
|
|
259
|
+
},
|
|
260
|
+
proven: {
|
|
261
|
+
block: {
|
|
262
|
+
number: provenBlockNumber,
|
|
263
|
+
hash: provenBlockHash
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
/** Handles an event emitted by the block stream. */ async handleBlockStreamEvent(event) {
|
|
269
|
+
switch(event.type){
|
|
270
|
+
case 'blocks-added':
|
|
271
|
+
await this.handleL2Blocks(event.blocks);
|
|
272
|
+
break;
|
|
273
|
+
case 'chain-pruned':
|
|
274
|
+
await this.handleChainPruned(event.block.number);
|
|
275
|
+
break;
|
|
276
|
+
case 'chain-proven':
|
|
277
|
+
await this.handleChainProven(event.block.number);
|
|
278
|
+
break;
|
|
279
|
+
case 'chain-finalized':
|
|
280
|
+
await this.handleChainFinalized(event.block.number);
|
|
281
|
+
break;
|
|
282
|
+
// World state runs in block mode with ignoreCheckpoints: it tracks tips via blocks-added/pruned/proven/finalized
|
|
283
|
+
// and ignores the thin tip events (it never anchors on them).
|
|
284
|
+
case 'chain-proposed':
|
|
285
|
+
case 'chain-checkpointed':
|
|
286
|
+
break;
|
|
287
|
+
default:
|
|
288
|
+
{
|
|
289
|
+
const _ = event;
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Handles a list of L2 blocks (i.e. Inserts the new note hashes into the merkle tree).
|
|
296
|
+
* @param l2Blocks - The L2 blocks to handle.
|
|
297
|
+
* @returns Whether the block handled was produced by this same node.
|
|
298
|
+
*/ async handleL2Blocks(l2Blocks) {
|
|
299
|
+
this.log.debug(`Handling L2 blocks ${l2Blocks[0].number} to ${l2Blocks.at(-1).number}`);
|
|
300
|
+
// Derive each block's real L1-to-L2 message bundle from the compact leaf-index range it inserted:
|
|
301
|
+
// the messages between the parent block's L1-to-L2 tree leaf count and this block's, resolved via the
|
|
302
|
+
// Inbox buckets. Blocks in a batch are consecutive, so we track the running leaf count.
|
|
303
|
+
const messagesForBlocks = new Map();
|
|
304
|
+
let prevLeafCount = await this.getL1ToL2LeafCountBefore(l2Blocks[0].number);
|
|
305
|
+
for (const block of l2Blocks){
|
|
306
|
+
const blockLeafCount = BigInt(block.header.state.l1ToL2MessageTree.nextAvailableLeafIndex);
|
|
307
|
+
if (blockLeafCount > prevLeafCount) {
|
|
308
|
+
const startBucket = await this.l2BlockSource.getInboxBucketByTotalMsgCount(prevLeafCount);
|
|
309
|
+
const endBucket = await this.l2BlockSource.getInboxBucketByTotalMsgCount(blockLeafCount);
|
|
310
|
+
if (startBucket !== undefined && endBucket !== undefined) {
|
|
311
|
+
messagesForBlocks.set(block.number, await this.l2BlockSource.getL1ToL2MessagesBetweenBuckets(startBucket.seq, endBucket.seq));
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
prevLeafCount = blockLeafCount;
|
|
315
|
+
}
|
|
316
|
+
let updateStatus = undefined;
|
|
317
|
+
for (const block of l2Blocks){
|
|
318
|
+
const [duration, result] = await elapsed(()=>this.handleL2Block(block, messagesForBlocks.get(block.number) ?? []));
|
|
319
|
+
this.log.info(`World state updated with L2 block ${block.number}`, {
|
|
320
|
+
eventName: 'l2-block-handled',
|
|
321
|
+
duration,
|
|
322
|
+
unfinalizedBlockNumber: BigInt(result.summary.unfinalizedBlockNumber),
|
|
323
|
+
finalizedBlockNumber: BigInt(result.summary.finalizedBlockNumber),
|
|
324
|
+
oldestHistoricBlock: BigInt(result.summary.oldestHistoricalBlock),
|
|
325
|
+
...block.getStats()
|
|
326
|
+
});
|
|
327
|
+
updateStatus = result;
|
|
328
|
+
}
|
|
329
|
+
if (!updateStatus) {
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
this.instrumentation.updateWorldStateMetrics(updateStatus);
|
|
333
|
+
}
|
|
334
|
+
/** The L1-to-L2 message tree leaf count as of the block before `blockNumber` (0 if that block is genesis). */ async getL1ToL2LeafCountBefore(blockNumber) {
|
|
335
|
+
const parentNumber = blockNumber - 1;
|
|
336
|
+
if (parentNumber < INITIAL_L2_BLOCK_NUM) {
|
|
337
|
+
return 0n;
|
|
338
|
+
}
|
|
339
|
+
const parentBlock = await this.l2BlockSource.getBlockData({
|
|
340
|
+
number: BlockNumber(parentNumber)
|
|
341
|
+
});
|
|
342
|
+
return parentBlock === undefined ? 0n : BigInt(parentBlock.header.state.l1ToL2MessageTree.nextAvailableLeafIndex);
|
|
343
|
+
}
|
|
344
|
+
/**
|
|
345
|
+
* Handles a single L2 block (i.e. Inserts the new note hashes into the merkle tree).
|
|
346
|
+
* @param l2Block - The L2 block to handle.
|
|
347
|
+
* @param l1ToL2Messages - The L1 to L2 messages for the block.
|
|
348
|
+
* @returns Whether the block handled was produced by this same node.
|
|
349
|
+
*/ async handleL2Block(l2Block, l1ToL2Messages) {
|
|
350
|
+
this.log.debug(`Pushing L2 block ${l2Block.number} to merkle tree db `, {
|
|
351
|
+
blockNumber: l2Block.number,
|
|
352
|
+
blockHash: await l2Block.hash().then((h)=>h.toString()),
|
|
353
|
+
l1ToL2Messages: l1ToL2Messages.map((msg)=>msg.toString()),
|
|
354
|
+
blockHeader: l2Block.header.toInspect(),
|
|
355
|
+
blockStats: l2Block.getStats()
|
|
356
|
+
});
|
|
357
|
+
const result = await this.merkleTreeDb.handleL2BlockAndMessages(l2Block, l1ToL2Messages);
|
|
358
|
+
if (this.currentState === WorldStateRunningState.SYNCHING && l2Block.number >= this.latestBlockNumberAtStart) {
|
|
359
|
+
this.setCurrentState(WorldStateRunningState.RUNNING);
|
|
360
|
+
this.syncPromise.resolve();
|
|
361
|
+
}
|
|
362
|
+
return result;
|
|
363
|
+
}
|
|
364
|
+
async handleChainFinalized(blockNumber) {
|
|
365
|
+
this.log.verbose(`Finalized chain is now at block ${blockNumber}`);
|
|
366
|
+
// If the finalized block number is older than the oldest available block in world state,
|
|
367
|
+
// skip entirely. The finalized block number can jump backwards (e.g. when the finalization
|
|
368
|
+
// heuristic changes) and try to read block data that has already been pruned. When this
|
|
369
|
+
// happens, there is nothing useful to do — the native world state is already finalized
|
|
370
|
+
// past this point and pruning has already happened.
|
|
371
|
+
const currentSummary = await this.merkleTreeDb.getStatusSummary();
|
|
372
|
+
if (blockNumber < currentSummary.oldestHistoricalBlock || blockNumber < 1) {
|
|
373
|
+
this.log.trace(`Finalized block ${blockNumber} is older than the oldest available block ${currentSummary.oldestHistoricalBlock}. Skipping.`);
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
const summary = await this.merkleTreeDb.setFinalized(blockNumber);
|
|
377
|
+
if (this.historyToKeep === undefined) {
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
const finalisedBlockData = await this.l2BlockSource.getBlockData({
|
|
381
|
+
number: summary.finalizedBlockNumber
|
|
382
|
+
});
|
|
383
|
+
if (finalisedBlockData === undefined) {
|
|
384
|
+
this.log.warn(`Failed to retrieve checkpointed block for finalized block number: ${summary.finalizedBlockNumber}`);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
// Compute the required historic checkpoint number
|
|
388
|
+
const newHistoricCheckpointNumber = finalisedBlockData.checkpointNumber - this.historyToKeep + 1;
|
|
389
|
+
if (newHistoricCheckpointNumber <= 1) {
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
// Retrieve the historic checkpoint
|
|
393
|
+
const historicCheckpoint = await this.l2BlockSource.getCheckpoint({
|
|
394
|
+
number: CheckpointNumber(newHistoricCheckpointNumber)
|
|
395
|
+
});
|
|
396
|
+
if (!historicCheckpoint) {
|
|
397
|
+
this.log.warn(`Failed to retrieve checkpoint number ${newHistoricCheckpointNumber} from Archiver`);
|
|
398
|
+
return;
|
|
399
|
+
}
|
|
400
|
+
if (historicCheckpoint.checkpoint.blocks.length === 0 || historicCheckpoint.checkpoint.blocks[0] === undefined) {
|
|
401
|
+
this.log.warn(`Retrieved checkpoint number ${newHistoricCheckpointNumber} has no blocks!`);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
// Find the block at the start of the checkpoint and remove blocks up to this one
|
|
405
|
+
const newHistoricBlock = historicCheckpoint.checkpoint.blocks[0];
|
|
406
|
+
if (newHistoricBlock.number <= currentSummary.oldestHistoricalBlock) {
|
|
407
|
+
this.log.debug(`Historic block ${newHistoricBlock.number} is not newer than oldest available ${currentSummary.oldestHistoricalBlock}. Skipping prune.`);
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
this.log.verbose(`Pruning historic blocks to ${newHistoricBlock.number}`);
|
|
411
|
+
const status = await this.merkleTreeDb.removeHistoricalBlocks(BlockNumber(newHistoricBlock.number));
|
|
412
|
+
this.log.debug(`World state summary `, status.summary);
|
|
413
|
+
}
|
|
414
|
+
handleChainProven(blockNumber) {
|
|
415
|
+
this.provenBlockNumber = blockNumber;
|
|
416
|
+
this.log.debug(`Proven chain is now at block ${blockNumber}`);
|
|
417
|
+
return Promise.resolve();
|
|
418
|
+
}
|
|
419
|
+
async handleChainPruned(blockNumber) {
|
|
420
|
+
this.log.info(`Chain pruned to block ${blockNumber}`);
|
|
421
|
+
const status = await this.merkleTreeDb.unwindBlocks(blockNumber);
|
|
422
|
+
if (this.provenBlockNumber !== undefined && this.provenBlockNumber > blockNumber) {
|
|
423
|
+
this.provenBlockNumber = undefined;
|
|
424
|
+
}
|
|
425
|
+
this.instrumentation.updateWorldStateMetrics(status);
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Method to set the value of the current state.
|
|
429
|
+
* @param newState - New state value.
|
|
430
|
+
*/ setCurrentState(newState) {
|
|
431
|
+
this.currentState = newState;
|
|
432
|
+
this.log.debug(`Moved to state ${WorldStateRunningState[this.currentState]}`);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/test/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './utils.js';
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { BlockNumber, type CheckpointNumber } from '@aztec-labs/foundation/branded-types';
|
|
2
|
+
import { Fr } from '@aztec-labs/foundation/curves/bn254';
|
|
3
|
+
import { L2Block } from '@aztec-labs/stdlib/block';
|
|
4
|
+
import type { MerkleTreeReadOperations, MerkleTreeWriteOperations } from '@aztec-labs/stdlib/interfaces/server';
|
|
5
|
+
import { mockCheckpointAndMessages } from '@aztec-labs/stdlib/testing';
|
|
6
|
+
import type { NativeWorldStateService } from '../native/native_world_state.js';
|
|
7
|
+
export declare function updateBlockState(block: L2Block, l1ToL2Messages: Fr[], fork: MerkleTreeWriteOperations): Promise<void>;
|
|
8
|
+
export declare function mockBlock(blockNum: BlockNumber, size: number, fork: MerkleTreeWriteOperations, maxEffects?: number | undefined, numL1ToL2Messages?: number, isFirstBlockInCheckpoint?: boolean): Promise<{
|
|
9
|
+
block: L2Block;
|
|
10
|
+
messages: Fr[];
|
|
11
|
+
}>;
|
|
12
|
+
/**
|
|
13
|
+
* Builds a mock L2 block at an explicit position within its checkpoint, applying its state (including its L1-to-L2
|
|
14
|
+
* message bundle) to the given fork. Unlike {@link mockBlock}, the caller chooses the `indexWithinCheckpoint`, so
|
|
15
|
+
* non-first blocks can carry message bundles — exercising the per-block message insertion path.
|
|
16
|
+
*/
|
|
17
|
+
export declare function mockBlockWithIndex(blockNum: BlockNumber, indexWithinCheckpoint: number, size: number, fork: MerkleTreeWriteOperations, numL1ToL2Messages?: number, maxEffects?: number | undefined): Promise<{
|
|
18
|
+
block: L2Block;
|
|
19
|
+
messages: Fr[];
|
|
20
|
+
}>;
|
|
21
|
+
export declare function mockEmptyBlock(blockNum: BlockNumber, fork: MerkleTreeWriteOperations): Promise<{
|
|
22
|
+
block: L2Block;
|
|
23
|
+
messages: Fr[];
|
|
24
|
+
}>;
|
|
25
|
+
export declare function mockBlocks(from: BlockNumber, count: number, numTxs: number, worldState: NativeWorldStateService): Promise<{
|
|
26
|
+
blocks: L2Block[];
|
|
27
|
+
messages: Fr[][];
|
|
28
|
+
}>;
|
|
29
|
+
export declare function mockCheckpoint(checkpointNumber: CheckpointNumber, fork: MerkleTreeWriteOperations, options?: Partial<Parameters<typeof mockCheckpointAndMessages>[1]>): Promise<{
|
|
30
|
+
checkpoint: import("@aztec-labs/stdlib/checkpoint").Checkpoint;
|
|
31
|
+
messages: Fr[];
|
|
32
|
+
}>;
|
|
33
|
+
export declare function assertSameState(forkA: MerkleTreeReadOperations, forkB: MerkleTreeReadOperations): Promise<void>;
|
|
34
|
+
export declare function compareChains(left: MerkleTreeReadOperations, right: MerkleTreeReadOperations): Promise<void>;
|
|
35
|
+
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXRpbHMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy90ZXN0L3V0aWxzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQU9BLE9BQU8sRUFBRSxXQUFXLEVBQUUsS0FBSyxnQkFBZ0IsRUFBeUIsTUFBTSxzQ0FBc0MsQ0FBQztBQUVqSCxPQUFPLEVBQUUsRUFBRSxFQUFFLE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AAE,MAAM,GAAG,SAAgB,EACrC,iBAAiB,GAAE,MAAyC,EAC5D,wBAAwB,GAAE,OAAc;;;GAGzC;AAED;;;;GAIG;AACH,wBAAsB,kBAAkB,CACtC,QAAQ,EAAE,WAAW,EACrB,qBAAqB,EAAE,MAAM,EAC7B,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,yBAAyB,EAC/B,iBAAiB,GAAE,MAAyC,EAC5D,UAAU,GAAE,MAAM,GAAG,SAAgB;;;GAetC;AAED,wBAAsB,cAAc,CAAC,QAAQ,EAAE,WAAW,EAAE,IAAI,EAAE,yBAAyB;;;GAY1F;AAED,wBAAsB,UAAU,CAC9B,IAAI,EAAE,WAAW,EACjB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,uBAAuB;;;GAepC;AAED,wBAAsB,cAAc,CAClC,gBAAgB,EAAE,gBAAgB,EAClC,IAAI,EAAE,yBAAyB,EAC/B,OAAO,GAAE,OAAO,CAAC,UAAU,CAAC,OAAO,yBAAyB,CAAC,CAAC,CAAC,CAAC,CAAM;;;GAOvE;AAED,wBAAsB,eAAe,CAAC,KAAK,EAAE,wBAAwB,EAAE,KAAK,EAAE,wBAAwB,iBAQrG;AAED,wBAAsB,aAAa,CAAC,IAAI,EAAE,wBAAwB,EAAE,KAAK,EAAE,wBAAwB,iBAYlG"}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { MAX_L1_TO_L2_MSGS_PER_CHECKPOINT, MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, NULLIFIER_SUBTREE_HEIGHT } from '@aztec-labs/constants';
|
|
2
|
+
import { asyncMap } from '@aztec-labs/foundation/async-map';
|
|
3
|
+
import { BlockNumber, IndexWithinCheckpoint } from '@aztec-labs/foundation/branded-types';
|
|
4
|
+
import { padArrayEnd } from '@aztec-labs/foundation/collection';
|
|
5
|
+
import { Fr } from '@aztec-labs/foundation/curves/bn254';
|
|
6
|
+
import { L2Block } from '@aztec-labs/stdlib/block';
|
|
7
|
+
import { mockCheckpointAndMessages, mockL1ToL2Messages } from '@aztec-labs/stdlib/testing';
|
|
8
|
+
import { AppendOnlyTreeSnapshot, MerkleTreeId } from '@aztec-labs/stdlib/trees';
|
|
9
|
+
import { BlockHeader } from '@aztec-labs/stdlib/tx';
|
|
10
|
+
export async function updateBlockState(block, l1ToL2Messages, fork) {
|
|
11
|
+
const insertData = async (treeId, data, subTreeHeight, fork)=>{
|
|
12
|
+
for (const dataBatch of data){
|
|
13
|
+
await fork.batchInsert(treeId, dataBatch, subTreeHeight);
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
const publicDataInsert = insertData(MerkleTreeId.PUBLIC_DATA_TREE, block.body.txEffects.map((txEffect)=>txEffect.publicDataWrites.map((write)=>write.toBuffer())), 0, fork);
|
|
17
|
+
const nullifierInsert = insertData(MerkleTreeId.NULLIFIER_TREE, block.body.txEffects.map((txEffect)=>padArrayEnd(txEffect.nullifiers, Fr.ZERO, MAX_NULLIFIERS_PER_TX).map((nullifier)=>nullifier.toBuffer())), NULLIFIER_SUBTREE_HEIGHT, fork);
|
|
18
|
+
const noteHashesPadded = block.body.txEffects.flatMap((txEffect)=>padArrayEnd(txEffect.noteHashes, Fr.ZERO, MAX_NOTE_HASHES_PER_TX));
|
|
19
|
+
// Every block appends its real message leaves unpadded at compact indices.
|
|
20
|
+
const noteHashInsert = fork.appendLeaves(MerkleTreeId.NOTE_HASH_TREE, noteHashesPadded);
|
|
21
|
+
const messageInsert = fork.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2Messages);
|
|
22
|
+
await Promise.all([
|
|
23
|
+
publicDataInsert,
|
|
24
|
+
nullifierInsert,
|
|
25
|
+
noteHashInsert,
|
|
26
|
+
messageInsert
|
|
27
|
+
]);
|
|
28
|
+
const state = await fork.getStateReference();
|
|
29
|
+
// Capture the archive root *before* appending this block so the header's lastArchive chains off the previous block.
|
|
30
|
+
// sync_block now verifies lastArchive against the committed archive root, so a block carrying an unchained value
|
|
31
|
+
// (e.g. the random lastArchive from L2Block.random) would be rejected as a divergence from the canonical chain.
|
|
32
|
+
const previousArchive = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
|
|
33
|
+
block.header = BlockHeader.from({
|
|
34
|
+
...block.header,
|
|
35
|
+
state,
|
|
36
|
+
lastArchive: new AppendOnlyTreeSnapshot(Fr.fromBuffer(previousArchive.root), Number(previousArchive.size))
|
|
37
|
+
});
|
|
38
|
+
await fork.updateArchive(block.header);
|
|
39
|
+
const archiveState = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
|
|
40
|
+
block.archive = new AppendOnlyTreeSnapshot(Fr.fromBuffer(archiveState.root), Number(archiveState.size));
|
|
41
|
+
}
|
|
42
|
+
export function mockBlock(blockNum, size, fork, maxEffects = 1000, numL1ToL2Messages = MAX_L1_TO_L2_MSGS_PER_CHECKPOINT, isFirstBlockInCheckpoint = true) {
|
|
43
|
+
return mockBlockWithIndex(blockNum, isFirstBlockInCheckpoint ? 0 : 1, size, fork, numL1ToL2Messages, maxEffects);
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Builds a mock L2 block at an explicit position within its checkpoint, applying its state (including its L1-to-L2
|
|
47
|
+
* message bundle) to the given fork. Unlike {@link mockBlock}, the caller chooses the `indexWithinCheckpoint`, so
|
|
48
|
+
* non-first blocks can carry message bundles — exercising the per-block message insertion path.
|
|
49
|
+
*/ export async function mockBlockWithIndex(blockNum, indexWithinCheckpoint, size, fork, numL1ToL2Messages = MAX_L1_TO_L2_MSGS_PER_CHECKPOINT, maxEffects = 1000) {
|
|
50
|
+
const block = await L2Block.random(blockNum, {
|
|
51
|
+
indexWithinCheckpoint: IndexWithinCheckpoint(indexWithinCheckpoint),
|
|
52
|
+
txsPerBlock: size,
|
|
53
|
+
txOptions: {
|
|
54
|
+
maxEffects
|
|
55
|
+
}
|
|
56
|
+
});
|
|
57
|
+
const l1ToL2Messages = mockL1ToL2Messages(numL1ToL2Messages);
|
|
58
|
+
await updateBlockState(block, l1ToL2Messages, fork);
|
|
59
|
+
return {
|
|
60
|
+
block,
|
|
61
|
+
messages: l1ToL2Messages
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
export async function mockEmptyBlock(blockNum, fork) {
|
|
65
|
+
const l2Block = L2Block.empty();
|
|
66
|
+
const l1ToL2Messages = Array(16).fill(0).map(Fr.zero);
|
|
67
|
+
l2Block.header.globalVariables.blockNumber = blockNum;
|
|
68
|
+
await updateBlockState(l2Block, l1ToL2Messages, fork);
|
|
69
|
+
return {
|
|
70
|
+
block: l2Block,
|
|
71
|
+
messages: l1ToL2Messages
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
export async function mockBlocks(from, count, numTxs, worldState) {
|
|
75
|
+
const tempFork = await worldState.fork(BlockNumber(from - 1));
|
|
76
|
+
const blocks = [];
|
|
77
|
+
const messagesArray = [];
|
|
78
|
+
for(let blockNumber = from; blockNumber < from + count; blockNumber++){
|
|
79
|
+
const { block, messages } = await mockBlock(BlockNumber(blockNumber), numTxs, tempFork);
|
|
80
|
+
blocks.push(block);
|
|
81
|
+
messagesArray.push(messages);
|
|
82
|
+
}
|
|
83
|
+
await tempFork.close();
|
|
84
|
+
return {
|
|
85
|
+
blocks,
|
|
86
|
+
messages: messagesArray
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
export async function mockCheckpoint(checkpointNumber, fork, options = {}) {
|
|
90
|
+
const { checkpoint, messages } = await mockCheckpointAndMessages(checkpointNumber, options);
|
|
91
|
+
await asyncMap(checkpoint.blocks, async (block, i)=>{
|
|
92
|
+
await updateBlockState(block, i === 0 ? messages : [], fork);
|
|
93
|
+
});
|
|
94
|
+
return {
|
|
95
|
+
checkpoint,
|
|
96
|
+
messages
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
export async function assertSameState(forkA, forkB) {
|
|
100
|
+
const nativeStateRef = await forkA.getStateReference();
|
|
101
|
+
const nativeArchive = await forkA.getTreeInfo(MerkleTreeId.ARCHIVE);
|
|
102
|
+
const legacyStateRef = await forkB.getStateReference();
|
|
103
|
+
const legacyArchive = await forkB.getTreeInfo(MerkleTreeId.ARCHIVE);
|
|
104
|
+
expect(nativeStateRef).toEqual(legacyStateRef);
|
|
105
|
+
expect(nativeArchive).toEqual(legacyArchive);
|
|
106
|
+
}
|
|
107
|
+
export async function compareChains(left, right) {
|
|
108
|
+
for (const treeId of [
|
|
109
|
+
MerkleTreeId.ARCHIVE,
|
|
110
|
+
MerkleTreeId.L1_TO_L2_MESSAGE_TREE,
|
|
111
|
+
MerkleTreeId.NOTE_HASH_TREE,
|
|
112
|
+
MerkleTreeId.NULLIFIER_TREE,
|
|
113
|
+
MerkleTreeId.PUBLIC_DATA_TREE
|
|
114
|
+
]){
|
|
115
|
+
expect(await left.getTreeInfo(treeId)).toEqual(await right.getTreeInfo(treeId));
|
|
116
|
+
expect(await left.getSiblingPath(treeId, 0n)).toEqual(await right.getSiblingPath(treeId, 0n));
|
|
117
|
+
}
|
|
118
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Fr } from '@aztec-labs/foundation/curves/bn254';
|
|
2
|
+
import type { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
|
|
3
|
+
import { PublicDataTreeLeaf } from '@aztec-labs/stdlib/trees';
|
|
4
|
+
import type { GenesisData } from '@aztec-labs/stdlib/world-state';
|
|
5
|
+
export declare const defaultInitialAccountFeeJuice: Fr;
|
|
6
|
+
export declare function getGenesisValues(initialAccounts: AztecAddress[], initialAccountFeeJuice?: Fr, genesisPublicData?: PublicDataTreeLeaf[], genesisTimestamp?: bigint, prefilledNullifiers?: Fr[]): Promise<{
|
|
7
|
+
genesisArchiveRoot: Fr;
|
|
8
|
+
genesis: GenesisData;
|
|
9
|
+
fundingNeeded: bigint;
|
|
10
|
+
}>;
|
|
11
|
+
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaW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