@aztec/validator-client 5.0.0-private.20260318 → 5.0.0-rc.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.
@@ -1,606 +0,0 @@
1
- function _ts_add_disposable_resource(env, value, async) {
2
- if (value !== null && value !== void 0) {
3
- if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
- var dispose, inner;
5
- if (async) {
6
- if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
- dispose = value[Symbol.asyncDispose];
8
- }
9
- if (dispose === void 0) {
10
- if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
- dispose = value[Symbol.dispose];
12
- if (async) inner = dispose;
13
- }
14
- if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
- if (inner) dispose = function() {
16
- try {
17
- inner.call(this);
18
- } catch (e) {
19
- return Promise.reject(e);
20
- }
21
- };
22
- env.stack.push({
23
- value: value,
24
- dispose: dispose,
25
- async: async
26
- });
27
- } else if (async) {
28
- env.stack.push({
29
- async: true
30
- });
31
- }
32
- return value;
33
- }
34
- function _ts_dispose_resources(env) {
35
- var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
36
- var e = new Error(message);
37
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
38
- };
39
- return (_ts_dispose_resources = function _ts_dispose_resources(env) {
40
- function fail(e) {
41
- env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
42
- env.hasError = true;
43
- }
44
- var r, s = 0;
45
- function next() {
46
- while(r = env.stack.pop()){
47
- try {
48
- if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
49
- if (r.dispose) {
50
- var result = r.dispose.call(r.value);
51
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
52
- fail(e);
53
- return next();
54
- });
55
- } else s |= 1;
56
- } catch (e) {
57
- fail(e);
58
- }
59
- }
60
- if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
61
- if (env.hasError) throw env.error;
62
- }
63
- return next();
64
- })(env);
65
- }
66
- import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
67
- import { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
68
- import { pick } from '@aztec/foundation/collection';
69
- import { Fr } from '@aztec/foundation/curves/bn254';
70
- import { TimeoutError } from '@aztec/foundation/error';
71
- import { createLogger } from '@aztec/foundation/log';
72
- import { retryUntil } from '@aztec/foundation/retry';
73
- import { DateProvider, Timer } from '@aztec/foundation/timer';
74
- import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
75
- import { Gas } from '@aztec/stdlib/gas';
76
- import { computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
77
- import { MerkleTreeId } from '@aztec/stdlib/trees';
78
- import { ReExFailedTxsError, ReExInitialStateMismatchError, ReExStateMismatchError, ReExTimeoutError, TransactionsNotAvailableError } from '@aztec/stdlib/validators';
79
- import { getTelemetryClient } from '@aztec/telemetry-client';
80
- export class BlockProposalHandler {
81
- checkpointsBuilder;
82
- worldState;
83
- blockSource;
84
- l1ToL2MessageSource;
85
- txProvider;
86
- blockProposalValidator;
87
- epochCache;
88
- config;
89
- metrics;
90
- dateProvider;
91
- log;
92
- tracer;
93
- constructor(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, metrics, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator:block-proposal-handler')){
94
- this.checkpointsBuilder = checkpointsBuilder;
95
- this.worldState = worldState;
96
- this.blockSource = blockSource;
97
- this.l1ToL2MessageSource = l1ToL2MessageSource;
98
- this.txProvider = txProvider;
99
- this.blockProposalValidator = blockProposalValidator;
100
- this.epochCache = epochCache;
101
- this.config = config;
102
- this.metrics = metrics;
103
- this.dateProvider = dateProvider;
104
- this.log = log;
105
- if (config.fishermanMode) {
106
- this.log = this.log.createChild('[FISHERMAN]');
107
- }
108
- this.tracer = telemetry.getTracer('BlockProposalHandler');
109
- }
110
- register(p2pClient, shouldReexecute) {
111
- // Non-validator handler that processes or re-executes for monitoring but does not attest.
112
- // Returns boolean indicating whether the proposal was valid.
113
- const handler = async (proposal, proposalSender)=>{
114
- try {
115
- const { slotNumber, blockNumber } = proposal;
116
- const result = await this.handleBlockProposal(proposal, proposalSender, shouldReexecute);
117
- if (result.isValid) {
118
- this.log.info(`Non-validator block proposal ${blockNumber} at slot ${slotNumber} handled`, {
119
- blockNumber: result.blockNumber,
120
- slotNumber,
121
- reexecutionTimeMs: result.reexecutionResult?.reexecutionTimeMs,
122
- totalManaUsed: result.reexecutionResult?.totalManaUsed,
123
- numTxs: result.reexecutionResult?.block?.body?.txEffects?.length ?? 0,
124
- reexecuted: shouldReexecute
125
- });
126
- return true;
127
- } else {
128
- this.log.warn(`Non-validator block proposal ${blockNumber} at slot ${slotNumber} failed processing with ${result.reason}`, {
129
- blockNumber: result.blockNumber,
130
- slotNumber,
131
- reason: result.reason
132
- });
133
- return false;
134
- }
135
- } catch (error) {
136
- this.log.error('Error processing block proposal in non-validator handler', error);
137
- return false;
138
- }
139
- };
140
- p2pClient.registerBlockProposalHandler(handler);
141
- return this;
142
- }
143
- async handleBlockProposal(proposal, proposalSender, shouldReexecute) {
144
- const slotNumber = proposal.slotNumber;
145
- const proposer = proposal.getSender();
146
- const config = this.checkpointsBuilder.getConfig();
147
- // Reject proposals with invalid signatures
148
- if (!proposer) {
149
- this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
150
- return {
151
- isValid: false,
152
- reason: 'invalid_proposal'
153
- };
154
- }
155
- const proposalInfo = {
156
- ...proposal.toBlockInfo(),
157
- proposer: proposer.toString(),
158
- blockNumber: undefined,
159
- checkpointNumber: undefined
160
- };
161
- this.log.info(`Processing proposal for slot ${slotNumber}`, {
162
- ...proposalInfo,
163
- txHashes: proposal.txHashes.map((t)=>t.toString())
164
- });
165
- // Check that the proposal is from the current proposer, or the next proposer
166
- // This should have been handled by the p2p layer, but we double check here out of caution
167
- const validationResult = await this.blockProposalValidator.validate(proposal);
168
- if (validationResult.result !== 'accept') {
169
- this.log.warn(`Proposal is not valid, skipping processing`, proposalInfo);
170
- return {
171
- isValid: false,
172
- reason: 'invalid_proposal'
173
- };
174
- }
175
- // Ensure the block source is synced before checking for existing blocks,
176
- // since a pending checkpoint prune may remove blocks we'd otherwise find.
177
- // This affects mostly the block_number_already_exists check, since a pending
178
- // checkpoint prune could remove a block that would conflict with this proposal.
179
- // TODO(@Maddiaa0): This may break staggered slots.
180
- const blockSourceSync = await this.waitForBlockSourceSync(slotNumber);
181
- if (!blockSourceSync) {
182
- this.log.warn(`Block source is not synced, skipping processing`, proposalInfo);
183
- return {
184
- isValid: false,
185
- reason: 'block_source_not_synced'
186
- };
187
- }
188
- // Check that the parent proposal is a block we know, otherwise reexecution would fail.
189
- // If we don't find it immediately, we keep retrying for a while; it may be we still
190
- // need to process other block proposals to get to it.
191
- const parentBlock = await this.getParentBlock(proposal);
192
- if (parentBlock === undefined) {
193
- this.log.warn(`Parent block for proposal not found, skipping processing`, proposalInfo);
194
- return {
195
- isValid: false,
196
- reason: 'parent_block_not_found'
197
- };
198
- }
199
- // Check that the parent block's slot is not greater than the proposal's slot.
200
- if (parentBlock !== 'genesis' && parentBlock.header.getSlot() > slotNumber) {
201
- this.log.warn(`Parent block slot is greater than proposal slot, skipping processing`, {
202
- parentBlockSlot: parentBlock.header.getSlot().toString(),
203
- proposalSlot: slotNumber.toString(),
204
- ...proposalInfo
205
- });
206
- return {
207
- isValid: false,
208
- reason: 'parent_block_wrong_slot'
209
- };
210
- }
211
- // Compute the block number based on the parent block
212
- const blockNumber = parentBlock === 'genesis' ? BlockNumber(INITIAL_L2_BLOCK_NUM) : BlockNumber(parentBlock.header.getBlockNumber() + 1);
213
- proposalInfo.blockNumber = blockNumber;
214
- // Check that this block number does not exist already
215
- const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
216
- if (existingBlock) {
217
- this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
218
- return {
219
- isValid: false,
220
- blockNumber,
221
- reason: 'block_number_already_exists'
222
- };
223
- }
224
- // Collect txs from the proposal. We start doing this as early as possible,
225
- // and we do it even if we don't plan to re-execute the txs, so that we have them if another node needs them.
226
- const { txs, missingTxs } = await this.txProvider.getTxsForBlockProposal(proposal, blockNumber, {
227
- pinnedPeer: proposalSender,
228
- deadline: this.getReexecutionDeadline(slotNumber, config)
229
- });
230
- // If reexecution is disabled, bail. We were just interested in triggering tx collection.
231
- if (!shouldReexecute) {
232
- this.log.info(`Received valid block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, proposalInfo);
233
- return {
234
- isValid: true,
235
- blockNumber
236
- };
237
- }
238
- // Compute the checkpoint number for this block and validate checkpoint consistency
239
- const checkpointResult = this.computeCheckpointNumber(proposal, parentBlock, proposalInfo);
240
- if (checkpointResult.reason) {
241
- return {
242
- isValid: false,
243
- blockNumber,
244
- reason: checkpointResult.reason
245
- };
246
- }
247
- const checkpointNumber = checkpointResult.checkpointNumber;
248
- proposalInfo.checkpointNumber = checkpointNumber;
249
- // Check that I have the same set of l1ToL2Messages as the proposal
250
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
251
- const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
252
- const proposalInHash = proposal.inHash;
253
- if (!computedInHash.equals(proposalInHash)) {
254
- this.log.warn(`L1 to L2 messages in hash mismatch, skipping processing`, {
255
- proposalInHash: proposalInHash.toString(),
256
- computedInHash: computedInHash.toString(),
257
- ...proposalInfo
258
- });
259
- return {
260
- isValid: false,
261
- blockNumber,
262
- reason: 'in_hash_mismatch'
263
- };
264
- }
265
- // Check that all of the transactions in the proposal are available
266
- if (missingTxs.length > 0) {
267
- this.log.warn(`Missing ${missingTxs.length} txs to process proposal`, {
268
- ...proposalInfo,
269
- missingTxs
270
- });
271
- return {
272
- isValid: false,
273
- blockNumber,
274
- reason: 'txs_not_available'
275
- };
276
- }
277
- // Collect the out hashes of all the checkpoints before this one in the same epoch
278
- const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
279
- const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch)).filter((c)=>c.checkpointNumber < checkpointNumber).map((c)=>c.checkpointOutHash);
280
- // Try re-executing the transactions in the proposal if needed
281
- let reexecutionResult;
282
- try {
283
- this.log.verbose(`Re-executing transactions in the proposal`, proposalInfo);
284
- reexecutionResult = await this.reexecuteTransactions(proposal, blockNumber, checkpointNumber, txs, l1ToL2Messages, previousCheckpointOutHashes);
285
- } catch (error) {
286
- this.log.error(`Error reexecuting txs while processing block proposal`, error, proposalInfo);
287
- const reason = this.getReexecuteFailureReason(error);
288
- return {
289
- isValid: false,
290
- blockNumber,
291
- reason,
292
- reexecutionResult
293
- };
294
- }
295
- // If we succeeded, push this block into the archiver (unless disabled)
296
- if (reexecutionResult?.block && this.config.skipPushProposedBlocksToArchiver === false) {
297
- await this.blockSource.addBlock(reexecutionResult?.block);
298
- }
299
- this.log.info(`Successfully re-executed block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, {
300
- ...proposalInfo,
301
- ...pick(reexecutionResult, 'reexecutionTimeMs', 'totalManaUsed')
302
- });
303
- return {
304
- isValid: true,
305
- blockNumber,
306
- reexecutionResult
307
- };
308
- }
309
- async getParentBlock(proposal) {
310
- const parentArchive = proposal.blockHeader.lastArchive.root;
311
- const slot = proposal.slotNumber;
312
- const config = this.checkpointsBuilder.getConfig();
313
- const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
314
- if (parentArchive.equals(genesisArchiveRoot)) {
315
- return 'genesis';
316
- }
317
- const deadline = this.getReexecutionDeadline(slot, config);
318
- const currentTime = this.dateProvider.now();
319
- const timeoutDurationMs = deadline.getTime() - currentTime;
320
- try {
321
- return await this.blockSource.getBlockDataByArchive(parentArchive) ?? (timeoutDurationMs <= 0 ? undefined : await retryUntil(()=>this.blockSource.syncImmediate().then(()=>this.blockSource.getBlockDataByArchive(parentArchive)), 'force archiver sync', timeoutDurationMs / 1000, 0.5));
322
- } catch (err) {
323
- if (err instanceof TimeoutError) {
324
- this.log.debug(`Timed out getting parent block by archive root`, {
325
- parentArchive
326
- });
327
- } else {
328
- this.log.error('Error getting parent block by archive root', err, {
329
- parentArchive
330
- });
331
- }
332
- return undefined;
333
- }
334
- }
335
- computeCheckpointNumber(proposal, parentBlock, proposalInfo) {
336
- if (parentBlock === 'genesis') {
337
- // First block is in checkpoint 1
338
- if (proposal.indexWithinCheckpoint !== 0) {
339
- this.log.warn(`First block proposal has non-zero indexWithinCheckpoint`, proposalInfo);
340
- return {
341
- reason: 'invalid_proposal'
342
- };
343
- }
344
- return {
345
- checkpointNumber: CheckpointNumber.INITIAL
346
- };
347
- }
348
- if (proposal.indexWithinCheckpoint === 0) {
349
- // If this is the first block in a new checkpoint, increment the checkpoint number
350
- if (!(proposal.blockHeader.getSlot() > parentBlock.header.getSlot())) {
351
- this.log.warn(`Slot should be greater than parent block slot for first block in checkpoint`, proposalInfo);
352
- return {
353
- reason: 'invalid_proposal'
354
- };
355
- }
356
- return {
357
- checkpointNumber: CheckpointNumber(parentBlock.checkpointNumber + 1)
358
- };
359
- }
360
- // Otherwise it should follow the previous block in the same checkpoint
361
- if (proposal.indexWithinCheckpoint !== parentBlock.indexWithinCheckpoint + 1) {
362
- this.log.warn(`Non-sequential indexWithinCheckpoint`, proposalInfo);
363
- return {
364
- reason: 'invalid_proposal'
365
- };
366
- }
367
- if (proposal.blockHeader.getSlot() !== parentBlock.header.getSlot()) {
368
- this.log.warn(`Slot should be equal to parent block slot for non-first block in checkpoint`, proposalInfo);
369
- return {
370
- reason: 'invalid_proposal'
371
- };
372
- }
373
- // For non-first blocks in a checkpoint, validate global variables match parent (except blockNumber)
374
- const validationResult = this.validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo);
375
- if (validationResult) {
376
- return validationResult;
377
- }
378
- return {
379
- checkpointNumber: parentBlock.checkpointNumber
380
- };
381
- }
382
- /**
383
- * Validates that a non-first block in a checkpoint has consistent global variables with its parent.
384
- * For blocks with indexWithinCheckpoint > 0, all global variables except blockNumber must match the parent.
385
- * @returns A failure result if validation fails, undefined if validation passes
386
- */ validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo) {
387
- const proposalGlobals = proposal.blockHeader.globalVariables;
388
- const parentGlobals = parentBlock.header.globalVariables;
389
- // All global variables except blockNumber should match the parent
390
- // blockNumber naturally increments between blocks
391
- if (!proposalGlobals.chainId.equals(parentGlobals.chainId)) {
392
- this.log.warn(`Non-first block in checkpoint has mismatched chainId`, {
393
- ...proposalInfo,
394
- proposalChainId: proposalGlobals.chainId.toString(),
395
- parentChainId: parentGlobals.chainId.toString()
396
- });
397
- return {
398
- reason: 'global_variables_mismatch'
399
- };
400
- }
401
- if (!proposalGlobals.version.equals(parentGlobals.version)) {
402
- this.log.warn(`Non-first block in checkpoint has mismatched version`, {
403
- ...proposalInfo,
404
- proposalVersion: proposalGlobals.version.toString(),
405
- parentVersion: parentGlobals.version.toString()
406
- });
407
- return {
408
- reason: 'global_variables_mismatch'
409
- };
410
- }
411
- if (proposalGlobals.slotNumber !== parentGlobals.slotNumber) {
412
- this.log.warn(`Non-first block in checkpoint has mismatched slotNumber`, {
413
- ...proposalInfo,
414
- proposalSlotNumber: proposalGlobals.slotNumber,
415
- parentSlotNumber: parentGlobals.slotNumber
416
- });
417
- return {
418
- reason: 'global_variables_mismatch'
419
- };
420
- }
421
- if (proposalGlobals.timestamp !== parentGlobals.timestamp) {
422
- this.log.warn(`Non-first block in checkpoint has mismatched timestamp`, {
423
- ...proposalInfo,
424
- proposalTimestamp: proposalGlobals.timestamp.toString(),
425
- parentTimestamp: parentGlobals.timestamp.toString()
426
- });
427
- return {
428
- reason: 'global_variables_mismatch'
429
- };
430
- }
431
- if (!proposalGlobals.coinbase.equals(parentGlobals.coinbase)) {
432
- this.log.warn(`Non-first block in checkpoint has mismatched coinbase`, {
433
- ...proposalInfo,
434
- proposalCoinbase: proposalGlobals.coinbase.toString(),
435
- parentCoinbase: parentGlobals.coinbase.toString()
436
- });
437
- return {
438
- reason: 'global_variables_mismatch'
439
- };
440
- }
441
- if (!proposalGlobals.feeRecipient.equals(parentGlobals.feeRecipient)) {
442
- this.log.warn(`Non-first block in checkpoint has mismatched feeRecipient`, {
443
- ...proposalInfo,
444
- proposalFeeRecipient: proposalGlobals.feeRecipient.toString(),
445
- parentFeeRecipient: parentGlobals.feeRecipient.toString()
446
- });
447
- return {
448
- reason: 'global_variables_mismatch'
449
- };
450
- }
451
- if (!proposalGlobals.gasFees.equals(parentGlobals.gasFees)) {
452
- this.log.warn(`Non-first block in checkpoint has mismatched gasFees`, {
453
- ...proposalInfo,
454
- proposalGasFees: proposalGlobals.gasFees.toInspect(),
455
- parentGasFees: parentGlobals.gasFees.toInspect()
456
- });
457
- return {
458
- reason: 'global_variables_mismatch'
459
- };
460
- }
461
- return undefined;
462
- }
463
- getReexecutionDeadline(slot, config) {
464
- const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
465
- return new Date(nextSlotTimestampSeconds * 1000);
466
- }
467
- /** Waits for the block source to sync L1 data up to at least the slot before the given one. */ async waitForBlockSourceSync(slot) {
468
- const deadline = this.getReexecutionDeadline(slot, this.checkpointsBuilder.getConfig());
469
- const timeoutMs = deadline.getTime() - this.dateProvider.now();
470
- if (slot === 0) {
471
- return true;
472
- }
473
- // Make a quick check before triggering an archiver sync
474
- const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
475
- if (syncedSlot !== undefined && syncedSlot + 1 >= slot) {
476
- return true;
477
- }
478
- try {
479
- // Trigger an immediate sync of the block source, and wait until it reports being synced to the required slot
480
- return await retryUntil(async ()=>{
481
- await this.blockSource.syncImmediate();
482
- const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
483
- return syncedSlot !== undefined && syncedSlot + 1 >= slot;
484
- }, 'wait for block source sync', timeoutMs / 1000, 0.5);
485
- } catch (err) {
486
- if (err instanceof TimeoutError) {
487
- this.log.warn(`Timed out waiting for block source to sync to slot ${slot}`);
488
- return false;
489
- } else {
490
- throw err;
491
- }
492
- }
493
- }
494
- getReexecuteFailureReason(err) {
495
- if (err instanceof ReExInitialStateMismatchError) {
496
- return 'initial_state_mismatch';
497
- } else if (err instanceof ReExStateMismatchError) {
498
- return 'state_mismatch';
499
- } else if (err instanceof ReExFailedTxsError) {
500
- return 'failed_txs';
501
- } else if (err instanceof ReExTimeoutError) {
502
- return 'timeout';
503
- } else {
504
- return 'unknown_error';
505
- }
506
- }
507
- async reexecuteTransactions(proposal, blockNumber, checkpointNumber, txs, l1ToL2Messages, previousCheckpointOutHashes) {
508
- const env = {
509
- stack: [],
510
- error: void 0,
511
- hasError: false
512
- };
513
- try {
514
- const { blockHeader, txHashes } = proposal;
515
- // If we do not have all of the transactions, then we should fail
516
- if (txs.length !== txHashes.length) {
517
- const foundTxHashes = txs.map((tx)=>tx.getTxHash());
518
- const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.includes(txHash));
519
- throw new TransactionsNotAvailableError(missingTxHashes);
520
- }
521
- const timer = new Timer();
522
- const slot = proposal.slotNumber;
523
- const config = this.checkpointsBuilder.getConfig();
524
- // Get prior blocks in this checkpoint (same slot before current block)
525
- const allBlocksInSlot = await this.blockSource.getBlocksForSlot(slot);
526
- const priorBlocks = allBlocksInSlot.filter((b)=>b.number < blockNumber && b.header.getSlot() === slot);
527
- // Fork before the block to be built
528
- const parentBlockNumber = BlockNumber(blockNumber - 1);
529
- await this.worldState.syncImmediate(parentBlockNumber);
530
- const fork = _ts_add_disposable_resource(env, await this.worldState.fork(parentBlockNumber), true);
531
- // Verify the fork's archive root matches the proposal's expected last archive.
532
- // If they don't match, our world state synced to a different chain and reexecution would fail.
533
- const forkArchiveRoot = new Fr((await fork.getTreeInfo(MerkleTreeId.ARCHIVE)).root);
534
- if (!forkArchiveRoot.equals(proposal.blockHeader.lastArchive.root)) {
535
- throw new ReExInitialStateMismatchError(proposal.blockHeader.lastArchive.root, forkArchiveRoot);
536
- }
537
- // Build checkpoint constants from proposal (excludes blockNumber which is per-block)
538
- const constants = {
539
- chainId: new Fr(config.l1ChainId),
540
- version: new Fr(config.rollupVersion),
541
- slotNumber: slot,
542
- timestamp: blockHeader.globalVariables.timestamp,
543
- coinbase: blockHeader.globalVariables.coinbase,
544
- feeRecipient: blockHeader.globalVariables.feeRecipient,
545
- gasFees: blockHeader.globalVariables.gasFees
546
- };
547
- // Create checkpoint builder with prior blocks
548
- const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, 0n, l1ToL2Messages, previousCheckpointOutHashes, fork, priorBlocks, this.log.getBindings());
549
- // Build the new block
550
- const deadline = this.getReexecutionDeadline(slot, config);
551
- const maxBlockGas = this.config.validateMaxL2BlockGas !== undefined || this.config.validateMaxDABlockGas !== undefined ? new Gas(this.config.validateMaxDABlockGas ?? Infinity, this.config.validateMaxL2BlockGas ?? Infinity) : undefined;
552
- const result = await checkpointBuilder.buildBlock(txs, blockNumber, blockHeader.globalVariables.timestamp, {
553
- deadline,
554
- expectedEndState: blockHeader.state,
555
- maxTransactions: this.config.validateMaxTxsPerBlock,
556
- maxBlockGas
557
- });
558
- const { block, failedTxs } = result;
559
- const numFailedTxs = failedTxs.length;
560
- this.log.verbose(`Block proposal ${blockNumber} at slot ${slot} transaction re-execution complete`, {
561
- numFailedTxs,
562
- numProposalTxs: txHashes.length,
563
- numProcessedTxs: block.body.txEffects.length,
564
- blockNumber,
565
- slot
566
- });
567
- if (numFailedTxs > 0) {
568
- this.metrics?.recordFailedReexecution(proposal);
569
- throw new ReExFailedTxsError(numFailedTxs);
570
- }
571
- if (block.body.txEffects.length !== txHashes.length) {
572
- this.metrics?.recordFailedReexecution(proposal);
573
- throw new ReExTimeoutError();
574
- }
575
- // Throw a ReExStateMismatchError error if state updates do not match
576
- // Compare the full block structure (archive and header) from the built block with the proposal
577
- const archiveMatches = proposal.archive.equals(block.archive.root);
578
- const headerMatches = proposal.blockHeader.equals(block.header);
579
- if (!archiveMatches || !headerMatches) {
580
- this.log.warn(`Re-execution state mismatch for slot ${slot}`, {
581
- expectedArchive: block.archive.root.toString(),
582
- actualArchive: proposal.archive.toString(),
583
- expectedHeader: block.header.toInspect(),
584
- actualHeader: proposal.blockHeader.toInspect()
585
- });
586
- this.metrics?.recordFailedReexecution(proposal);
587
- throw new ReExStateMismatchError(proposal.archive, block.archive.root);
588
- }
589
- const reexecutionTimeMs = timer.ms();
590
- const totalManaUsed = block.header.totalManaUsed.toNumber() / 1e6;
591
- this.metrics?.recordReex(reexecutionTimeMs, txs.length, totalManaUsed);
592
- return {
593
- block,
594
- failedTxs,
595
- reexecutionTimeMs,
596
- totalManaUsed
597
- };
598
- } catch (e) {
599
- env.error = e;
600
- env.hasError = true;
601
- } finally{
602
- const result = _ts_dispose_resources(env);
603
- if (result) await result;
604
- }
605
- }
606
- }