@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.
@@ -65,6 +65,7 @@ function _ts_dispose_resources(env) {
65
65
  }
66
66
  import { encodeCheckpointBlobDataFromBlocks, getBlobsPerL1Block } from '@aztec/blob-lib';
67
67
  import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
68
+ import { PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec/epoch-cache';
68
69
  import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
69
70
  import { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
70
71
  import { pick } from '@aztec/foundation/collection';
@@ -73,13 +74,31 @@ import { TimeoutError } from '@aztec/foundation/error';
73
74
  import { createLogger } from '@aztec/foundation/log';
74
75
  import { retryUntil } from '@aztec/foundation/retry';
75
76
  import { DateProvider, Timer } from '@aztec/foundation/timer';
76
- import { validateCheckpoint } from '@aztec/stdlib/checkpoint';
77
- import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
77
+ import { getPreviousCheckpointOutHashes, validateCheckpoint } from '@aztec/stdlib/checkpoint';
78
+ import { getEpochAtSlot, getLastL1SlotTimestampForL2Slot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
78
79
  import { Gas } from '@aztec/stdlib/gas';
79
80
  import { accumulateCheckpointOutHashes, computeInHashFromL1ToL2Messages } from '@aztec/stdlib/messaging';
80
81
  import { MerkleTreeId } from '@aztec/stdlib/trees';
81
82
  import { ReExFailedTxsError, ReExInitialStateMismatchError, ReExStateMismatchError, ReExTimeoutError, TransactionsNotAvailableError } from '@aztec/stdlib/validators';
82
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
+ };
83
102
  /** Handles block and checkpoint proposals for both validator and non-validator nodes. */ export class ProposalHandler {
84
103
  checkpointsBuilder;
85
104
  worldState;
@@ -90,14 +109,19 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
90
109
  epochCache;
91
110
  config;
92
111
  blobClient;
112
+ reexecutionTracker;
93
113
  metrics;
94
114
  dateProvider;
95
115
  log;
96
116
  tracer;
97
- /** Cached last checkpoint validation result to avoid double-validation on validator nodes. */ lastCheckpointValidationResult;
117
+ /** Cached last checkpoint validation result to avoid double-validation on validator nodes.
118
+ * Keyed by signed-payload hash so two proposals at the same (slot, archive) but with a
119
+ * different `feeAssetPriceModifier` (or any other signed field) are validated independently. */ lastCheckpointValidationResult;
98
120
  /** Archiver reference for setting proposed checkpoints (pipelining). Set via register(). */ archiver;
99
121
  /** Returns current validator addresses for own-proposal detection. Set via register(). */ getOwnValidatorAddresses;
100
- constructor(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, blobClient, metrics, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator:proposal-handler')){
122
+ /** P2P proposal pool access for deciding when retained proposals should block archiver processing. */ p2pClient;
123
+ checkpointProposalValidationFailureCallback;
124
+ constructor(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, blobClient, reexecutionTracker, metrics, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator:proposal-handler')){
101
125
  this.checkpointsBuilder = checkpointsBuilder;
102
126
  this.worldState = worldState;
103
127
  this.blockSource = blockSource;
@@ -107,6 +131,7 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
107
131
  this.epochCache = epochCache;
108
132
  this.config = config;
109
133
  this.blobClient = blobClient;
134
+ this.reexecutionTracker = reexecutionTracker;
110
135
  this.metrics = metrics;
111
136
  this.dateProvider = dateProvider;
112
137
  this.log = log;
@@ -115,13 +140,37 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
115
140
  }
116
141
  this.tracer = telemetry.getTracer('ProposalHandler');
117
142
  }
143
+ updateConfig(config) {
144
+ this.config = {
145
+ ...this.config,
146
+ ...config
147
+ };
148
+ }
149
+ setCheckpointProposalValidationFailureCallback(callback) {
150
+ this.checkpointProposalValidationFailureCallback = callback;
151
+ }
152
+ /**
153
+ * Records the proposer's own checkpoint proposal as a `valid` outcome in the re-execution
154
+ * tracker. Without this, the node's own checkpoint proposals never flow through
155
+ * `handleCheckpointProposal` (proposers don't validate their own proposals), so its sentinel
156
+ * sees no outcome for slots where it was the proposer and reports itself as inactive.
157
+ *
158
+ * `archive` should be the locally-computed archive (NOT the broadcast archive, which may have
159
+ * been deliberately corrupted in tests via `broadcastInvalidBlockProposal` /
160
+ * `broadcastInvalidCheckpointProposalOnly`). Recording the local archive correctly models the
161
+ * proposer's own view of its own work.
162
+ */ recordOwnCheckpointProposalAsValid(slot, archive, checkpointNumber) {
163
+ this.reexecutionTracker.recordOutcome(slot, archive, 'valid', checkpointNumber);
164
+ }
118
165
  /**
119
166
  * Registers handlers for block and checkpoint proposals on the p2p client.
167
+ * Records the p2p client so validation can inspect retained proposals.
120
168
  * Block proposals are registered for non-validator nodes (validators register their own enhanced handler).
121
169
  * The all-nodes checkpoint proposal handler is always registered for validation, caching, and pipelining.
122
170
  * @param archiver - Archiver reference for setting proposed checkpoints (pipelining)
123
171
  * @param getOwnValidatorAddresses - Returns current validator addresses for own-proposal detection
124
172
  */ register(p2pClient, shouldReexecute, archiver, getOwnValidatorAddresses) {
173
+ this.p2pClient = p2pClient;
125
174
  this.archiver = archiver;
126
175
  this.getOwnValidatorAddresses = getOwnValidatorAddresses;
127
176
  // Non-validator handler that processes or re-executes for monitoring but does not attest.
@@ -165,19 +214,30 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
165
214
  archive: proposal.archive.toString(),
166
215
  proposer: proposal.getSender()?.toString()
167
216
  };
168
- // For own proposals, skip validation — the proposer already built and validated the checkpoint
217
+ if (this.config.skipCheckpointProposalValidation) {
218
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposal.slotNumber}`, proposalInfo);
219
+ return undefined;
220
+ }
221
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposal.slotNumber)) {
222
+ this.log.warn(`Escape hatch open for slot ${proposal.slotNumber}, skipping checkpoint proposal validation`, proposalInfo);
223
+ return undefined;
224
+ }
225
+ // For own proposals, skip validation and return: the proposer already built and validated the
226
+ // checkpoint, and the sequencer's checkpoint proposal job pushed the proposed checkpoint to the
227
+ // archiver from local data before broadcasting. Gossipsub doesn't echo our own messages back, so
228
+ // this branch is normally unreachable — it remains as defense if an own proposal arrives by some
229
+ // other path.
169
230
  const proposer = proposal.getSender();
170
231
  const ownAddresses = this.getOwnValidatorAddresses?.();
171
232
  const isOwnProposal = proposer && ownAddresses?.some((addr)=>addr === proposer.toString());
172
233
  if (isOwnProposal) {
173
234
  this.log.debug(`Skipping validation for own checkpoint proposal at slot ${proposal.slotNumber}`);
174
- if (this.archiver && this.epochCache.isProposerPipeliningEnabled()) {
175
- await this.setProposedCheckpointFromBlocks(proposal);
176
- }
177
235
  return undefined;
178
236
  }
179
237
  const result = await this.handleCheckpointProposal(proposal, proposalInfo);
180
- if (result.isValid && this.archiver && this.epochCache.isProposerPipeliningEnabled()) {
238
+ if (!result.isValid) {
239
+ await this.checkpointProposalValidationFailureCallback?.(proposal, result, proposalInfo);
240
+ } else if (this.archiver) {
181
241
  const set = await this.setProposedCheckpointFromValidation(proposal);
182
242
  if (set) {
183
243
  this.metrics?.recordCheckpointProposalToPipelinedStateDuration(pipeliningTimer.ms());
@@ -202,7 +262,7 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
202
262
  this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
203
263
  return {
204
264
  isValid: false,
205
- reason: 'invalid_proposal'
265
+ reason: 'invalid_signature'
206
266
  };
207
267
  }
208
268
  const proposalInfo = {
@@ -225,23 +285,22 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
225
285
  reason: 'invalid_proposal'
226
286
  };
227
287
  }
228
- // Ensure the block source is synced before checking for existing blocks,
229
- // since a proposed checkpoint prune may remove blocks we'd otherwise find.
230
- // This affects mostly the block_number_already_exists check, since a pending
231
- // checkpoint prune could remove a block that would conflict with this proposal.
232
- // When pipelining is enabled, the proposer builds ahead of L1 submission, so the
233
- // block source won't have synced to the proposed slot yet. Skip the sync wait to
234
- // avoid eating into the attestation window.
235
- if (!this.epochCache.isProposerPipeliningEnabled()) {
236
- const blockSourceSync = await this.waitForBlockSourceSync(slotNumber);
237
- if (!blockSourceSync) {
238
- this.log.warn(`Block source is not synced, skipping processing`, proposalInfo);
239
- return {
240
- isValid: false,
241
- reason: 'block_source_not_synced'
242
- };
243
- }
288
+ const retainedSlotValidation = await this.validateNewBlockInSlot(proposal);
289
+ if (!retainedSlotValidation.isValid) {
290
+ this.log.info(`Block proposal conflicts with retained proposals, skipping archiver processing`, {
291
+ ...proposalInfo,
292
+ indexWithinCheckpoint: proposal.indexWithinCheckpoint,
293
+ reason: retainedSlotValidation.reason
294
+ });
295
+ return {
296
+ isValid: false,
297
+ blockNumber: proposal.blockNumber,
298
+ reason: retainedSlotValidation.reason
299
+ };
244
300
  }
301
+ // The proposer builds ahead of L1 submission under pipelining, so the block source won't have
302
+ // synced to the proposed slot yet. We deliberately do not wait for it to sync here, to avoid
303
+ // eating into the attestation window.
245
304
  // Check that the parent proposal is a block we know, otherwise reexecution would fail.
246
305
  // If we don't find it immediately, we keep retrying for a while; it may be we still
247
306
  // need to process other block proposals to get to it.
@@ -269,7 +328,9 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
269
328
  const blockNumber = parentBlock === 'genesis' ? BlockNumber(INITIAL_L2_BLOCK_NUM) : BlockNumber(parentBlock.header.getBlockNumber() + 1);
270
329
  proposalInfo.blockNumber = blockNumber;
271
330
  // Check that this block number does not exist already
272
- const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
331
+ const existingBlock = await this.blockSource.getBlockData({
332
+ number: blockNumber
333
+ });
273
334
  if (existingBlock) {
274
335
  this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
275
336
  return {
@@ -284,6 +345,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
284
345
  pinnedPeer: proposalSender,
285
346
  deadline: this.getReexecutionDeadline(slotNumber, config)
286
347
  });
348
+ // Record the tx-collection outcome on the re-execution tracker
349
+ this.reexecutionTracker.recordTxsCollected(slotNumber, proposal.indexWithinCheckpoint, missingTxs.length === 0);
287
350
  // If reexecution is disabled, bail. We were just interested in triggering tx collection.
288
351
  if (!shouldReexecute) {
289
352
  this.log.info(`Received valid block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, proposalInfo);
@@ -331,9 +394,18 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
331
394
  reason: 'txs_not_available'
332
395
  };
333
396
  }
