@aztec/validator-client 0.0.1-commit.b2a5d0dd1 → 0.0.1-commit.b3d3157a

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.
@@ -2,9 +2,14 @@ import type { Archiver } from '@aztec/archiver';
2
2
  import type { BlobClientInterface } from '@aztec/blob-client/client';
3
3
  import { type Blob, encodeCheckpointBlobDataFromBlocks, getBlobsPerL1Block } from '@aztec/blob-lib';
4
4
  import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
5
- import type { EpochCache } from '@aztec/epoch-cache';
5
+ import { type EpochCache, PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec/epoch-cache';
6
6
  import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
7
- import { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
7
+ import {
8
+ BlockNumber,
9
+ CheckpointNumber,
10
+ type CheckpointProposalHash,
11
+ SlotNumber,
12
+ } from '@aztec/foundation/branded-types';
8
13
  import { pick } from '@aztec/foundation/collection';
9
14
  import { Fr } from '@aztec/foundation/curves/bn254';
10
15
  import { TimeoutError } from '@aztec/foundation/error';
@@ -15,8 +20,9 @@ import { DateProvider, Timer } from '@aztec/foundation/timer';
15
20
  import type { P2P, PeerId } from '@aztec/p2p';
16
21
  import { BlockProposalValidator } from '@aztec/p2p/msg_validators';
17
22
  import type { BlockData, L2Block, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
18
- import { validateCheckpoint } from '@aztec/stdlib/checkpoint';
19
- import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
23
+ import type { CheckpointReexecutionTracker, ReexecutionOutcome } from '@aztec/stdlib/checkpoint';
24
+ import { getPreviousCheckpointOutHashes, validateCheckpoint } from '@aztec/stdlib/checkpoint';
25
+ import { getEpochAtSlot, getLastL1SlotTimestampForL2Slot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
20
26
  import { Gas } from '@aztec/stdlib/gas';
21
27
  import type { ITxProvider, ValidatorClientFullConfig, WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
22
28
  import {
@@ -40,9 +46,9 @@ import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
40
46
  import type { ValidatorMetrics } from './metrics.js';
41
47
 
42
48
  export type BlockProposalValidationFailureReason =
49
+ | 'invalid_signature'
43
50
  | 'invalid_proposal'
44
51
  | 'parent_block_not_found'
45
- | 'block_source_not_synced'
46
52
  | 'parent_block_wrong_slot'
47
53
  | 'in_hash_mismatch'
48
54
  | 'global_variables_mismatch'
@@ -52,6 +58,8 @@ export type BlockProposalValidationFailureReason =
52
58
  | 'failed_txs'
53
59
  | 'initial_state_mismatch'
54
60
  | 'timeout'
61
+ | 'block_proposal_beyond_checkpoint'
62
+ | 'checkpoint_proposal_equivocation'
55
63
  | 'unknown_error';
56
64
 
57
65
  type ReexecuteTransactionsResult = {
@@ -76,31 +84,96 @@ export type BlockProposalValidationFailureResult = {
76
84
 
77
85
  export type BlockProposalValidationResult = BlockProposalValidationSuccessResult | BlockProposalValidationFailureResult;
78
86
 
87
+ export type CheckpointProposalValidationFailureReason =
88
+ | 'invalid_signature'
89
+ | 'invalid_fee_asset_price_modifier'
90
+ | 'last_block_not_found'
91
+ | 'block_fetch_error'
92
+ | 'checkpoint_already_published'
93
+ | 'no_blocks_for_slot'
94
+ | 'last_block_archive_mismatch'
95
+ | 'too_many_blocks_in_checkpoint'
96
+ | 'checkpoint_header_mismatch'
97
+ | 'archive_mismatch'
98
+ | 'out_hash_mismatch'
99
+ | 'checkpoint_validation_failed';
100
+
101
+ /**
102
+ * Mapping from a checkpoint-proposal validation failure reason to the tracker outcome that
103
+ * `handleCheckpointProposal` should record. `undefined` means do not record (signature
104
+ * couldn't be verified, or the checkpoint is already on L1 so the question is moot).
105
+ */
106
+ /* eslint-disable camelcase */
107
+ const CHECKPOINT_VALIDATION_REASON_TO_OUTCOME: Record<
108
+ CheckpointProposalValidationFailureReason,
109
+ ReexecutionOutcome | undefined
110
+ > = {
111
+ invalid_signature: undefined,
112
+ invalid_fee_asset_price_modifier: 'invalid',
113
+ checkpoint_already_published: undefined,
114
+ last_block_not_found: 'unvalidated',
115
+ block_fetch_error: 'unvalidated',
116
+ no_blocks_for_slot: 'unvalidated',
117
+ last_block_archive_mismatch: 'invalid',
118
+ too_many_blocks_in_checkpoint: 'invalid',
119
+ checkpoint_header_mismatch: 'invalid',
120
+ archive_mismatch: 'invalid',
121
+ out_hash_mismatch: 'invalid',
122
+ checkpoint_validation_failed: 'invalid',
123
+ };
124
+
125
+ export type CheckpointProposalValidationSuccessResult = {
126
+ isValid: true;
127
+ checkpointNumber: CheckpointNumber;
128
+ };
129
+
130
+ export type CheckpointProposalValidationFailureResult = {
131
+ isValid: false;
132
+ reason: CheckpointProposalValidationFailureReason;
133
+ checkpointNumber?: CheckpointNumber;
134
+ };
135
+
79
136
  export type CheckpointProposalValidationResult =
80
- | { isValid: true; checkpointNumber: CheckpointNumber }
81
- | { isValid: false; reason: string };
137
+ | CheckpointProposalValidationSuccessResult
138
+ | CheckpointProposalValidationFailureResult;
139
+
140
+ export type CheckpointProposalValidationFailureCallback = (
141
+ proposal: CheckpointProposalCore,
142
+ result: CheckpointProposalValidationFailureResult,
143
+ proposalInfo: LogData,
144
+ ) => void | Promise<void>;
82
145
 
83
146
  type CheckpointComputationResult =
84
147
  | { checkpointNumber: CheckpointNumber; reason?: undefined }
85
148
  | { checkpointNumber?: undefined; reason: 'invalid_proposal' | 'global_variables_mismatch' };
86
149
 
150
+ type BlockProposalSlotValidationResult =
151
+ | { isValid: true }
152
+ | { isValid: false; reason: 'block_proposal_beyond_checkpoint' | 'checkpoint_proposal_equivocation' };
153
+
87
154
  /** Handles block and checkpoint proposals for both validator and non-validator nodes. */
88
155
  export class ProposalHandler {
89
156
  public readonly tracer: Tracer;
90
157
 
91
- /** Cached last checkpoint validation result to avoid double-validation on validator nodes. */
158
+ /** Cached last checkpoint validation result to avoid double-validation on validator nodes.
159
+ * Keyed by signed-payload hash so two proposals at the same (slot, archive) but with a
160
+ * different `feeAssetPriceModifier` (or any other signed field) are validated independently. */
92
161
  private lastCheckpointValidationResult?: {
93
- archive: Fr;
94
- slotNumber: SlotNumber;
162
+ payloadHash: CheckpointProposalHash;
95
163
  result: CheckpointProposalValidationResult;
96
164
  };
97
165
 
98
166
  /** Archiver reference for setting proposed checkpoints (pipelining). Set via register(). */
99
- private archiver?: Pick<Archiver, 'setProposedCheckpoint' | 'getL1Constants'>;
167
+ private archiver?: Pick<Archiver, 'addProposedCheckpoint'>;
100
168
 
101
169
  /** Returns current validator addresses for own-proposal detection. Set via register(). */
102
170
  private getOwnValidatorAddresses?: () => string[];
103
171
 
172
+ /** P2P proposal pool access for deciding when retained proposals should block archiver processing. */
173
+ private p2pClient?: Pick<P2P, 'getProposalsForSlot'>;
174
+
175
+ private checkpointProposalValidationFailureCallback?: CheckpointProposalValidationFailureCallback;
176
+
104
177
  constructor(
105
178
  private checkpointsBuilder: FullNodeCheckpointsBuilder,
106
179
  private worldState: WorldStateSynchronizer,
@@ -111,6 +184,7 @@ export class ProposalHandler {
111
184
  private epochCache: EpochCache,
112
185
  private config: ValidatorClientFullConfig,
113
186
  private blobClient: BlobClientInterface,
187
+ private reexecutionTracker: CheckpointReexecutionTracker,
114
188
  private metrics?: ValidatorMetrics,
115
189
  private dateProvider: DateProvider = new DateProvider(),
116
190
  telemetry: TelemetryClient = getTelemetryClient(),
@@ -122,8 +196,32 @@ export class ProposalHandler {
122
196
  this.tracer = telemetry.getTracer('ProposalHandler');
123
197
  }
124
198
 
199
+ public updateConfig(config: Partial<ValidatorClientFullConfig>): void {
200
+ this.config = { ...this.config, ...config };
201
+ }
202
+
203
+ public setCheckpointProposalValidationFailureCallback(callback?: CheckpointProposalValidationFailureCallback): void {
204
+ this.checkpointProposalValidationFailureCallback = callback;
205
+ }
206
+
207
+ /**
208
+ * Records the proposer's own checkpoint proposal as a `valid` outcome in the re-execution
209
+ * tracker. Without this, the node's own checkpoint proposals never flow through
210
+ * `handleCheckpointProposal` (proposers don't validate their own proposals), so its sentinel
211
+ * sees no outcome for slots where it was the proposer and reports itself as inactive.
212
+ *
213
+ * `archive` should be the locally-computed archive (NOT the broadcast archive, which may have
214
+ * been deliberately corrupted in tests via `broadcastInvalidBlockProposal` /
215
+ * `broadcastInvalidCheckpointProposalOnly`). Recording the local archive correctly models the
216
+ * proposer's own view of its own work.
217
+ */
218
+ public recordOwnCheckpointProposalAsValid(slot: SlotNumber, archive: Fr, checkpointNumber: CheckpointNumber): void {
219
+ this.reexecutionTracker.recordOutcome(slot, archive, 'valid', checkpointNumber);
220
+ }
221
+
125
222
  /**
126
223
  * Registers handlers for block and checkpoint proposals on the p2p client.
224
+ * Records the p2p client so validation can inspect retained proposals.
127
225
  * Block proposals are registered for non-validator nodes (validators register their own enhanced handler).
128
226
  * The all-nodes checkpoint proposal handler is always registered for validation, caching, and pipelining.
129
227
  * @param archiver - Archiver reference for setting proposed checkpoints (pipelining)
@@ -132,9 +230,10 @@ export class ProposalHandler {
132
230
  register(
133
231
  p2pClient: P2P,
134
232
  shouldReexecute: boolean,
135
- archiver?: Pick<Archiver, 'setProposedCheckpoint' | 'getL1Constants'>,
233
+ archiver?: Pick<Archiver, 'addProposedCheckpoint'>,
136
234
  getOwnValidatorAddresses?: () => string[],
137
235
  ): ProposalHandler {
236
+ this.p2pClient = p2pClient;
138
237
  this.archiver = archiver;
139
238
  this.getOwnValidatorAddresses = getOwnValidatorAddresses;
140
239
 
@@ -184,21 +283,37 @@ export class ProposalHandler {
184
283
  proposer: proposal.getSender()?.toString(),
185
284
  };
186
285
 
187
- // For own proposals, skip validation — the proposer already built and validated the checkpoint
286
+ if (this.config.skipCheckpointProposalValidation) {
287
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposal.slotNumber}`, proposalInfo);
288
+ return undefined;
289
+ }
290
+
291
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposal.slotNumber)) {
292
+ this.log.warn(
293
+ `Escape hatch open for slot ${proposal.slotNumber}, skipping checkpoint proposal validation`,
294
+ proposalInfo,
295
+ );
296
+ return undefined;
297
+ }
298
+
299
+ // For own proposals, skip validation and return: the proposer already built and validated the
300
+ // checkpoint, and the sequencer's checkpoint proposal job pushed the proposed checkpoint to the
301
+ // archiver from local data before broadcasting. Gossipsub doesn't echo our own messages back, so
302
+ // this branch is normally unreachable — it remains as defense if an own proposal arrives by some
303
+ // other path.
188
304
  const proposer = proposal.getSender();
189
305
  const ownAddresses = this.getOwnValidatorAddresses?.();
190
306
  const isOwnProposal = proposer && ownAddresses?.some(addr => addr === proposer.toString());
191
307
 
192
308
  if (isOwnProposal) {
193
309
  this.log.debug(`Skipping validation for own checkpoint proposal at slot ${proposal.slotNumber}`);
194
- if (this.archiver && this.epochCache.isProposerPipeliningEnabled()) {
195
- await this.setProposedCheckpointFromBlocks(proposal);
196
- }
197
310
  return undefined;
198
311
  }
199
312
 
200
313
  const result = await this.handleCheckpointProposal(proposal, proposalInfo);
201
- if (result.isValid && this.archiver && this.epochCache.isProposerPipeliningEnabled()) {
314
+ if (!result.isValid) {
315
+ await this.checkpointProposalValidationFailureCallback?.(proposal, result, proposalInfo);
316
+ } else if (this.archiver) {
202
317
  const set = await this.setProposedCheckpointFromValidation(proposal);
203
318
  if (set) {
204
319
  this.metrics?.recordCheckpointProposalToPipelinedStateDuration(pipeliningTimer.ms());
@@ -227,7 +342,7 @@ export class ProposalHandler {
227
342
  // Reject proposals with invalid signatures
228
343
  if (!proposer) {
229
344
  this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
230
- return { isValid: false, reason: 'invalid_proposal' };
345
+ return { isValid: false, reason: 'invalid_signature' };
231
346
  }
232
347
 
233
348
  const proposalInfo = {
@@ -250,21 +365,20 @@ export class ProposalHandler {
250
365
  return { isValid: false, reason: 'invalid_proposal' };
251
366
  }
252
367
 
253
- // Ensure the block source is synced before checking for existing blocks,
254
- // since a proposed checkpoint prune may remove blocks we'd otherwise find.
255
- // This affects mostly the block_number_already_exists check, since a pending
256
- // checkpoint prune could remove a block that would conflict with this proposal.
257
- // When pipelining is enabled, the proposer builds ahead of L1 submission, so the
258
- // block source won't have synced to the proposed slot yet. Skip the sync wait to
259
- // avoid eating into the attestation window.
260
- if (!this.epochCache.isProposerPipeliningEnabled()) {
261
- const blockSourceSync = await this.waitForBlockSourceSync(slotNumber);
262
- if (!blockSourceSync) {
263
- this.log.warn(`Block source is not synced, skipping processing`, proposalInfo);
264
- return { isValid: false, reason: 'block_source_not_synced' };
265
- }
368
+ const retainedSlotValidation = await this.validateNewBlockInSlot(proposal);
369
+ if (!retainedSlotValidation.isValid) {
370
+ this.log.info(`Block proposal conflicts with retained proposals, skipping archiver processing`, {
371
+ ...proposalInfo,
372
+ indexWithinCheckpoint: proposal.indexWithinCheckpoint,
373
+ reason: retainedSlotValidation.reason,
374
+ });
375
+ return { isValid: false, blockNumber: proposal.blockNumber, reason: retainedSlotValidation.reason };
266
376
  }
267
377
 
378
+ // The proposer builds ahead of L1 submission under pipelining, so the block source won't have
379
+ // synced to the proposed slot yet. We deliberately do not wait for it to sync here, to avoid
380
+ // eating into the attestation window.
381
+
268
382
  // Check that the parent proposal is a block we know, otherwise reexecution would fail.
269
383
  // If we don't find it immediately, we keep retrying for a while; it may be we still
270
384
  // need to process other block proposals to get to it.
@@ -292,7 +406,7 @@ export class ProposalHandler {
292
406
  proposalInfo.blockNumber = blockNumber;
293
407
 
294
408
  // Check that this block number does not exist already
295
- const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
409
+ const existingBlock = await this.blockSource.getBlockData({ number: blockNumber });
296
410
  if (existingBlock) {
297
411
  this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
298
412
  return { isValid: false, blockNumber, reason: 'block_number_already_exists' };
@@ -305,6 +419,9 @@ export class ProposalHandler {
305
419
  deadline: this.getReexecutionDeadline(slotNumber, config),
306
420
  });
307
421
 
422
+ // Record the tx-collection outcome on the re-execution tracker
423
+ this.reexecutionTracker.recordTxsCollected(slotNumber, proposal.indexWithinCheckpoint, missingTxs.length === 0);
424
+
308
425
  // If reexecution is disabled, bail. We were just interested in triggering tx collection.
309
426
  if (!shouldReexecute) {
310
427
  this.log.info(
@@ -341,11 +458,18 @@ export class ProposalHandler {
341
458
  return { isValid: false, blockNumber, reason: 'txs_not_available' };
342
459
  }
343
460
 
344
- // Collect the out hashes of all the checkpoints before this one in the same epoch
461
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
462
+ // Mirror the proposer-side fallback: under pipelining the immediately-preceding cp may not
463
+ // yet be on L1, in which case the helper grafts the locally-known proposed cp's outHash.
345
464
  const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
346
- const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch))
347
- .filter(c => c.checkpointNumber < checkpointNumber)
348
- .map(c => c.checkpointOutHash);
465
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
466
+ blockSource: this.blockSource,
467
+ epoch,
468
+ checkpointNumber,
469
+ l1Constants: this.epochCache.getL1Constants(),
470
+ pipeliningEnabled: true,
471
+ log: this.log,
472
+ });
349
473
 
350
474
  // Try re-executing the transactions in the proposal if needed
351
475
  let reexecutionResult;
@@ -378,6 +502,26 @@ export class ProposalHandler {
378
502
  return { isValid: true, blockNumber, reexecutionResult };
379
503
  }
380
504
 
505
+ private async validateNewBlockInSlot(blockProposal: BlockProposal): Promise<BlockProposalSlotValidationResult> {
506
+ if (!this.p2pClient) {
507
+ return { isValid: true };
508
+ }
509
+
510
+ const { blockProposals, checkpointProposals } = await this.p2pClient.getProposalsForSlot(blockProposal.slotNumber);
511
+
512
+ if (checkpointProposals.length === 0) {
513
+ return { isValid: true };
514
+ } else if (checkpointProposals.length > 1) {
515
+ return { isValid: false, reason: 'checkpoint_proposal_equivocation' };
516
+ } else {
517
+ const checkpointProposal = checkpointProposals[0];
518
+ const terminalBlock = blockProposals.find(block => block.archive.equals(checkpointProposal.archive));
519
+ return terminalBlock !== undefined && blockProposal.indexWithinCheckpoint > terminalBlock.indexWithinCheckpoint
520
+ ? { isValid: false, reason: 'block_proposal_beyond_checkpoint' }
521
+ : { isValid: true };
522
+ }
523
+ }
524
+
381
525
  private async getParentBlock(proposal: BlockProposal): Promise<'genesis' | BlockData | undefined> {
382
526
  const parentArchive = proposal.blockHeader.lastArchive.root;
383
527
  const config = this.checkpointsBuilder.getConfig();
@@ -393,11 +537,12 @@ export class ProposalHandler {
393
537
 
394
538
  try {
395
539
  return (
396
- (await this.blockSource.getBlockDataByArchive(parentArchive)) ??
540
+ (await this.blockSource.getBlockData({ archive: parentArchive })) ??
397
541
  (timeoutDurationMs <= 0
398
542
  ? undefined
399
543
  : await retryUntil(
400
- () => this.blockSource.syncImmediate().then(() => this.blockSource.getBlockDataByArchive(parentArchive)),
544
+ () =>
545
+ this.blockSource.syncImmediate().then(() => this.blockSource.getBlockData({ archive: parentArchive })),
401
546
  'force archiver sync',
402
547
  timeoutDurationMs / 1000,
403
548
  0.5,
@@ -542,48 +687,11 @@ export class ProposalHandler {
542
687
  ): Date {
543
688
  // Under proposer pipelining, the proposal slot may be ahead of wall clock time.
544
689
  // Reexecution budgets should still be bounded by the current slot we are in now.
545
- const wallclockSlot = slotNumber - this.epochCache.pipeliningOffset();
690
+ const wallclockSlot = slotNumber - PROPOSER_PIPELINING_SLOT_OFFSET;
546
691
  const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(wallclockSlot + 1), config));
547
692
  return new Date(nextSlotTimestampSeconds * 1000);
548
693
  }
549
694
 
550
- /** Waits for the block source to sync L1 data up to at least the slot before the given one. */
551
- private async waitForBlockSourceSync(slot: SlotNumber): Promise<boolean> {
552
- const deadline = this.getReexecutionDeadline(slot, this.checkpointsBuilder.getConfig());
553
- const timeoutMs = deadline.getTime() - this.dateProvider.now();
554
- if (slot === 0) {
555
- return true;
556
- }
557
-
558
- // Make a quick check before triggering an archiver sync
559
- // If we are pipelining and have a pending checkpoint number stored, we will allow the block proposal to be for a slot further
560
- const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
561
- if (syncedSlot !== undefined && syncedSlot + 1 + this.epochCache.pipeliningOffset() >= slot) {
562
- return true;
563
- }
564
-
565
- try {
566
- // Trigger an immediate sync of the block source, and wait until it reports being synced to the required slot
567
- return await retryUntil(
568
- async () => {
569
- await this.blockSource.syncImmediate();
570
- const updatedSyncedSlot = await this.blockSource.getSyncedL2SlotNumber();
571
- return updatedSyncedSlot !== undefined && updatedSyncedSlot + 1 >= slot;
572
- },
573
- 'wait for block source sync',
574
- timeoutMs / 1000,
575
- 0.5,
576
- );
577
- } catch (err) {
578
- if (err instanceof TimeoutError) {
579
- this.log.warn(`Timed out waiting for block source to sync to slot ${slot}`);
580
- return false;
581
- } else {
582
- throw err;
583
- }
584
- }
585
- }
586
-
587
695
  private getReexecuteFailureReason(err: any): BlockProposalValidationFailureReason {
588
696
  if (err instanceof TransactionsNotAvailableError) {
589
697
  return 'txs_not_available';
@@ -613,7 +721,7 @@ export class ProposalHandler {
613
721
  // If we do not have all of the transactions, then we should fail
614
722
  if (txs.length !== txHashes.length) {
615
723
  const foundTxHashes = txs.map(tx => tx.getTxHash());
616
- const missingTxHashes = txHashes.filter(txHash => !foundTxHashes.includes(txHash));
724
+ const missingTxHashes = txHashes.filter(txHash => !foundTxHashes.some(h => h.equals(txHash)));
617
725
  throw new TransactionsNotAvailableError(missingTxHashes);
618
726
  }
619
727
 
@@ -734,36 +842,46 @@ export class ProposalHandler {
734
842
  proposalInfo: LogData,
735
843
  ): Promise<CheckpointProposalValidationResult> {
736
844
  const slot = proposal.slotNumber;
845
+ const payloadHash = proposal.getPayloadHash();
737
846
 
738
- // Check cache: same archive+slot means we already validated this proposal
739
- if (
740
- this.lastCheckpointValidationResult &&
741
- this.lastCheckpointValidationResult.archive.equals(proposal.archive) &&
742
- this.lastCheckpointValidationResult.slotNumber === slot
743
- ) {
847
+ // Check cache: same signed-payload hash means we already validated this exact proposal.
848
+ if (this.lastCheckpointValidationResult && this.lastCheckpointValidationResult.payloadHash === payloadHash) {
744
849
  this.log.debug(`Returning cached validation result for checkpoint proposal at slot ${slot}`, proposalInfo);
745
850
  return this.lastCheckpointValidationResult.result;
746
851
  }
747
852
 
748
853
  const proposer = proposal.getSender();
854
+ let result: CheckpointProposalValidationResult;
749
855
  if (!proposer) {
750
856
  this.log.warn(`Received checkpoint proposal with invalid signature for slot ${proposal.slotNumber}`);
751
- const result: CheckpointProposalValidationResult = { isValid: false, reason: 'invalid_signature' };
752
- this.lastCheckpointValidationResult = { archive: proposal.archive, slotNumber: slot, result };
753
- return result;
754
- }
755
-
756
- if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
857
+ result = { isValid: false as const, reason: 'invalid_signature' };
858
+ } else if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
757
859
  this.log.warn(
758
860
  `Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${proposal.slotNumber}`,
759
861
  );
760
- const result: CheckpointProposalValidationResult = { isValid: false, reason: 'invalid_fee_asset_price_modifier' };
761
- this.lastCheckpointValidationResult = { archive: proposal.archive, slotNumber: slot, result };
762
- return result;
862
+ result = { isValid: false, reason: 'invalid_fee_asset_price_modifier' };
863
+ } else {
864
+ result = await this.validateCheckpointProposal(proposal, proposalInfo);
763
865
  }
764
866
 
765
- const result = await this.validateCheckpointProposal(proposal, proposalInfo);
766
- this.lastCheckpointValidationResult = { archive: proposal.archive, slotNumber: slot, result };
867
+ this.lastCheckpointValidationResult = { payloadHash, result };
868
+
869
+ // Record the outcome on the re-execution tracker.
870
+ const outcome = result.isValid ? ('valid' as const) : CHECKPOINT_VALIDATION_REASON_TO_OUTCOME[result.reason];
871
+ if (outcome !== undefined) {
872
+ this.reexecutionTracker.recordOutcome(slot, proposal.archive, outcome, result.checkpointNumber);
873
+ }
874
+
875
+ // Drop tracker entries for checkpoints that have reached L1 finality.
876
+ try {
877
+ const tips = await this.blockSource.getL2Tips();
878
+ const finalizedCheckpointNumber = tips.finalized.checkpoint.number;
879
+ if (finalizedCheckpointNumber > 0) {
880
+ this.reexecutionTracker.removeBefore(CheckpointNumber(finalizedCheckpointNumber + 1));
881
+ }
882
+ } catch (err) {
883
+ this.log.error(`Error pruning reexecution tracker`, err, proposalInfo);
884
+ }
767
885
 
768
886
  // Upload blobs to filestore if validation passed (fire and forget)
769
887
  if (result.isValid) {
@@ -783,18 +901,24 @@ export class ProposalHandler {
783
901
  ): Promise<CheckpointProposalValidationResult> {
784
902
  const slot = proposal.slotNumber;
785
903
 
786
- // Timeout block syncing at the start of the next slot
787
- const config = this.checkpointsBuilder.getConfig();
788
- const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
789
- const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
904
+ // Block-sync deadline = the L1 publish deadline, i.e. the latest moment the proposer can submit
905
+ // this checkpoint and still have it land on L1 in the target slot. That is 12s (one Ethereum
906
+ // slot) before the last L1 block of the target slot, which is later than the target-slot start
907
+ // used for block re-execution. Keeping validation/attestation alive until then lets validators
908
+ // keep attesting right up to the proposer's real publish cutoff.
909
+ const l1Constants = this.epochCache.getL1Constants();
910
+ const publishDeadlineSeconds =
911
+ Number(getLastL1SlotTimestampForL2Slot(slot, l1Constants)) - l1Constants.ethereumSlotDuration;
912
+ const deadline = new Date(publishDeadlineSeconds * 1000);
913
+ const timeoutSeconds = Math.max(1, Math.floor((deadline.getTime() - this.dateProvider.now()) / 1000));
790
914
 
791
915
  // Wait for last block to sync by archive
792
- let lastBlockHeader;
916
+ let lastBlockData;
793
917
  try {
794
- lastBlockHeader = await retryUntil(
918
+ lastBlockData = await retryUntil(
795
919
  async () => {
796
920
  await this.blockSource.syncImmediate();
797
- return this.blockSource.getBlockHeaderByArchive(proposal.archive);
921
+ return await this.blockSource.getBlockData({ archive: proposal.archive });
798
922
  },
799
923
  `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`,
800
924
  timeoutSeconds,
@@ -809,22 +933,54 @@ export class ProposalHandler {
809
933
  return { isValid: false, reason: 'block_fetch_error' };
810
934
  }
811
935
 
812
- if (!lastBlockHeader) {
936
+ if (!lastBlockData) {
813
937
  this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
814
938
  return { isValid: false, reason: 'last_block_not_found' };
815
939
  }
816
940
 
941
+ // Refuse to attest if the block's enclosing checkpoint has already been published to L1.
942
+ const existingCheckpoint = await this.blockSource.getCheckpointData({ number: lastBlockData.checkpointNumber });
943
+ if (existingCheckpoint) {
944
+ this.log.warn(`Refusing to attest to checkpoint proposal whose checkpoint is already on L1`, {
945
+ ...proposalInfo,
946
+ checkpointNumber: lastBlockData.checkpointNumber,
947
+ });
948
+ return {
949
+ isValid: false,
950
+ reason: 'checkpoint_already_published',
951
+ checkpointNumber: lastBlockData.checkpointNumber,
952
+ };
953
+ }
954
+
817
955
  // Get all full blocks for the slot and checkpoint
818
956
  const blocks = await this.blockSource.getBlocksForSlot(slot);
819
957
  if (blocks.length === 0) {
820
958
  this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
821
- return { isValid: false, reason: 'no_blocks_for_slot' };
959
+ return { isValid: false, reason: 'no_blocks_for_slot', checkpointNumber: lastBlockData.checkpointNumber };
822
960
  }
823
961
 
824
962
  // Ensure the last block for this slot matches the archive in the checkpoint proposal
825
963
  if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
826
964
  this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
827
- return { isValid: false, reason: 'last_block_archive_mismatch' };
965
+ return {
966
+ isValid: false,
967
+ reason: 'last_block_archive_mismatch',
968
+ checkpointNumber: lastBlockData.checkpointNumber,
969
+ };
970
+ }
971
+
972
+ const maxBlocksPerCheckpoint = this.config.maxBlocksPerCheckpoint;
973
+ if (maxBlocksPerCheckpoint !== undefined && blocks.length > maxBlocksPerCheckpoint) {
974
+ this.log.warn(`Checkpoint proposal exceeds maxBlocksPerCheckpoint`, {
975
+ ...proposalInfo,
976
+ blocksInProposal: blocks.length,
977
+ maxBlocksPerCheckpoint,
978
+ });
979
+ return {
980
+ isValid: false,
981
+ reason: 'too_many_blocks_in_checkpoint',
982
+ checkpointNumber: lastBlockData.checkpointNumber,
983
+ };
828
984
  }
829
985
 
830
986
  this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
@@ -840,11 +996,17 @@ export class ProposalHandler {
840
996
  // Get L1-to-L2 messages for this checkpoint
841
997
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
842
998
 
843
- // Collect the out hashes of all the checkpoints before this one in the same epoch
999
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
1000
+ // See note on the analogous block-proposal site: the helper handles pipelining lag.
844
1001
  const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
845
- const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch))
846
- .filter(c => c.checkpointNumber < checkpointNumber)
847
- .map(c => c.checkpointOutHash);
1002
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
1003
+ blockSource: this.blockSource,
1004
+ epoch,
1005
+ checkpointNumber,
1006
+ l1Constants: this.epochCache.getL1Constants(),
1007
+ pipeliningEnabled: true,
1008
+ log: this.log,
1009
+ });
848
1010
 
849
1011
  // Fork world state at the block before the first block
850
1012
  const parentBlockNumber = BlockNumber(firstBlock.number - 1);
@@ -872,7 +1034,7 @@ export class ProposalHandler {
872
1034
  computed: computedCheckpoint.header.toInspect(),
873
1035
  proposal: proposal.checkpointHeader.toInspect(),
874
1036
  });
875
- return { isValid: false, reason: 'checkpoint_header_mismatch' };
1037
+ return { isValid: false, reason: 'checkpoint_header_mismatch', checkpointNumber };
876
1038
  }
877
1039
 
878
1040
  // Compare archive root with proposal
@@ -882,7 +1044,7 @@ export class ProposalHandler {
882
1044
  computed: computedCheckpoint.archive.root.toString(),
883
1045
  proposal: proposal.archive.toString(),
884
1046
  });
885
- return { isValid: false, reason: 'archive_mismatch' };
1047
+ return { isValid: false, reason: 'archive_mismatch', checkpointNumber };
886
1048
  }
887
1049
 
888
1050
  // Check that the accumulated epoch out hash matches the value in the proposal.
@@ -898,7 +1060,7 @@ export class ProposalHandler {
898
1060
  previousCheckpointOutHashes: previousCheckpointOutHashes.map(h => h.toString()),
899
1061
  ...proposalInfo,
900
1062
  });
901
- return { isValid: false, reason: 'out_hash_mismatch' };
1063
+ return { isValid: false, reason: 'out_hash_mismatch', checkpointNumber };
902
1064
  }
903
1065
 
904
1066
  // Final round of validations on the checkpoint, just in case.
@@ -912,10 +1074,11 @@ export class ProposalHandler {
912
1074
  });
913
1075
  } catch (err) {
914
1076
  this.log.warn(`Checkpoint validation failed: ${err}`, proposalInfo);
915
- return { isValid: false, reason: 'checkpoint_validation_failed' };
1077
+ return { isValid: false, reason: 'checkpoint_validation_failed', checkpointNumber };
916
1078
  }
917
1079
 
918
1080
  this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
1081
+
919
1082
  return { isValid: true, checkpointNumber };
920
1083
  }
921
1084
 
@@ -943,7 +1106,7 @@ export class ProposalHandler {
943
1106
  /** Uploads blobs for a checkpoint to the filestore. */
944
1107
  protected async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
945
1108
  try {
946
- const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
1109
+ const lastBlockHeader = (await this.blockSource.getBlockData({ archive: proposal.archive }))?.header;
947
1110
  if (!lastBlockHeader) {
948
1111
  this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
949
1112
  return;
@@ -977,7 +1140,7 @@ export class ProposalHandler {
977
1140
  if (!this.archiver) {
978
1141
  return false;
979
1142
  }
980
- const blockData = await this.blockSource.getBlockDataByArchive(proposal.archive);
1143
+ const blockData = await this.blockSource.getBlockData({ archive: proposal.archive });
981
1144
  if (!blockData) {
982
1145
  this.log.debug(`Block data not found for checkpoint proposal archive, cannot set proposed checkpoint`, {
983
1146
  archive: proposal.archive.toString(),
@@ -985,7 +1148,7 @@ export class ProposalHandler {
985
1148
  return false;
986
1149
  }
987
1150
 
988
- await this.archiver.setProposedCheckpoint({
1151
+ await this.archiver.addProposedCheckpoint({
989
1152
  header: proposal.checkpointHeader,
990
1153
  checkpointNumber: blockData.checkpointNumber,
991
1154
  startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
@@ -995,48 +1158,4 @@ export class ProposalHandler {
995
1158
  });
996
1159
  return true;
997
1160
  }
998
-
999
- /**
1000
- * Sets proposed checkpoint from blocks for own proposals (skips full validation).
1001
- * Retries fetching block data since the checkpoint proposal often arrives before the last block
1002
- * finishes re-execution.
1003
- */
1004
- private async setProposedCheckpointFromBlocks(proposal: CheckpointProposalCore): Promise<boolean> {
1005
- if (!this.archiver) {
1006
- return false;
1007
- }
1008
- let blockData = await this.blockSource.getBlockDataByArchive(proposal.archive);
1009
-
1010
- if (!blockData) {
1011
- // The checkpoint proposal often arrives before the last block finishes re-execution.
1012
- // Retry until we find the data or give up at the end of the slot.
1013
- const nextSlot = this.epochCache.getSlotNow() + 1;
1014
- const timeOfNextSlot = getTimestampForSlot(SlotNumber(nextSlot), await this.archiver.getL1Constants());
1015
- const timeoutSeconds = Math.max(1, Number(timeOfNextSlot) - Math.floor(this.dateProvider.now() / 1000));
1016
-
1017
- blockData = await retryUntil(
1018
- () => this.blockSource.getBlockDataByArchive(proposal.archive),
1019
- 'block data for own checkpoint proposal',
1020
- timeoutSeconds,
1021
- 0.25,
1022
- ).catch(() => undefined);
1023
- }
1024
-
1025
- if (blockData) {
1026
- await this.archiver.setProposedCheckpoint({
1027
- header: proposal.checkpointHeader,
1028
- checkpointNumber: blockData.checkpointNumber,
1029
- startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
1030
- blockCount: blockData.indexWithinCheckpoint + 1,
1031
- totalManaUsed: proposal.checkpointHeader.totalManaUsed.toBigInt(),
1032
- feeAssetPriceModifier: proposal.feeAssetPriceModifier,
1033
- });
1034
- return true;
1035
- } else {
1036
- this.log.debug(`Block data not found for own checkpoint proposal archive, cannot set proposed checkpoint`, {
1037
- archive: proposal.archive.toString(),
1038
- });
1039
- return false;
1040
- }
1041
- }
1042
1161
  }