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