334
- // Collect the out hashes of all the checkpoints before this one in the same epoch
397
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
398
+ // Mirror the proposer-side fallback: under pipelining the immediately-preceding cp may not
399
+ // yet be on L1, in which case the helper grafts the locally-known proposed cp's outHash.
335
400
  const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
336
- const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch)).filter((c)=>c.checkpointNumber < checkpointNumber).map((c)=>c.checkpointOutHash);
401
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
402
+ blockSource: this.blockSource,
403
+ epoch,
404
+ checkpointNumber,
405
+ l1Constants: this.epochCache.getL1Constants(),
406
+ pipeliningEnabled: true,
407
+ log: this.log
408
+ });
337
409
  // Try re-executing the transactions in the proposal if needed
338
410
  let reexecutionResult;
339
411
  try {
@@ -363,6 +435,33 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
363
435
  reexecutionResult
364
436
  };
365
437
  }
438
+ async validateNewBlockInSlot(blockProposal) {
439
+ if (!this.p2pClient) {
440
+ return {
441
+ isValid: true
442
+ };
443
+ }
444
+ const { blockProposals, checkpointProposals } = await this.p2pClient.getProposalsForSlot(blockProposal.slotNumber);
445
+ if (checkpointProposals.length === 0) {
446
+ return {
447
+ isValid: true
448
+ };
449
+ } else if (checkpointProposals.length > 1) {
450
+ return {
451
+ isValid: false,
452
+ reason: 'checkpoint_proposal_equivocation'
453
+ };
454
+ } else {
455
+ const checkpointProposal = checkpointProposals[0];
456
+ const terminalBlock = blockProposals.find((block)=>block.archive.equals(checkpointProposal.archive));
457
+ return terminalBlock !== undefined && blockProposal.indexWithinCheckpoint > terminalBlock.indexWithinCheckpoint ? {
458
+ isValid: false,
459
+ reason: 'block_proposal_beyond_checkpoint'
460
+ } : {
461
+ isValid: true
462
+ };
463
+ }
464
+ }
366
465
  async getParentBlock(proposal) {
367
466
  const parentArchive = proposal.blockHeader.lastArchive.root;
368
467
  const config = this.checkpointsBuilder.getConfig();
@@ -374,7 +473,11 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
374
473
  const currentTime = this.dateProvider.now();
375
474
  const timeoutDurationMs = deadline.getTime() - currentTime;
376
475
  try {
377
- return await this.blockSource.getBlockDataByArchive(parentArchive) ?? (timeoutDurationMs <= 0 ? undefined : await retryUntil(()=>this.blockSource.syncImmediate().then(()=>this.blockSource.getBlockDataByArchive(parentArchive)), 'force archiver sync', timeoutDurationMs / 1000, 0.5));
476
+ return await this.blockSource.getBlockData({
477
+ archive: parentArchive
478
+ }) ?? (timeoutDurationMs <= 0 ? undefined : await retryUntil(()=>this.blockSource.syncImmediate().then(()=>this.blockSource.getBlockData({
479
+ archive: parentArchive
480
+ })), 'force archiver sync', timeoutDurationMs / 1000, 0.5));
378
481
  } catch (err) {
379
482
  if (err instanceof TimeoutError) {
380
483
  this.log.debug(`Timed out getting parent block by archive root`, {
@@ -519,38 +622,10 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
519
622
  getReexecutionDeadline(slotNumber, config) {
520
623
  // Under proposer pipelining, the proposal slot may be ahead of wall clock time.
521
624
  // Reexecution budgets should still be bounded by the current slot we are in now.
522
- const wallclockSlot = slotNumber - this.epochCache.pipeliningOffset();
625
+ const wallclockSlot = slotNumber - PROPOSER_PIPELINING_SLOT_OFFSET;
523
626
  const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(wallclockSlot + 1), config));
524
627
  return new Date(nextSlotTimestampSeconds * 1000);
525
628
  }
526
- /** Waits for the block source to sync L1 data up to at least the slot before the given one. */ async waitForBlockSourceSync(slot) {
527
- const deadline = this.getReexecutionDeadline(slot, this.checkpointsBuilder.getConfig());
528
- const timeoutMs = deadline.getTime() - this.dateProvider.now();
529
- if (slot === 0) {
530
- return true;
531
- }
532
- // Make a quick check before triggering an archiver sync
533
- // If we are pipelining and have a pending checkpoint number stored, we will allow the block proposal to be for a slot further
534
- const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
535
- if (syncedSlot !== undefined && syncedSlot + 1 + this.epochCache.pipeliningOffset() >= slot) {
536
- return true;
537
- }
538
- try {
539
- // Trigger an immediate sync of the block source, and wait until it reports being synced to the required slot
540
- return await retryUntil(async ()=>{
541
- await this.blockSource.syncImmediate();
542
- const updatedSyncedSlot = await this.blockSource.getSyncedL2SlotNumber();
543
- return updatedSyncedSlot !== undefined && updatedSyncedSlot + 1 >= slot;
544
- }, 'wait for block source sync', timeoutMs / 1000, 0.5);
545
- } catch (err) {
546
- if (err instanceof TimeoutError) {
547
- this.log.warn(`Timed out waiting for block source to sync to slot ${slot}`);
548
- return false;
549
- } else {
550
- throw err;
551
- }
552
- }
553
- }
554
629
  getReexecuteFailureReason(err) {
555
630
  if (err instanceof TransactionsNotAvailableError) {
556
631
  return 'txs_not_available';
@@ -577,7 +652,7 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
577
652
  // If we do not have all of the transactions, then we should fail
578
653
  if (txs.length !== txHashes.length) {
579
654
  const foundTxHashes = txs.map((tx)=>tx.getTxHash());
580
- const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.includes(txHash));
655
+ const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.some((h)=>h.equals(txHash)));
581
656
  throw new TransactionsNotAvailableError(missingTxHashes);
582
657
  }
583
658
  const timer = new Timer();
@@ -673,44 +748,48 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
673
748
  * Used by both the all-nodes callback (via register) and the validator client (via delegation).
674
749
  */ async handleCheckpointProposal(proposal, proposalInfo) {
675
750
  const slot = proposal.slotNumber;
676
- // Check cache: same archive+slot means we already validated this proposal
677
- if (this.lastCheckpointValidationResult && this.lastCheckpointValidationResult.archive.equals(proposal.archive) && this.lastCheckpointValidationResult.slotNumber === slot) {
751
+ const payloadHash = proposal.getPayloadHash();
752
+ // Check cache: same signed-payload hash means we already validated this exact proposal.
753
+ if (this.lastCheckpointValidationResult && this.lastCheckpointValidationResult.payloadHash === payloadHash) {
678
754
  this.log.debug(`Returning cached validation result for checkpoint proposal at slot ${slot}`, proposalInfo);
679
755
  return this.lastCheckpointValidationResult.result;
680
756
  }
681
757
  const proposer = proposal.getSender();
758
+ let result;
682
759
  if (!proposer) {
683
760
  this.log.warn(`Received checkpoint proposal with invalid signature for slot ${proposal.slotNumber}`);
684
- const result = {
761
+ result = {
685
762
  isValid: false,
686
763
  reason: 'invalid_signature'
687
764
  };
688
- this.lastCheckpointValidationResult = {
689
- archive: proposal.archive,
690
- slotNumber: slot,
691
- result
692
- };
693
- return result;
694
- }
695
- if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
765
+ } else if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
696
766
  this.log.warn(`Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${proposal.slotNumber}`);
697
- const result = {
767
+ result = {
698
768
  isValid: false,
699
769
  reason: 'invalid_fee_asset_price_modifier'
700
770
  };
701
- this.lastCheckpointValidationResult = {
702
- archive: proposal.archive,
703
- slotNumber: slot,
704
- result
705
- };
706
- return result;
771
+ } else {
772
+ result = await this.validateCheckpointProposal(proposal, proposalInfo);
707
773
  }
708
- const result = await this.validateCheckpointProposal(proposal, proposalInfo);
709
774
  this.lastCheckpointValidationResult = {
710
- archive: proposal.archive,
711
- slotNumber: slot,
775
+ payloadHash,
712
776
  result
713
777
  };
778
+ // Record the outcome on the re-execution tracker.
779
+ const outcome = result.isValid ? 'valid' : CHECKPOINT_VALIDATION_REASON_TO_OUTCOME[result.reason];
780
+ if (outcome !== undefined) {
781
+ this.reexecutionTracker.recordOutcome(slot, proposal.archive, outcome, result.checkpointNumber);
782
+ }
783
+ // Drop tracker entries for checkpoints that have reached L1 finality.
784
+ try {
785
+ const tips = await this.blockSource.getL2Tips();
786
+ const finalizedCheckpointNumber = tips.finalized.checkpoint.number;
787
+ if (finalizedCheckpointNumber > 0) {
788
+ this.reexecutionTracker.removeBefore(CheckpointNumber(finalizedCheckpointNumber + 1));
789
+ }
790
+ } catch (err) {
791
+ this.log.error(`Error pruning reexecution tracker`, err, proposalInfo);
792
+ }
714
793
  // Upload blobs to filestore if validation passed (fire and forget)
715
794
  if (result.isValid) {
716
795
  this.tryUploadBlobsForCheckpoint(proposal, proposalInfo);
@@ -728,16 +807,23 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
728
807
  };
729
808
  try {
730
809
  const slot = proposal.slotNumber;
731
- // Timeout block syncing at the start of the next slot
732
- const config = this.checkpointsBuilder.getConfig();
733
- const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
734
- const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
810
+ // Block-sync deadline = the L1 publish deadline, i.e. the latest moment the proposer can submit
811
+ // this checkpoint and still have it land on L1 in the target slot. That is 12s (one Ethereum
812
+ // slot) before the last L1 block of the target slot, which is later than the target-slot start
813
+ // used for block re-execution. Keeping validation/attestation alive until then lets validators
814
+ // keep attesting right up to the proposer's real publish cutoff.
815
+ const l1Constants = this.epochCache.getL1Constants();
816
+ const publishDeadlineSeconds = Number(getLastL1SlotTimestampForL2Slot(slot, l1Constants)) - l1Constants.ethereumSlotDuration;
817
+ const deadline = new Date(publishDeadlineSeconds * 1000);
818
+ const timeoutSeconds = Math.max(1, Math.floor((deadline.getTime() - this.dateProvider.now()) / 1000));
735
819
  // Wait for last block to sync by archive
736
- let lastBlockHeader;
820
+ let lastBlockData;
737
821
  try {
738
- lastBlockHeader = await retryUntil(async ()=>{
822
+ lastBlockData = await retryUntil(async ()=>{
739
823
  await this.blockSource.syncImmediate();
740
- return this.blockSource.getBlockHeaderByArchive(proposal.archive);
824
+ return await this.blockSource.getBlockData({
825
+ archive: proposal.archive
826
+ });
741
827
  }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, timeoutSeconds, 0.5);
742
828
  } catch (err) {
743
829
  if (err instanceof TimeoutError) {
@@ -753,20 +839,36 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
753
839
  reason: 'block_fetch_error'
754
840
  };
755
841
  }
756
- if (!lastBlockHeader) {
842
+ if (!lastBlockData) {
757
843
  this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
758
844
  return {
759
845
  isValid: false,
760
846
  reason: 'last_block_not_found'
761
847
  };
762
848
  }
849
+ // Refuse to attest if the block's enclosing checkpoint has already been published to L1.
850
+ const existingCheckpoint = await this.blockSource.getCheckpointData({
851
+ number: lastBlockData.checkpointNumber
852
+ });
853
+ if (existingCheckpoint) {
854
+ this.log.warn(`Refusing to attest to checkpoint proposal whose checkpoint is already on L1`, {
855
+ ...proposalInfo,
856
+ checkpointNumber: lastBlockData.checkpointNumber
857
+ });
858
+ return {
859
+ isValid: false,
860
+ reason: 'checkpoint_already_published',
861
+ checkpointNumber: lastBlockData.checkpointNumber
862
+ };
863
+ }
763
864
  // Get all full blocks for the slot and checkpoint
764
865
  const blocks = await this.blockSource.getBlocksForSlot(slot);
765
866
  if (blocks.length === 0) {
766
867
  this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
767
868
  return {
768
869
  isValid: false,
769
- reason: 'no_blocks_for_slot'
870
+ reason: 'no_blocks_for_slot',
871
+ checkpointNumber: lastBlockData.checkpointNumber
770
872
  };
771
873
  }
772
874
  // Ensure the last block for this slot matches the archive in the checkpoint proposal
@@ -774,7 +876,21 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
774
876
  this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
775
877
  return {
776
878
  isValid: false,
777
- reason: 'last_block_archive_mismatch'
879
+ reason: 'last_block_archive_mismatch',
880
+ checkpointNumber: lastBlockData.checkpointNumber
881
+ };
882
+ }
883
+ const maxBlocksPerCheckpoint = this.config.maxBlocksPerCheckpoint;
884
+ if (maxBlocksPerCheckpoint !== undefined && blocks.length > maxBlocksPerCheckpoint) {
885
+ this.log.warn(`Checkpoint proposal exceeds maxBlocksPerCheckpoint`, {
886
+ ...proposalInfo,
887
+ blocksInProposal: blocks.length,
888
+ maxBlocksPerCheckpoint
889
+ });
890
+ return {
891
+ isValid: false,
892
+ reason: 'too_many_blocks_in_checkpoint',
893
+ checkpointNumber: lastBlockData.checkpointNumber
778
894
  };
779
895
  }
780
896
  this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
@@ -787,9 +903,17 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
787
903
  const checkpointNumber = firstBlock.checkpointNumber;
788
904
  // Get L1-to-L2 messages for this checkpoint
789
905
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
790
- // Collect the out hashes of all the checkpoints before this one in the same epoch
906
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
907
+ // See note on the analogous block-proposal site: the helper handles pipelining lag.
791
908
  const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
792
- const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch)).filter((c)=>c.checkpointNumber < checkpointNumber).map((c)=>c.checkpointOutHash);
909
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
910
+ blockSource: this.blockSource,
911
+ epoch,
912
+ checkpointNumber,
913
+ l1Constants: this.epochCache.getL1Constants(),
914
+ pipeliningEnabled: true,
915
+ log: this.log
916
+ });
793
917
  // Fork world state at the block before the first block
794
918
  const parentBlockNumber = BlockNumber(firstBlock.number - 1);
795
919
  const fork = _ts_add_disposable_resource(env, await this.checkpointsBuilder.getFork(parentBlockNumber), true);
@@ -806,7 +930,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
806
930
  });
807
931
  return {
808
932
  isValid: false,
809
- reason: 'checkpoint_header_mismatch'
933
+ reason: 'checkpoint_header_mismatch',
934
+ checkpointNumber
810
935
  };
811
936
  }
812
937
  // Compare archive root with proposal
@@ -818,7 +943,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
818
943
  });
