@aztec/validator-client 5.0.0-private.20260319 → 5.0.0-rc.2

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.
@@ -0,0 +1,1207 @@
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 { encodeCheckpointBlobDataFromBlocks, getBlobsPerL1Block } from '@aztec/blob-lib';
67
+ import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
68
+ import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
69
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
70
+ import { pick } from '@aztec/foundation/collection';
71
+ import { Fr } from '@aztec/foundation/curves/bn254';
72
+ import { TimeoutError } from '@aztec/foundation/error';
73
+ import { FifoSet } from '@aztec/foundation/fifo-set';
74
+ import { createLogger } from '@aztec/foundation/log';
75
+ import { retryUntil } from '@aztec/foundation/retry';
76
+ import { DateProvider, Timer } from '@aztec/foundation/timer';
77
+ import { getPreviousCheckpointOutHashes, validateCheckpoint } from '@aztec/stdlib/checkpoint';
78
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
79
+ import { Gas } from '@aztec/stdlib/gas';
80
+ import { accumulateCheckpointOutHashes, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
81
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
82
+ import { ReExFailedTxsError, ReExInitialStateMismatchError, ReExStateMismatchError, ReExTimeoutError, TransactionsNotAvailableError } from '@aztec/stdlib/validators';
83
+ import { getTelemetryClient } from '@aztec/telemetry-client';
84
+ /**
85
+ * Mapping from a checkpoint-proposal validation failure reason to the tracker outcome that
86
+ * `handleCheckpointProposal` should record. `undefined` means do not record (signature
87
+ * couldn't be verified, or the checkpoint is already on L1 so the question is moot).
88
+ */ /* eslint-disable camelcase */ const CHECKPOINT_VALIDATION_REASON_TO_OUTCOME = {
89
+ invalid_signature: undefined,
90
+ invalid_fee_asset_price_modifier: 'invalid',
91
+ checkpoint_already_published: undefined,
92
+ last_block_not_found: 'unvalidated',
93
+ block_fetch_error: 'unvalidated',
94
+ no_blocks_for_slot: 'unvalidated',
95
+ last_block_archive_mismatch: 'invalid',
96
+ too_many_blocks_in_checkpoint: 'invalid',
97
+ checkpoint_header_mismatch: 'invalid',
98
+ archive_mismatch: 'invalid',
99
+ out_hash_mismatch: 'invalid',
100
+ checkpoint_validation_failed: 'invalid'
101
+ };
102
+ const MAX_TRACKED_INVALID_PROPOSAL_SLOTS = 1000;
103
+ /** Block-proposal validation failures that constitute a slashable invalid-block offense. */ export const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
104
+ 'state_mismatch',
105
+ 'failed_txs',
106
+ 'global_variables_mismatch',
107
+ 'invalid_proposal',
108
+ 'parent_block_wrong_slot',
109
+ 'in_hash_mismatch'
110
+ ];
111
+ /** Checkpoint-proposal validation failures that constitute a slashable invalid-checkpoint offense. */ export const SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT = {
112
+ // enabled
113
+ ['invalid_fee_asset_price_modifier']: true,
114
+ ['checkpoint_header_mismatch']: true,
115
+ // These late mismatches should normally be caught by earlier checks, but if reached after validating the local
116
+ // checkpoint inputs, the proposer-signed payload disagrees with deterministic recomputation.
117
+ ['archive_mismatch']: true,
118
+ ['out_hash_mismatch']: true,
119
+ ['no_blocks_for_slot']: true,
120
+ ['too_many_blocks_in_checkpoint']: true,
121
+ ['checkpoint_validation_failed']: true,
122
+ ['last_block_archive_mismatch']: true,
123
+ // disabled
124
+ ['invalid_signature']: false,
125
+ ['last_block_not_found']: false,
126
+ ['block_fetch_error']: false,
127
+ ['checkpoint_already_published']: false
128
+ };
129
+ /**
130
+ * Handles block and checkpoint proposals for both validator and non-validator nodes. Also tracks which slots
131
+ * had a slashable invalid proposal or a proposal equivocation, exposing them via the
132
+ * `InvalidProposalSlotSource` interface consumed by the attested-invalid-proposal slashing watcher. The
133
+ * tracking is populated as a side effect of validating/re-executing proposals, so any node that re-executes
134
+ * proposals (the default) can serve it — not only validators.
135
+ */ export class ProposalHandler {
136
+ checkpointsBuilder;
137
+ worldState;
138
+ blockSource;
139
+ l1ToL2MessageSource;
140
+ txProvider;
141
+ blockProposalValidator;
142
+ epochCache;
143
+ timetable;
144
+ config;
145
+ blobClient;
146
+ reexecutionTracker;
147
+ metrics;
148
+ dateProvider;
149
+ log;
150
+ tracer;
151
+ /** Cached last checkpoint validation result to avoid double-validation on validator nodes.
152
+ * Keyed by signed-payload hash so two proposals at the same (slot, archive) but with a
153
+ * different `feeAssetPriceModifier` (or any other signed field) are validated independently. */ lastCheckpointValidationResult;
154
+ /** Archiver reference for setting proposed checkpoints (pipelining). Set via register(). */ archiver;
155
+ /** Returns current validator addresses for own-proposal detection. Set via register(). */ getOwnValidatorAddresses;
156
+ /** P2P proposal pool access for deciding when retained proposals should block archiver processing. */ p2pClient;
157
+ checkpointProposalValidationFailureCallback;
158
+ /** Slots at which a slashable invalid block or checkpoint proposal was observed. */ slotsWithInvalidProposals;
159
+ /** Slots at which a proposal equivocation was observed; suppresses attested-to-invalid-proposal slashing. */ slotsWithProposalEquivocation;
160
+ constructor(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, timetable, config, blobClient, reexecutionTracker, metrics, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator:proposal-handler')){
161
+ this.checkpointsBuilder = checkpointsBuilder;
162
+ this.worldState = worldState;
163
+ this.blockSource = blockSource;
164
+ this.l1ToL2MessageSource = l1ToL2MessageSource;
165
+ this.txProvider = txProvider;
166
+ this.blockProposalValidator = blockProposalValidator;
167
+ this.epochCache = epochCache;
168
+ this.timetable = timetable;
169
+ this.config = config;
170
+ this.blobClient = blobClient;
171
+ this.reexecutionTracker = reexecutionTracker;
172
+ this.metrics = metrics;
173
+ this.dateProvider = dateProvider;
174
+ this.log = log;
175
+ this.slotsWithInvalidProposals = FifoSet.withLimit(MAX_TRACKED_INVALID_PROPOSAL_SLOTS);
176
+ this.slotsWithProposalEquivocation = FifoSet.withLimit(MAX_TRACKED_INVALID_PROPOSAL_SLOTS);
177
+ if (config.fishermanMode) {
178
+ this.log = this.log.createChild('[FISHERMAN]');
179
+ }
180
+ this.tracer = telemetry.getTracer('ProposalHandler');
181
+ }
182
+ updateConfig(config) {
183
+ this.config = {
184
+ ...this.config,
185
+ ...config
186
+ };
187
+ }
188
+ setCheckpointProposalValidationFailureCallback(callback) {
189
+ this.checkpointProposalValidationFailureCallback = callback;
190
+ }
191
+ /**
192
+ * Records the proposer's own checkpoint proposal as a `valid` outcome in the re-execution
193
+ * tracker. Without this, the node's own checkpoint proposals never flow through
194
+ * `handleCheckpointProposal` (proposers don't validate their own proposals), so its sentinel
195
+ * sees no outcome for slots where it was the proposer and reports itself as inactive.
196
+ *
197
+ * `archive` should be the locally-computed archive (NOT the broadcast archive, which may have
198
+ * been deliberately corrupted in tests via `broadcastInvalidBlockProposal` /
199
+ * `broadcastInvalidCheckpointProposalOnly`). Recording the local archive correctly models the
200
+ * proposer's own view of its own work.
201
+ */ recordOwnCheckpointProposalAsValid(slot, archive, checkpointNumber) {
202
+ this.reexecutionTracker.recordOutcome(slot, archive, 'valid', checkpointNumber);
203
+ }
204
+ /** Whether a slashable invalid block or checkpoint proposal was observed at the given slot (InvalidProposalSlotSource). */ hasInvalidProposals(slotNumber) {
205
+ return this.slotsWithInvalidProposals.has(slotNumber);
206
+ }
207
+ /** Whether a proposal equivocation was observed at the given slot (InvalidProposalSlotSource). */ hasProposalEquivocation(slotNumber) {
208
+ return this.slotsWithProposalEquivocation.has(slotNumber);
209
+ }
210
+ /** Records a slot as having a slashable invalid proposal, for offense observers (sentinel/slasher watchers). */ markInvalidProposalSlot(slotNumber) {
211
+ this.slotsWithInvalidProposals.add(slotNumber);
212
+ }
213
+ /** Records a slot as having a proposal equivocation, which suppresses attested-to-invalid-proposal slashing. */ markProposalEquivocation(slotNumber) {
214
+ this.slotsWithProposalEquivocation.add(slotNumber);
215
+ }
216
+ /**
217
+ * Registers handlers for block and checkpoint proposals on the p2p client.
218
+ * Records the p2p client so validation can inspect retained proposals.
219
+ * Block proposals are registered for non-validator nodes (validators register their own enhanced handler).
220
+ * The all-nodes checkpoint proposal handler is always registered for validation, caching, and pipelining.
221
+ * @param archiver - Archiver reference for setting proposed checkpoints (pipelining)
222
+ * @param getOwnValidatorAddresses - Returns current validator addresses for own-proposal detection
223
+ */ register(p2pClient, shouldReexecute, archiver, getOwnValidatorAddresses) {
224
+ this.p2pClient = p2pClient;
225
+ this.archiver = archiver;
226
+ this.getOwnValidatorAddresses = getOwnValidatorAddresses;
227
+ // Non-validator handler that processes or re-executes for monitoring but does not attest.
228
+ // Returns boolean indicating whether the proposal was valid.
229
+ const blockHandler = async (proposal, proposalSender)=>{
230
+ try {
231
+ const { slotNumber, blockNumber } = proposal;
232
+ const result = await this.handleBlockProposal(proposal, proposalSender, shouldReexecute);
233
+ if (result.isValid) {
234
+ this.log.info(`Non-validator block proposal ${blockNumber} at slot ${slotNumber} handled`, {
235
+ blockNumber: result.blockNumber,
236
+ slotNumber,
237
+ reexecutionTimeMs: result.reexecutionResult?.reexecutionTimeMs,
238
+ totalManaUsed: result.reexecutionResult?.totalManaUsed,
239
+ numTxs: result.reexecutionResult?.block?.body?.txEffects?.length ?? 0,
240
+ reexecuted: shouldReexecute
241
+ });
242
+ return true;
243
+ } else {
244
+ // Track invalid proposals / equivocations so offense observers (the attested-invalid-proposal
245
+ // watcher) work on non-validator nodes too. Validators populate these via their own handlers.
246
+ // Skip invalid-proposal marking while the escape hatch is open, matching the validator path,
247
+ // which intentionally disables invalid-block slashing then.
248
+ if (result.reason === 'checkpoint_proposal_equivocation') {
249
+ this.markProposalEquivocation(slotNumber);
250
+ } else if (SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(result.reason) && !await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
251
+ this.markInvalidProposalSlot(slotNumber);
252
+ }
253
+ this.log.warn(`Non-validator block proposal ${blockNumber} at slot ${slotNumber} failed processing with ${result.reason}`, {
254
+ blockNumber: result.blockNumber,
255
+ slotNumber,
256
+ reason: result.reason
257
+ });
258
+ return false;
259
+ }
260
+ } catch (error) {
261
+ this.log.error('Error processing block proposal in non-validator handler', error);
262
+ return false;
263
+ }
264
+ };
265
+ p2pClient.registerBlockProposalHandler(blockHandler);
266
+ // p2p detects duplicate (equivocated) proposals without routing them through the handlers above, so mark
267
+ // the slot as equivocated here. This suppresses false-positive attested-to-invalid-proposal slashing on
268
+ // non-validator offense collectors. Validators overwrite this with their own richer handler.
269
+ p2pClient.registerDuplicateProposalCallback((info)=>this.markProposalEquivocation(info.slot));
270
+ // All-nodes checkpoint proposal handler: validates, caches, and sets proposed checkpoint for pipelining.
271
+ // Runs for all nodes (validators and non-validators). Validators get the cached result in the
272
+ // validator-specific callback (attestToCheckpointProposal) which runs after this one.
273
+ const checkpointHandler = async (proposal, _sender)=>{
274
+ try {
275
+ const pipeliningTimer = new Timer();
276
+ const proposalInfo = {
277
+ slot: proposal.slotNumber,
278
+ archive: proposal.archive.toString(),
279
+ proposer: proposal.getSender()?.toString()
280
+ };
281
+ if (this.config.skipCheckpointProposalValidation) {
282
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposal.slotNumber}`, proposalInfo);
283
+ return undefined;
284
+ }
285
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposal.slotNumber)) {
286
+ this.log.warn(`Escape hatch open for slot ${proposal.slotNumber}, skipping checkpoint proposal validation`, proposalInfo);
287
+ return undefined;
288
+ }
289
+ // A proposal is "own" when it was signed by a validator key this node also owns. The true local
290
+ // proposer already built, validated, and stored this checkpoint before broadcasting, so a matching
291
+ // proposed checkpoint is already in its archiver — skip the redundant re-validation. An HA peer that
292
+ // shares the proposer's keys sees the same "own" proposal over gossip but never built it, so it has
293
+ // nothing stored; it falls through to the normal validate-and-persist path below to hydrate the
294
+ // proposed-checkpoint metadata it needs to build the next slot on top of this checkpoint.
295
+ const proposer = proposal.getSender();
296
+ const ownAddresses = this.getOwnValidatorAddresses?.();
297
+ const isOwnProposal = proposer && ownAddresses?.some((addr)=>addr === proposer.toString());
298
+ if (isOwnProposal) {
299
+ const existing = await this.archiver?.getProposedCheckpointData({
300
+ slot: proposal.slotNumber
301
+ });
302
+ if (existing?.archive.root.equals(proposal.archive)) {
303
+ this.log.debug(`Skipping sync for existing own checkpoint proposal at slot ${proposal.slotNumber}`);
304
+ return undefined;
305
+ }
306
+ }
307
+ const result = await this.handleCheckpointProposal(proposal, proposalInfo);
308
+ if (!result.isValid) {
309
+ // Track invalid checkpoint proposals so offense observers (the attested-invalid-proposal watcher)
310
+ // work on non-validator nodes too. This handler runs for all nodes; validators also mark via the
311
+ // failure callback below (idempotent).
312
+ if (SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT[result.reason]) {
313
+ this.markInvalidProposalSlot(proposal.slotNumber);
314
+ }
315
+ await this.checkpointProposalValidationFailureCallback?.(proposal, result, proposalInfo);
316
+ } else if (this.archiver) {
317
+ const set = await this.setProposedCheckpoint(proposal);
318
+ if (set) {
319
+ this.metrics?.recordCheckpointProposalToPipelinedStateDuration(pipeliningTimer.ms());
320
+ }
321
+ }
322
+ } catch (err) {
323
+ this.log.warn(`Error handling checkpoint proposal for slot ${proposal.slotNumber}`, {
324
+ err
325
+ });
326
+ }
327
+ return undefined;
328
+ };
329
+ p2pClient.registerAllNodesCheckpointProposalHandler(checkpointHandler);
330
+ return this;
331
+ }
332
+ async handleBlockProposal(proposal, proposalSender, shouldReexecute) {
333
+ const slotNumber = proposal.slotNumber;
334
+ const proposer = proposal.getSender();
335
+ // Reject proposals with invalid signatures
336
+ if (!proposer) {
337
+ this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
338
+ return {
339
+ isValid: false,
340
+ reason: 'invalid_signature'
341
+ };
342
+ }
343
+ const proposalInfo = {
344
+ ...proposal.toBlockInfo(),
345
+ proposer: proposer.toString(),
346
+ blockNumber: undefined,
347
+ checkpointNumber: undefined
348
+ };
349
+ this.log.info(`Processing proposal for slot ${slotNumber}`, {
350
+ ...proposalInfo,
351
+ txHashes: proposal.txHashes.map((t)=>t.toString())
352
+ });
353
+ // Check that the proposal is from the current proposer, or the next proposer
354
+ // This should have been handled by the p2p layer, but we double check here out of caution
355
+ const validationResult = await this.blockProposalValidator.validate(proposal);
356
+ if (validationResult.result !== 'accept') {
357
+ this.log.warn(`Proposal is not valid, skipping processing`, proposalInfo);
358
+ return {
359
+ isValid: false,
360
+ reason: 'invalid_proposal'
361
+ };
362
+ }
363
+ const retainedSlotValidation = await this.validateNewBlockInSlot(proposal);
364
+ if (!retainedSlotValidation.isValid) {
365
+ this.log.info(`Block proposal conflicts with retained proposals, skipping archiver processing`, {
366
+ ...proposalInfo,
367
+ indexWithinCheckpoint: proposal.indexWithinCheckpoint,
368
+ reason: retainedSlotValidation.reason
369
+ });
370
+ return {
371
+ isValid: false,
372
+ blockNumber: proposal.blockNumber,
373
+ reason: retainedSlotValidation.reason
374
+ };
375
+ }
376
+ // The proposer builds ahead of L1 submission under pipelining, so the block source won't have
377
+ // synced to the proposed slot yet. We deliberately do not wait for it to sync here, to avoid
378
+ // eating into the attestation window.
379
+ // Check that the parent proposal is a block we know, otherwise reexecution would fail.
380
+ // If we don't find it immediately, we keep retrying for a while; it may be we still
381
+ // need to process other block proposals to get to it.
382
+ const parentBlock = await this.getParentBlock(proposal);
383
+ if (parentBlock === undefined) {
384
+ this.log.warn(`Parent block for proposal not found, skipping processing`, proposalInfo);
385
+ return {
386
+ isValid: false,
387
+ reason: 'parent_block_not_found'
388
+ };
389
+ }
390
+ // Check that the parent block's slot is not greater than the proposal's slot.
391
+ if (parentBlock !== 'genesis' && parentBlock.header.getSlot() > slotNumber) {
392
+ this.log.warn(`Parent block slot is greater than proposal slot, skipping processing`, {
393
+ parentBlockSlot: parentBlock.header.getSlot().toString(),
394
+ proposalSlot: slotNumber.toString(),
395
+ ...proposalInfo
396
+ });
397
+ return {
398
+ isValid: false,
399
+ reason: 'parent_block_wrong_slot'
400
+ };
401
+ }
402
+ // Compute the block number based on the parent block
403
+ const blockNumber = parentBlock === 'genesis' ? BlockNumber(INITIAL_L2_BLOCK_NUM) : BlockNumber(parentBlock.header.getBlockNumber() + 1);
404
+ proposalInfo.blockNumber = blockNumber;
405
+ // Check that this block number does not exist already. During a reorg the archiver can still hold a
406
+ // stale block at this number (a different archive, about to be pruned) while the proposal carries the
407
+ // rebuilt replacement; resolveExistingBlockAtNumber waits for the local prune in that case so the
408
+ // rebuilt block is processed in time to attest, rather than being permanently dropped on a bare
409
+ // number collision.
410
+ const existingBlock = await this.resolveExistingBlockAtNumber(blockNumber, proposal.archive, slotNumber);
411
+ if (existingBlock) {
412
+ this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
413
+ return {
414
+ isValid: false,
415
+ blockNumber,
416
+ reason: 'block_number_already_exists'
417
+ };
418
+ }
419
+ // Collect txs from the proposal. We start doing this as early as possible,
420
+ // 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.
421
+ const { txs, missingTxs } = await this.txProvider.getTxsForBlockProposal(proposal, blockNumber, {
422
+ pinnedPeer: proposalSender,
423
+ deadline: this.getReexecutionDeadline(slotNumber)
424
+ });
425
+ // Record the tx-collection outcome on the re-execution tracker
426
+ this.reexecutionTracker.recordTxsCollected(slotNumber, proposal.indexWithinCheckpoint, missingTxs.length === 0);
427
+ // If reexecution is disabled, bail. We were just interested in triggering tx collection.
428
+ if (!shouldReexecute) {
429
+ this.log.info(`Received valid block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, proposalInfo);
430
+ return {
431
+ isValid: true,
432
+ blockNumber
433
+ };
434
+ }
435
+ // Compute the checkpoint number for this block and validate checkpoint consistency
436
+ const checkpointResult = this.computeCheckpointNumber(proposal, parentBlock, proposalInfo);
437
+ if (checkpointResult.reason) {
438
+ return {
439
+ isValid: false,
440
+ blockNumber,
441
+ reason: checkpointResult.reason
442
+ };
443
+ }
444
+ const checkpointNumber = checkpointResult.checkpointNumber;
445
+ proposalInfo.checkpointNumber = checkpointNumber;
446
+ // Check that I have the same set of l1ToL2Messages as the proposal
447
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
448
+ const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
449
+ const proposalInHash = proposal.inHash;
450
+ if (!computedInHash.equals(proposalInHash)) {
451
+ this.log.warn(`L1 to L2 messages in hash mismatch, skipping processing`, {
452
+ proposalInHash: proposalInHash.toString(),
453
+ computedInHash: computedInHash.toString(),
454
+ ...proposalInfo
455
+ });
456
+ return {
457
+ isValid: false,
458
+ blockNumber,
459
+ reason: 'in_hash_mismatch'
460
+ };
461
+ }
462
+ // Check that all of the transactions in the proposal are available
463
+ if (missingTxs.length > 0) {
464
+ this.log.warn(`Missing ${missingTxs.length} txs to process proposal`, {
465
+ ...proposalInfo,
466
+ missingTxs
467
+ });
468
+ return {
469
+ isValid: false,
470
+ blockNumber,
471
+ reason: 'txs_not_available'
472
+ };
473
+ }
474
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
475
+ // Mirror the proposer-side fallback: under pipelining the immediately-preceding cp may not
476
+ // yet be on L1, in which case the helper grafts the locally-known proposed cp's outHash.
477
+ const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
478
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
479
+ blockSource: this.blockSource,
480
+ epoch,
481
+ checkpointNumber,
482
+ l1Constants: this.epochCache.getL1Constants(),
483
+ pipeliningEnabled: true,
484
+ log: this.log
485
+ });
486
+ // Try re-executing the transactions in the proposal if needed
487
+ let reexecutionResult;
488
+ try {
489
+ this.log.verbose(`Re-executing transactions in the proposal`, proposalInfo);
490
+ reexecutionResult = await this.reexecuteTransactions(proposal, blockNumber, checkpointNumber, txs, l1ToL2Messages, previousCheckpointOutHashes);
491
+ } catch (error) {
492
+ this.log.error(`Error reexecuting txs while processing block proposal`, error, proposalInfo);
493
+ const reason = this.getReexecuteFailureReason(error);
494
+ return {
495
+ isValid: false,
496
+ blockNumber,
497
+ reason,
498
+ reexecutionResult
499
+ };
500
+ }
501
+ // If we succeeded, push this block into the archiver (unless disabled)
502
+ if (reexecutionResult?.block && this.config.skipPushProposedBlocksToArchiver === false) {
503
+ await this.blockSource.addBlock(reexecutionResult.block);
504
+ }
505
+ this.log.info(`Successfully re-executed block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, {
506
+ ...proposalInfo,
507
+ ...pick(reexecutionResult, 'reexecutionTimeMs', 'totalManaUsed')
508
+ });
509
+ return {
510
+ isValid: true,
511
+ blockNumber,
512
+ reexecutionResult
513
+ };
514
+ }
515
+ async validateNewBlockInSlot(blockProposal) {
516
+ if (!this.p2pClient) {
517
+ return {
518
+ isValid: true
519
+ };
520
+ }
521
+ const { blockProposals, checkpointProposals } = await this.p2pClient.getProposalsForSlot(blockProposal.slotNumber);
522
+ if (checkpointProposals.length === 0) {
523
+ return {
524
+ isValid: true
525
+ };
526
+ } else if (checkpointProposals.length > 1) {
527
+ return {
528
+ isValid: false,
529
+ reason: 'checkpoint_proposal_equivocation'
530
+ };
531
+ } else {
532
+ const checkpointProposal = checkpointProposals[0];
533
+ const terminalBlock = blockProposals.find((block)=>block.archive.equals(checkpointProposal.archive));
534
+ return terminalBlock !== undefined && blockProposal.indexWithinCheckpoint > terminalBlock.indexWithinCheckpoint ? {
535
+ isValid: false,
536
+ reason: 'block_proposal_beyond_checkpoint'
537
+ } : {
538
+ isValid: true
539
+ };
540
+ }
541
+ }
542
+ async getParentBlock(proposal) {
543
+ const parentArchive = proposal.blockHeader.lastArchive.root;
544
+ const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
545
+ if (parentArchive.equals(genesisArchiveRoot)) {
546
+ return 'genesis';
547
+ }
548
+ const deadline = this.getReexecutionDeadline(proposal.slotNumber);
549
+ const timeoutDurationMs = deadline.getTime() - this.dateProvider.now();
550
+ try {
551
+ return await this.blockSource.getBlockData({
552
+ archive: parentArchive
553
+ }) ?? (timeoutDurationMs <= 0 ? undefined : await retryUntil(()=>this.blockSource.syncImmediate().then(()=>this.blockSource.getBlockData({
554
+ archive: parentArchive
555
+ })), 'force archiver sync', {
556
+ deadline,
557
+ dateProvider: this.dateProvider
558
+ }, 0.5));
559
+ } catch (err) {
560
+ if (err instanceof TimeoutError) {
561
+ this.log.debug(`Timed out getting parent block by archive root`, {
562
+ parentArchive
563
+ });
564
+ } else {
565
+ this.log.error('Error getting parent block by archive root', err, {
566
+ parentArchive
567
+ });
568
+ }
569
+ return undefined;
570
+ }
571
+ }
572
+ /**
573
+ * Resolves whether a block genuinely already exists at `blockNumber`. Returns the existing block only if
574
+ * it is a true duplicate of the proposal (matching archive). During a reorg the archiver can still hold a
575
+ * stale fork at this number (different archive) that is about to be pruned; in that case this forces L1
576
+ * sync and waits, bounded by the re-execution deadline, for the prune to land, then returns `undefined` so
577
+ * the rebuilt block proposal can be processed in time to attest. If the prune does not complete before the
578
+ * deadline it returns the stale block, so the caller falls back to the safe `block_number_already_exists`
579
+ * rejection.
580
+ */ async resolveExistingBlockAtNumber(blockNumber, proposalArchive, slotNumber) {
581
+ const existingBlock = await this.blockSource.getBlockData({
582
+ number: blockNumber
583
+ });
584
+ if (!existingBlock || existingBlock.archive.root.equals(proposalArchive)) {
585
+ return existingBlock;
586
+ }
587
+ // A different block already occupies this number: it may be a stale fork being pruned during a reorg, not a
588
+ // genuine duplicate. Wait for the local prune rather than permanently rejecting the proposal.
589
+ const deadline = this.getReexecutionDeadline(slotNumber);
590
+ if (deadline.getTime() - this.dateProvider.now() <= 0) {
591
+ return existingBlock;
592
+ }
593
+ this.log.warn(`Block number ${blockNumber} already exists, awaiting potential prune`, {
594
+ blockNumber,
595
+ existingArchive: existingBlock.archive.root.toString(),
596
+ proposalArchive: proposalArchive.toString()
597
+ });
598
+ try {
599
+ const { block } = await retryUntil(async ()=>{
600
+ await this.blockSource.syncImmediate();
601
+ const block = await this.blockSource.getBlockData({
602
+ number: blockNumber
603
+ });
604
+ // Resolve once the existing block is gone (pruned) or has been replaced by one matching the
605
+ // proposal — the same condition as the early return above. A matching block is returned so the
606
+ // caller still treats it as a genuine duplicate; an `undefined` (pruned) block lets the proposal
607
+ // be processed. Wrap in an object so the `undefined` case is still a truthy retry result.
608
+ return block === undefined || block.archive.root.equals(proposalArchive) ? {
609
+ block
610
+ } : undefined;
611
+ }, `prune of stale block ${blockNumber}`, {
612
+ deadline,
613
+ dateProvider: this.dateProvider
614
+ }, 0.5);
615
+ return block;
616
+ } catch (err) {
617
+ if (err instanceof TimeoutError) {
618
+ this.log.warn(`Timed out waiting for stale block ${blockNumber} to be pruned`, {
619
+ blockNumber
620
+ });
621
+ return existingBlock;
622
+ }
623
+ throw err;
624
+ }
625
+ }
626
+ computeCheckpointNumber(proposal, parentBlock, proposalInfo) {
627
+ if (parentBlock === 'genesis') {
628
+ // First block is in checkpoint 1
629
+ if (proposal.indexWithinCheckpoint !== 0) {
630
+ this.log.warn(`First block proposal has non-zero indexWithinCheckpoint`, proposalInfo);
631
+ return {
632
+ reason: 'invalid_proposal'
633
+ };
634
+ }
635
+ return {
636
+ checkpointNumber: CheckpointNumber.INITIAL
637
+ };
638
+ }
639
+ if (proposal.indexWithinCheckpoint === 0) {
640
+ // If this is the first block in a new checkpoint, increment the checkpoint number
641
+ if (!(proposal.blockHeader.getSlot() > parentBlock.header.getSlot())) {
642
+ this.log.warn(`Slot should be greater than parent block slot for first block in checkpoint`, proposalInfo);
643
+ return {
644
+ reason: 'invalid_proposal'
645
+ };
646
+ }
647
+ return {
648
+ checkpointNumber: CheckpointNumber(parentBlock.checkpointNumber + 1)
649
+ };
650
+ }
651
+ // Otherwise it should follow the previous block in the same checkpoint
652
+ if (proposal.indexWithinCheckpoint !== parentBlock.indexWithinCheckpoint + 1) {
653
+ this.log.warn(`Non-sequential indexWithinCheckpoint`, proposalInfo);
654
+ return {
655
+ reason: 'invalid_proposal'
656
+ };
657
+ }
658
+ if (proposal.blockHeader.getSlot() !== parentBlock.header.getSlot()) {
659
+ this.log.warn(`Slot should be equal to parent block slot for non-first block in checkpoint`, proposalInfo);
660
+ return {
661
+ reason: 'invalid_proposal'
662
+ };
663
+ }
664
+ // For non-first blocks in a checkpoint, validate global variables match parent (except blockNumber)
665
+ const validationResult = this.validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo);
666
+ if (validationResult) {
667
+ return validationResult;
668
+ }
669
+ return {
670
+ checkpointNumber: parentBlock.checkpointNumber
671
+ };
672
+ }
673
+ /**
674
+ * Validates that a non-first block in a checkpoint has consistent global variables with its parent.
675
+ * For blocks with indexWithinCheckpoint > 0, all global variables except blockNumber must match the parent.
676
+ * @returns A failure result if validation fails, undefined if validation passes
677
+ */ validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo) {
678
+ const proposalGlobals = proposal.blockHeader.globalVariables;
679
+ const parentGlobals = parentBlock.header.globalVariables;
680
+ // All global variables except blockNumber should match the parent
681
+ // blockNumber naturally increments between blocks
682
+ if (!proposalGlobals.chainId.equals(parentGlobals.chainId)) {
683
+ this.log.warn(`Non-first block in checkpoint has mismatched chainId`, {
684
+ ...proposalInfo,
685
+ proposalChainId: proposalGlobals.chainId.toString(),
686
+ parentChainId: parentGlobals.chainId.toString()
687
+ });
688
+ return {
689
+ reason: 'global_variables_mismatch'
690
+ };
691
+ }
692
+ if (!proposalGlobals.version.equals(parentGlobals.version)) {
693
+ this.log.warn(`Non-first block in checkpoint has mismatched version`, {
694
+ ...proposalInfo,
695
+ proposalVersion: proposalGlobals.version.toString(),
696
+ parentVersion: parentGlobals.version.toString()
697
+ });
698
+ return {
699
+ reason: 'global_variables_mismatch'
700
+ };
701
+ }
702
+ if (proposalGlobals.slotNumber !== parentGlobals.slotNumber) {
703
+ this.log.warn(`Non-first block in checkpoint has mismatched slotNumber`, {
704
+ ...proposalInfo,
705
+ proposalSlotNumber: proposalGlobals.slotNumber,
706
+ parentSlotNumber: parentGlobals.slotNumber
707
+ });
708
+ return {
709
+ reason: 'global_variables_mismatch'
710
+ };
711
+ }
712
+ if (proposalGlobals.timestamp !== parentGlobals.timestamp) {
713
+ this.log.warn(`Non-first block in checkpoint has mismatched timestamp`, {
714
+ ...proposalInfo,
715
+ proposalTimestamp: proposalGlobals.timestamp.toString(),
716
+ parentTimestamp: parentGlobals.timestamp.toString()
717
+ });
718
+ return {
719
+ reason: 'global_variables_mismatch'
720
+ };
721
+ }
722
+ if (!proposalGlobals.coinbase.equals(parentGlobals.coinbase)) {
723
+ this.log.warn(`Non-first block in checkpoint has mismatched coinbase`, {
724
+ ...proposalInfo,
725
+ proposalCoinbase: proposalGlobals.coinbase.toString(),
726
+ parentCoinbase: parentGlobals.coinbase.toString()
727
+ });
728
+ return {
729
+ reason: 'global_variables_mismatch'
730
+ };
731
+ }
732
+ if (!proposalGlobals.feeRecipient.equals(parentGlobals.feeRecipient)) {
733
+ this.log.warn(`Non-first block in checkpoint has mismatched feeRecipient`, {
734
+ ...proposalInfo,
735
+ proposalFeeRecipient: proposalGlobals.feeRecipient.toString(),
736
+ parentFeeRecipient: parentGlobals.feeRecipient.toString()
737
+ });
738
+ return {
739
+ reason: 'global_variables_mismatch'
740
+ };
741
+ }
742
+ if (!proposalGlobals.gasFees.equals(parentGlobals.gasFees)) {
743
+ this.log.warn(`Non-first block in checkpoint has mismatched gasFees`, {
744
+ ...proposalInfo,
745
+ proposalGasFees: proposalGlobals.gasFees.toInspect(),
746
+ parentGasFees: parentGlobals.gasFees.toInspect()
747
+ });
748
+ return {
749
+ reason: 'global_variables_mismatch'
750
+ };
751
+ }
752
+ return undefined;
753
+ }
754
+ /**
755
+ * Hard re-execution/validation deadline for any block or checkpoint proposal targeting `slotNumber`:
756
+ * the single consensus `attestation_deadline` (`target_slot_start + S - 2E`). This is the latest the
757
+ * checkpoint can land on L1 in the target slot; all nodes agree on it. Loosened from the previous
758
+ * next-wall-clock-slot-boundary bound (see the timetable spec / refactor notes).
759
+ */ getReexecutionDeadline(slotNumber) {
760
+ return new Date(this.timetable.getAttestationDeadline(slotNumber) * 1000);
761
+ }
762
+ getReexecuteFailureReason(err) {
763
+ if (err instanceof TransactionsNotAvailableError) {
764
+ return 'txs_not_available';
765
+ } else if (err instanceof ReExInitialStateMismatchError) {
766
+ return 'initial_state_mismatch';
767
+ } else if (err instanceof ReExStateMismatchError) {
768
+ return 'state_mismatch';
769
+ } else if (err instanceof ReExFailedTxsError) {
770
+ return 'failed_txs';
771
+ } else if (err instanceof ReExTimeoutError) {
772
+ return 'timeout';
773
+ } else {
774
+ return 'unknown_error';
775
+ }
776
+ }
777
+ async reexecuteTransactions(proposal, blockNumber, checkpointNumber, txs, l1ToL2Messages, previousCheckpointOutHashes) {
778
+ const env = {
779
+ stack: [],
780
+ error: void 0,
781
+ hasError: false
782
+ };
783
+ try {
784
+ const { blockHeader, txHashes } = proposal;
785
+ // If we do not have all of the transactions, then we should fail
786
+ if (txs.length !== txHashes.length) {
787
+ const foundTxHashes = txs.map((tx)=>tx.getTxHash());
788
+ const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.some((h)=>h.equals(txHash)));
789
+ throw new TransactionsNotAvailableError(missingTxHashes);
790
+ }
791
+ const timer = new Timer();
792
+ const slot = proposal.slotNumber;
793
+ const config = this.checkpointsBuilder.getConfig();
794
+ // Get prior blocks in this checkpoint (same slot before current block)
795
+ const allBlocksInSlot = await this.blockSource.getBlocksForSlot(slot);
796
+ const priorBlocks = allBlocksInSlot.filter((b)=>b.number < blockNumber && b.header.getSlot() === slot);
797
+ // Fork before the block to be built
798
+ const parentBlockNumber = BlockNumber(blockNumber - 1);
799
+ await this.worldState.syncImmediate(parentBlockNumber);
800
+ const fork = _ts_add_disposable_resource(env, await this.worldState.fork(parentBlockNumber), true);
801
+ // Verify the fork's archive root matches the proposal's expected last archive.
802
+ // If they don't match, our world state synced to a different chain and reexecution would fail.
803
+ const forkArchiveRoot = new Fr((await fork.getTreeInfo(MerkleTreeId.ARCHIVE)).root);
804
+ if (!forkArchiveRoot.equals(proposal.blockHeader.lastArchive.root)) {
805
+ throw new ReExInitialStateMismatchError(proposal.blockHeader.lastArchive.root, forkArchiveRoot);
806
+ }
807
+ // Build checkpoint constants from proposal (excludes blockNumber which is per-block)
808
+ const constants = {
809
+ chainId: new Fr(config.l1ChainId),
810
+ version: new Fr(config.rollupVersion),
811
+ slotNumber: slot,
812
+ timestamp: blockHeader.globalVariables.timestamp,
813
+ coinbase: blockHeader.globalVariables.coinbase,
814
+ feeRecipient: blockHeader.globalVariables.feeRecipient,
815
+ gasFees: blockHeader.globalVariables.gasFees
816
+ };
817
+ // Create checkpoint builder with prior blocks
818
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, 0n, l1ToL2Messages, previousCheckpointOutHashes, fork, priorBlocks, this.log.getBindings());
819
+ // Build the new block
820
+ const deadline = this.getReexecutionDeadline(slot);
821
+ const maxBlockGas = this.config.validateMaxL2BlockGas !== undefined || this.config.validateMaxDABlockGas !== undefined ? new Gas(this.config.validateMaxDABlockGas ?? Infinity, this.config.validateMaxL2BlockGas ?? Infinity) : undefined;
822
+ const result = await checkpointBuilder.buildBlock(txs, blockNumber, blockHeader.globalVariables.timestamp, {
823
+ isBuildingProposal: false,
824
+ minValidTxs: 0,
825
+ deadline,
826
+ expectedEndState: blockHeader.state,
827
+ maxTransactions: this.config.validateMaxTxsPerBlock,
828
+ maxBlockGas
829
+ });
830
+ const { block, failedTxs } = result;
831
+ const numFailedTxs = failedTxs.length;
832
+ this.log.verbose(`Block proposal ${blockNumber} at slot ${slot} transaction re-execution complete`, {
833
+ numFailedTxs,
834
+ numProposalTxs: txHashes.length,
835
+ numProcessedTxs: block.body.txEffects.length,
836
+ blockNumber,
837
+ slot
838
+ });
839
+ if (numFailedTxs > 0) {
840
+ this.metrics?.recordFailedReexecution(proposal);
841
+ throw new ReExFailedTxsError(numFailedTxs);
842
+ }
843
+ if (block.body.txEffects.length !== txHashes.length) {
844
+ this.metrics?.recordFailedReexecution(proposal);
845
+ throw new ReExTimeoutError();
846
+ }
847
+ // Throw a ReExStateMismatchError error if state updates do not match
848
+ // Compare the full block structure (archive and header) from the built block with the proposal
849
+ const archiveMatches = proposal.archive.equals(block.archive.root);
850
+ const headerMatches = proposal.blockHeader.equals(block.header);
851
+ if (!archiveMatches || !headerMatches) {
852
+ this.log.warn(`Re-execution state mismatch for slot ${slot}`, {
853
+ expectedArchive: block.archive.root.toString(),
854
+ actualArchive: proposal.archive.toString(),
855
+ expectedHeader: block.header.toInspect(),
856
+ actualHeader: proposal.blockHeader.toInspect()
857
+ });
858
+ this.metrics?.recordFailedReexecution(proposal);
859
+ throw new ReExStateMismatchError(proposal.archive, block.archive.root);
860
+ }
861
+ const reexecutionTimeMs = timer.ms();
862
+ const totalManaUsed = block.header.totalManaUsed.toNumber() / 1e6;
863
+ this.metrics?.recordReex(reexecutionTimeMs, txs.length, totalManaUsed);
864
+ return {
865
+ block,
866
+ failedTxs,
867
+ reexecutionTimeMs,
868
+ totalManaUsed
869
+ };
870
+ } catch (e) {
871
+ env.error = e;
872
+ env.hasError = true;
873
+ } finally{
874
+ const result = _ts_dispose_resources(env);
875
+ if (result) await result;
876
+ }
877
+ }
878
+ /**
879
+ * Validates a checkpoint proposal, caches the result, and uploads blobs if configured.
880
+ * Returns a cached result if the same proposal (archive + slot) was already validated.
881
+ * Used by both the all-nodes callback (via register) and the validator client (via delegation).
882
+ */ async handleCheckpointProposal(proposal, proposalInfo) {
883
+ const slot = proposal.slotNumber;
884
+ const payloadHash = proposal.getPayloadHash();
885
+ // Check cache: same signed-payload hash means we already validated this exact proposal.
886
+ if (this.lastCheckpointValidationResult && this.lastCheckpointValidationResult.payloadHash === payloadHash) {
887
+ this.log.debug(`Returning cached validation result for checkpoint proposal at slot ${slot}`, proposalInfo);
888
+ return this.lastCheckpointValidationResult.result;
889
+ }
890
+ const proposer = proposal.getSender();
891
+ let result;
892
+ if (!proposer) {
893
+ this.log.warn(`Received checkpoint proposal with invalid signature for slot ${proposal.slotNumber}`);
894
+ result = {
895
+ isValid: false,
896
+ reason: 'invalid_signature'
897
+ };
898
+ } else if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
899
+ this.log.warn(`Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${proposal.slotNumber}`);
900
+ result = {
901
+ isValid: false,
902
+ reason: 'invalid_fee_asset_price_modifier'
903
+ };
904
+ } else {
905
+ result = await this.validateCheckpointProposal(proposal, proposalInfo);
906
+ }
907
+ this.lastCheckpointValidationResult = {
908
+ payloadHash,
909
+ result
910
+ };
911
+ // Record the outcome on the re-execution tracker.
912
+ const outcome = result.isValid ? 'valid' : CHECKPOINT_VALIDATION_REASON_TO_OUTCOME[result.reason];
913
+ if (outcome !== undefined) {
914
+ this.reexecutionTracker.recordOutcome(slot, proposal.archive, outcome, result.checkpointNumber);
915
+ }
916
+ // Drop tracker entries for checkpoints that have reached L1 finality.
917
+ try {
918
+ const tips = await this.blockSource.getL2Tips();
919
+ const finalizedCheckpointNumber = tips.finalized.checkpoint.number;
920
+ if (finalizedCheckpointNumber > 0) {
921
+ this.reexecutionTracker.removeBefore(CheckpointNumber(finalizedCheckpointNumber + 1));
922
+ }
923
+ } catch (err) {
924
+ this.log.error(`Error pruning reexecution tracker`, err, proposalInfo);
925
+ }
926
+ // Upload blobs to filestore if validation passed (fire and forget)
927
+ if (result.isValid) {
928
+ this.tryUploadBlobsForCheckpoint(proposal, proposalInfo);
929
+ }
930
+ return result;
931
+ }
932
+ /**
933
+ * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
934
+ * @returns Validation result with isValid flag and reason if invalid.
935
+ */ async validateCheckpointProposal(proposal, proposalInfo) {
936
+ const env = {
937
+ stack: [],
938
+ error: void 0,
939
+ hasError: false
940
+ };
941
+ try {
942
+ const slot = proposal.slotNumber;
943
+ // Block-sync/validation deadline = the single consensus attestation_deadline (target_slot_start + S
944
+ // - 2E): the latest moment the proposer can submit this checkpoint and still have it land on L1 in
945
+ // the target slot. Keeping validation/attestation alive until then lets validators keep attesting
946
+ // right up to the proposer's real publish cutoff.
947
+ const deadline = this.getReexecutionDeadline(slot);
948
+ // Wait for last block to sync by archive. The deadline is passed to retryUntil as an absolute date so
949
+ // the remaining budget is derived from the date provider; a deadline already in the past times out
950
+ // after a single attempt instead of looping (the immediate-timeout semantics of the deadline overload).
951
+ let lastBlockData;
952
+ try {
953
+ lastBlockData = await retryUntil(async ()=>{
954
+ await this.blockSource.syncImmediate();
955
+ return await this.blockSource.getBlockData({
956
+ archive: proposal.archive
957
+ });
958
+ }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, {
959
+ deadline,
960
+ dateProvider: this.dateProvider
961
+ }, 0.5);
962
+ } catch (err) {
963
+ if (err instanceof TimeoutError) {
964
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
965
+ return {
966
+ isValid: false,
967
+ reason: 'last_block_not_found'
968
+ };
969
+ }
970
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
971
+ return {
972
+ isValid: false,
973
+ reason: 'block_fetch_error'
974
+ };
975
+ }
976
+ if (!lastBlockData) {
977
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
978
+ return {
979
+ isValid: false,
980
+ reason: 'last_block_not_found'
981
+ };
982
+ }
983
+ // Refuse to attest if the block's enclosing checkpoint has already been published to L1.
984
+ const existingCheckpoint = await this.blockSource.getCheckpointData({
985
+ number: lastBlockData.checkpointNumber
986
+ });
987
+ if (existingCheckpoint) {
988
+ this.log.warn(`Refusing to attest to checkpoint proposal whose checkpoint is already on L1`, {
989
+ ...proposalInfo,
990
+ checkpointNumber: lastBlockData.checkpointNumber
991
+ });
992
+ return {
993
+ isValid: false,
994
+ reason: 'checkpoint_already_published',
995
+ checkpointNumber: lastBlockData.checkpointNumber
996
+ };
997
+ }
998
+ // Get all full blocks for the slot and checkpoint
999
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
1000
+ if (blocks.length === 0) {
1001
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
1002
+ return {
1003
+ isValid: false,
1004
+ reason: 'no_blocks_for_slot',
1005
+ checkpointNumber: lastBlockData.checkpointNumber
1006
+ };
1007
+ }
1008
+ // Ensure the last block for this slot matches the archive in the checkpoint proposal
1009
+ if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
1010
+ this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
1011
+ return {
1012
+ isValid: false,
1013
+ reason: 'last_block_archive_mismatch',
1014
+ checkpointNumber: lastBlockData.checkpointNumber
1015
+ };
1016
+ }
1017
+ // Note this condition should never trigger, since we dont process block proposals that exceed indexWithinCheckpoint
1018
+ const maxBlocksPerCheckpoint = this.config.maxBlocksPerCheckpoint;
1019
+ if (maxBlocksPerCheckpoint !== undefined && blocks.length > maxBlocksPerCheckpoint) {
1020
+ this.log.warn(`Checkpoint proposal exceeds maxBlocksPerCheckpoint`, {
1021
+ ...proposalInfo,
1022
+ blocksInProposal: blocks.length,
1023
+ maxBlocksPerCheckpoint
1024
+ });
1025
+ return {
1026
+ isValid: false,
1027
+ reason: 'too_many_blocks_in_checkpoint',
1028
+ checkpointNumber: lastBlockData.checkpointNumber
1029
+ };
1030
+ }
1031
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
1032
+ ...proposalInfo,
1033
+ blockNumbers: blocks.map((b)=>b.number)
1034
+ });
1035
+ // Get checkpoint constants from first block
1036
+ const firstBlock = blocks[0];
1037
+ const constants = this.extractCheckpointConstants(firstBlock);
1038
+ const checkpointNumber = firstBlock.checkpointNumber;
1039
+ // Get L1-to-L2 messages for this checkpoint
1040
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
1041
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
1042
+ // See note on the analogous block-proposal site: the helper handles pipelining lag.
1043
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
1044
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
1045
+ blockSource: this.blockSource,
1046
+ epoch,
1047
+ checkpointNumber,
1048
+ l1Constants: this.epochCache.getL1Constants(),
1049
+ pipeliningEnabled: true,
1050
+ log: this.log
1051
+ });
1052
+ // Fork world state at the block before the first block
1053
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
1054
+ const fork = _ts_add_disposable_resource(env, await this.checkpointsBuilder.getFork(parentBlockNumber), true);
1055
+ // Create checkpoint builder with all existing blocks
1056
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, proposal.feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks, this.log.getBindings());
1057
+ // Complete the checkpoint to get computed values
1058
+ const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
1059
+ // Compare checkpoint header with proposal
1060
+ if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
1061
+ this.log.warn(`Checkpoint header mismatch`, {
1062
+ ...proposalInfo,
1063
+ computed: computedCheckpoint.header.toInspect(),
1064
+ proposal: proposal.checkpointHeader.toInspect()
1065
+ });
1066
+ return {
1067
+ isValid: false,
1068
+ reason: 'checkpoint_header_mismatch',
1069
+ checkpointNumber
1070
+ };
1071
+ }
1072
+ // Compare archive root with proposal
1073
+ if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
1074
+ this.log.warn(`Archive root mismatch`, {
1075
+ ...proposalInfo,
1076
+ computed: computedCheckpoint.archive.root.toString(),
1077
+ proposal: proposal.archive.toString()
1078
+ });
1079
+ return {
1080
+ isValid: false,
1081
+ reason: 'archive_mismatch',
1082
+ checkpointNumber
1083
+ };
1084
+ }
1085
+ // Check that the accumulated epoch out hash matches the value in the proposal.
1086
+ // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
1087
+ const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
1088
+ const computedEpochOutHash = accumulateCheckpointOutHashes([
1089
+ ...previousCheckpointOutHashes,
1090
+ checkpointOutHash
1091
+ ]);
1092
+ const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
1093
+ if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
1094
+ this.log.warn(`Epoch out hash mismatch`, {
1095
+ proposalEpochOutHash: proposalEpochOutHash.toString(),
1096
+ computedEpochOutHash: computedEpochOutHash.toString(),
1097
+ checkpointOutHash: checkpointOutHash.toString(),
1098
+ previousCheckpointOutHashes: previousCheckpointOutHashes.map((h)=>h.toString()),
1099
+ ...proposalInfo
1100
+ });
1101
+ return {
1102
+ isValid: false,
1103
+ reason: 'out_hash_mismatch',
1104
+ checkpointNumber
1105
+ };
1106
+ }
1107
+ // Final round of validations on the checkpoint, just in case.
1108
+ try {
1109
+ validateCheckpoint(computedCheckpoint, {
1110
+ rollupManaLimit: this.checkpointsBuilder.getConfig().rollupManaLimit,
1111
+ maxDABlockGas: this.config.validateMaxDABlockGas,
1112
+ maxL2BlockGas: this.config.validateMaxL2BlockGas,
1113
+ maxTxsPerBlock: this.config.validateMaxTxsPerBlock,
1114
+ maxTxsPerCheckpoint: this.config.validateMaxTxsPerCheckpoint
1115
+ });
1116
+ } catch (err) {
1117
+ this.log.warn(`Checkpoint validation failed: ${err}`, proposalInfo);
1118
+ return {
1119
+ isValid: false,
1120
+ reason: 'checkpoint_validation_failed',
1121
+ checkpointNumber
1122
+ };
1123
+ }
1124
+ this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
1125
+ return {
1126
+ isValid: true,
1127
+ checkpointNumber
1128
+ };
1129
+ } catch (e) {
1130
+ env.error = e;
1131
+ env.hasError = true;
1132
+ } finally{
1133
+ const result = _ts_dispose_resources(env);
1134
+ if (result) await result;
1135
+ }
1136
+ }
1137
+ /** Extracts checkpoint global variables from a block. */ extractCheckpointConstants(block) {
1138
+ const gv = block.header.globalVariables;
1139
+ return {
1140
+ chainId: gv.chainId,
1141
+ version: gv.version,
1142
+ slotNumber: gv.slotNumber,
1143
+ timestamp: gv.timestamp,
1144
+ coinbase: gv.coinbase,
1145
+ feeRecipient: gv.feeRecipient,
1146
+ gasFees: gv.gasFees
1147
+ };
1148
+ }
1149
+ /** Triggers blob upload for a checkpoint if the blob client can upload (fire and forget). */ tryUploadBlobsForCheckpoint(proposal, proposalInfo) {
1150
+ if (this.blobClient.canUpload()) {
1151
+ void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
1152
+ }
1153
+ }
1154
+ /** Uploads blobs for a checkpoint to the filestore. */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
1155
+ try {
1156
+ const lastBlockHeader = (await this.blockSource.getBlockData({
1157
+ archive: proposal.archive
1158
+ }))?.header;
1159
+ if (!lastBlockHeader) {
1160
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
1161
+ return;
1162
+ }
1163
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
1164
+ if (blocks.length === 0) {
1165
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
1166
+ return;
1167
+ }
1168
+ const blockBlobData = blocks.map((b)=>b.toBlockBlobData());
1169
+ const blobFields = encodeCheckpointBlobDataFromBlocks(blockBlobData);
1170
+ const blobs = await getBlobsPerL1Block(blobFields);
1171
+ await this.blobClient.sendBlobsToFilestore(blobs);
1172
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
1173
+ ...proposalInfo,
1174
+ numBlobs: blobs.length
1175
+ });
1176
+ } catch (err) {
1177
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
1178
+ }
1179
+ }
1180
+ /**
1181
+ * Derives proposed checkpoint data from validated blocks and sets it on the archiver, so this node can
1182
+ * pipeline building on top of the checkpoint. Does not retry, since validation already waited for the
1183
+ * last block to sync.
1184
+ */ async setProposedCheckpoint(proposal) {
1185
+ if (!this.archiver) {
1186
+ return false;
1187
+ }
1188
+ const blockData = await this.blockSource.getBlockData({
1189
+ archive: proposal.archive
1190
+ });
1191
+ if (!blockData) {
1192
+ this.log.debug(`Block data not found for checkpoint proposal archive, cannot set proposed checkpoint`, {
1193
+ archive: proposal.archive.toString()
1194
+ });
1195
+ return false;
1196
+ }
1197
+ await this.archiver.addProposedCheckpoint({
1198
+ header: proposal.checkpointHeader,
1199
+ checkpointNumber: blockData.checkpointNumber,
1200
+ startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
1201
+ blockCount: blockData.indexWithinCheckpoint + 1,
1202
+ totalManaUsed: proposal.checkpointHeader.totalManaUsed.toBigInt(),
1203
+ feeAssetPriceModifier: proposal.feeAssetPriceModifier
1204
+ });
1205
+ return true;
1206
+ }
1207
+ }