819
944
  return {
820
945
  isValid: false,
821
- reason: 'archive_mismatch'
946
+ reason: 'archive_mismatch',
947
+ checkpointNumber
822
948
  };
823
949
  }
824
950
  // Check that the accumulated epoch out hash matches the value in the proposal.
@@ -839,7 +965,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
839
965
  });
840
966
  return {
841
967
  isValid: false,
842
- reason: 'out_hash_mismatch'
968
+ reason: 'out_hash_mismatch',
969
+ checkpointNumber
843
970
  };
844
971
  }
845
972
  // Final round of validations on the checkpoint, just in case.
@@ -855,7 +982,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
855
982
  this.log.warn(`Checkpoint validation failed: ${err}`, proposalInfo);
856
983
  return {
857
984
  isValid: false,
858
- reason: 'checkpoint_validation_failed'
985
+ reason: 'checkpoint_validation_failed',
986
+ checkpointNumber
859
987
  };
860
988
  }
861
989
  this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
@@ -890,7 +1018,9 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
890
1018
  }
891
1019
  /** Uploads blobs for a checkpoint to the filestore. */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
892
1020
  try {
893
- const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
1021
+ const lastBlockHeader = (await this.blockSource.getBlockData({
1022
+ archive: proposal.archive
1023
+ }))?.header;
894
1024
  if (!lastBlockHeader) {
895
1025
  this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
896
1026
  return;
@@ -920,14 +1050,16 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
920
1050
  if (!this.archiver) {
921
1051
  return false;
922
1052
  }
923
- const blockData = await this.blockSource.getBlockDataByArchive(proposal.archive);
1053
+ const blockData = await this.blockSource.getBlockData({
1054
+ archive: proposal.archive
1055
+ });
924
1056
  if (!blockData) {
925
1057
  this.log.debug(`Block data not found for checkpoint proposal archive, cannot set proposed checkpoint`, {
926
1058
  archive: proposal.archive.toString()
927
1059
  });
928
1060
  return false;
929
1061
  }
930
- await this.archiver.setProposedCheckpoint({
1062
+ await this.archiver.addProposedCheckpoint({
931
1063
  header: proposal.checkpointHeader,
932
1064
  checkpointNumber: blockData.checkpointNumber,
933
1065
  startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
@@ -937,38 +1069,4 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
937
1069
  });
938
1070
  return true;
939
1071
  }
940
- /**
941
- * Sets proposed checkpoint from blocks for own proposals (skips full validation).
942
- * Retries fetching block data since the checkpoint proposal often arrives before the last block
943
- * finishes re-execution.
944
- */ async setProposedCheckpointFromBlocks(proposal) {
945
- if (!this.archiver) {
946
- return false;
947
- }
948
- let blockData = await this.blockSource.getBlockDataByArchive(proposal.archive);
949
- if (!blockData) {
950
- // The checkpoint proposal often arrives before the last block finishes re-execution.
951
- // Retry until we find the data or give up at the end of the slot.
952
- const nextSlot = this.epochCache.getSlotNow() + 1;
953
- const timeOfNextSlot = getTimestampForSlot(SlotNumber(nextSlot), await this.archiver.getL1Constants());
954
- const timeoutSeconds = Math.max(1, Number(timeOfNextSlot) - Math.floor(this.dateProvider.now() / 1000));
955
- blockData = await retryUntil(()=>this.blockSource.getBlockDataByArchive(proposal.archive), 'block data for own checkpoint proposal', timeoutSeconds, 0.25).catch(()=>undefined);
956
- }
957
- if (blockData) {
958
- await this.archiver.setProposedCheckpoint({
959
- header: proposal.checkpointHeader,
960
- checkpointNumber: blockData.checkpointNumber,
961
- startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
962
- blockCount: blockData.indexWithinCheckpoint + 1,
963
- totalManaUsed: proposal.checkpointHeader.totalManaUsed.toBigInt(),
964
- feeAssetPriceModifier: proposal.feeAssetPriceModifier
965
- });
966
- return true;
967
- } else {
968
- this.log.debug(`Block data not found for own checkpoint proposal archive, cannot set proposed checkpoint`, {
969
- archive: proposal.archive.toString()
970
- });
971
- return false;
972
- }
973
- }
974
1072
  }