@aztec/validator-client 0.0.1-commit.2448fdb → 0.0.1-commit.2606882

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,11 +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
- constructor(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, blobClient, metrics, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator:proposal-handler')){
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;
120
+ /** Archiver reference for setting proposed checkpoints (pipelining). Set via register(). */ archiver;
121
+ /** Returns current validator addresses for own-proposal detection. Set via register(). */ getOwnValidatorAddresses;
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')){
98
125
  this.checkpointsBuilder = checkpointsBuilder;
99
126
  this.worldState = worldState;
100
127
  this.blockSource = blockSource;
@@ -104,6 +131,7 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
104
131
  this.epochCache = epochCache;
105
132
  this.config = config;
106
133
  this.blobClient = blobClient;
134
+ this.reexecutionTracker = reexecutionTracker;
107
135
  this.metrics = metrics;
108
136
  this.dateProvider = dateProvider;
109
137
  this.log = log;
@@ -112,10 +140,39 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
112
140
  }
113
141
  this.tracer = telemetry.getTracer('ProposalHandler');
114
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
+ }
115
165
  /**
116
- * Registers non-validator handlers for block and checkpoint proposals on the p2p client.
117
- * Block proposals are always registered. Checkpoint proposals are registered if the blob client can upload.
118
- */ register(p2pClient, shouldReexecute) {
166
+ * Registers handlers for block and checkpoint proposals on the p2p client.
167
+ * Records the p2p client so validation can inspect retained proposals.
168
+ * Block proposals are registered for non-validator nodes (validators register their own enhanced handler).
169
+ * The all-nodes checkpoint proposal handler is always registered for validation, caching, and pipelining.
170
+ * @param archiver - Archiver reference for setting proposed checkpoints (pipelining)
171
+ * @param getOwnValidatorAddresses - Returns current validator addresses for own-proposal detection
172
+ */ register(p2pClient, shouldReexecute, archiver, getOwnValidatorAddresses) {
173
+ this.p2pClient = p2pClient;
174
+ this.archiver = archiver;
175
+ this.getOwnValidatorAddresses = getOwnValidatorAddresses;
119
176
  // Non-validator handler that processes or re-executes for monitoring but does not attest.
120
177
  // Returns boolean indicating whether the proposal was valid.
121
178
  const blockHandler = async (proposal, proposalSender)=>{
@@ -146,29 +203,54 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
146
203
  }
147
204
  };
148
205
  p2pClient.registerBlockProposalHandler(blockHandler);
149
- // Register checkpoint proposal handler if blob uploads are enabled and we are reexecuting
150
- if (this.blobClient.canUpload() && shouldReexecute) {
151
- const checkpointHandler = async (checkpoint, _sender)=>{
152
- try {
153
- const proposalInfo = {
154
- proposalSlotNumber: checkpoint.slotNumber,
155
- archive: checkpoint.archive.toString(),
156
- proposer: checkpoint.getSender()?.toString()
157
- };
158
- const result = await this.handleCheckpointProposal(checkpoint, proposalInfo);
159
- if (result.isValid) {
160
- this.log.info(`Non-validator checkpoint proposal at slot ${checkpoint.slotNumber} handled`, proposalInfo);
161
- } else {
162
- this.log.warn(`Non-validator checkpoint proposal at slot ${checkpoint.slotNumber} failed: ${result.reason}`, proposalInfo);
206
+ // All-nodes checkpoint proposal handler: validates, caches, and sets proposed checkpoint for pipelining.
207
+ // Runs for all nodes (validators and non-validators). Validators get the cached result in the
208
+ // validator-specific callback (attestToCheckpointProposal) which runs after this one.
209
+ const checkpointHandler = async (proposal, _sender)=>{
210
+ try {
211
+ const pipeliningTimer = new Timer();
212
+ const proposalInfo = {
213
+ slot: proposal.slotNumber,
214
+ archive: proposal.archive.toString(),
215
+ proposer: proposal.getSender()?.toString()
216
+ };
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.
230
+ const proposer = proposal.getSender();
231
+ const ownAddresses = this.getOwnValidatorAddresses?.();
232
+ const isOwnProposal = proposer && ownAddresses?.some((addr)=>addr === proposer.toString());
233
+ if (isOwnProposal) {
234
+ this.log.debug(`Skipping validation for own checkpoint proposal at slot ${proposal.slotNumber}`);
235
+ return undefined;
236
+ }
237
+ const result = await this.handleCheckpointProposal(proposal, proposalInfo);
238
+ if (!result.isValid) {
239
+ await this.checkpointProposalValidationFailureCallback?.(proposal, result, proposalInfo);
240
+ } else if (this.archiver) {
241
+ const set = await this.setProposedCheckpointFromValidation(proposal);
242
+ if (set) {
243
+ this.metrics?.recordCheckpointProposalToPipelinedStateDuration(pipeliningTimer.ms());
163
244
  }
164
- } catch (error) {
165
- this.log.error('Error processing checkpoint proposal in non-validator handler', error);
166
245
  }
167
- // Non-validators don't attest
168
- return undefined;
169
- };
170
- p2pClient.registerCheckpointProposalHandler(checkpointHandler);
171
- }
246
+ } catch (err) {
247
+ this.log.warn(`Error handling checkpoint proposal for slot ${proposal.slotNumber}`, {
248
+ err
249
+ });
250
+ }
251
+ return undefined;
252
+ };
253
+ p2pClient.registerAllNodesCheckpointProposalHandler(checkpointHandler);
172
254
  return this;
173
255
  }
174
256
  async handleBlockProposal(proposal, proposalSender, shouldReexecute) {
@@ -180,7 +262,7 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
180
262
  this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
181
263
  return {
182
264
  isValid: false,
183
- reason: 'invalid_proposal'
265
+ reason: 'invalid_signature'
184
266
  };
185
267
  }
186
268
  const proposalInfo = {
@@ -203,19 +285,22 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
203
285
  reason: 'invalid_proposal'
204
286
  };
205
287
  }
206
- // Ensure the block source is synced before checking for existing blocks,
207
- // since a pending checkpoint prune may remove blocks we'd otherwise find.
208
- // This affects mostly the block_number_already_exists check, since a pending
209
- // checkpoint prune could remove a block that would conflict with this proposal.
210
- // TODO(@Maddiaa0): This may break staggered slots.
211
- const blockSourceSync = await this.waitForBlockSourceSync(slotNumber);
212
- if (!blockSourceSync) {
213
- this.log.warn(`Block source is not synced, skipping processing`, proposalInfo);
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
+ });
214
295
  return {
215
296
  isValid: false,
216
- reason: 'block_source_not_synced'
297
+ blockNumber: proposal.blockNumber,
298
+ reason: retainedSlotValidation.reason
217
299
  };
218
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.
219
304
  // Check that the parent proposal is a block we know, otherwise reexecution would fail.
220
305
  // If we don't find it immediately, we keep retrying for a while; it may be we still
221
306
  // need to process other block proposals to get to it.
@@ -243,7 +328,9 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
243
328
  const blockNumber = parentBlock === 'genesis' ? BlockNumber(INITIAL_L2_BLOCK_NUM) : BlockNumber(parentBlock.header.getBlockNumber() + 1);
244
329
  proposalInfo.blockNumber = blockNumber;
245
330
  // Check that this block number does not exist already
246
- const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
331
+ const existingBlock = await this.blockSource.getBlockData({
332
+ number: blockNumber
333
+ });
247
334
  if (existingBlock) {
248
335
  this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
249
336
  return {
@@ -258,6 +345,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
258
345
  pinnedPeer: proposalSender,
259
346
  deadline: this.getReexecutionDeadline(slotNumber, config)
260
347
  });
348
+ // Record the tx-collection outcome on the re-execution tracker
349
+ this.reexecutionTracker.recordTxsCollected(slotNumber, proposal.indexWithinCheckpoint, missingTxs.length === 0);
261
350
  // If reexecution is disabled, bail. We were just interested in triggering tx collection.
262
351
  if (!shouldReexecute) {
263
352
  this.log.info(`Received valid block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, proposalInfo);
@@ -305,9 +394,18 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
305
394
  reason: 'txs_not_available'
306
395
  };
307
396
  }
308
- // 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.
309
400
  const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
310
- 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
+ });
311
409
  // Try re-executing the transactions in the proposal if needed
312
410
  let reexecutionResult;
313
411
  try {
@@ -325,7 +423,7 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
325
423
  }
326
424
  // If we succeeded, push this block into the archiver (unless disabled)
327
425
  if (reexecutionResult?.block && this.config.skipPushProposedBlocksToArchiver === false) {
328
- await this.blockSource.addBlock(reexecutionResult?.block);
426
+ await this.blockSource.addBlock(reexecutionResult.block);
329
427
  }
330
428
  this.log.info(`Successfully re-executed block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, {
331
429
  ...proposalInfo,
@@ -337,19 +435,49 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
337
435
  reexecutionResult
338
436
  };
339
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
+ }
340
465
  async getParentBlock(proposal) {
341
466
  const parentArchive = proposal.blockHeader.lastArchive.root;
342
- const slot = proposal.slotNumber;
343
467
  const config = this.checkpointsBuilder.getConfig();
344
468
  const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
345
469
  if (parentArchive.equals(genesisArchiveRoot)) {
346
470
  return 'genesis';
347
471
  }
348
- const deadline = this.getReexecutionDeadline(slot, config);
472
+ const deadline = this.getReexecutionDeadline(proposal.slotNumber, config);
349
473
  const currentTime = this.dateProvider.now();
350
474
  const timeoutDurationMs = deadline.getTime() - currentTime;
351
475
  try {
352
- 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));
353
481
  } catch (err) {
354
482
  if (err instanceof TimeoutError) {
355
483
  this.log.debug(`Timed out getting parent block by archive root`, {
@@ -491,37 +619,13 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
491
619
  }
492
620
  return undefined;
493
621
  }
494
- getReexecutionDeadline(slot, config) {
495
- const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
622
+ getReexecutionDeadline(slotNumber, config) {
623
+ // Under proposer pipelining, the proposal slot may be ahead of wall clock time.
624
+ // Reexecution budgets should still be bounded by the current slot we are in now.
625
+ const wallclockSlot = slotNumber - PROPOSER_PIPELINING_SLOT_OFFSET;
626
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(wallclockSlot + 1), config));
496
627
  return new Date(nextSlotTimestampSeconds * 1000);
497
628
  }
498
- /** Waits for the block source to sync L1 data up to at least the slot before the given one. */ async waitForBlockSourceSync(slot) {
499
- const deadline = this.getReexecutionDeadline(slot, this.checkpointsBuilder.getConfig());
500
- const timeoutMs = deadline.getTime() - this.dateProvider.now();
501
- if (slot === 0) {
502
- return true;
503
- }
504
- // Make a quick check before triggering an archiver sync
505
- const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
506
- if (syncedSlot !== undefined && syncedSlot + 1 >= slot) {
507
- return true;
508
- }
509
- try {
510
- // Trigger an immediate sync of the block source, and wait until it reports being synced to the required slot
511
- return await retryUntil(async ()=>{
512
- await this.blockSource.syncImmediate();
513
- const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
514
- return syncedSlot !== undefined && syncedSlot + 1 >= slot;
515
- }, 'wait for block source sync', timeoutMs / 1000, 0.5);
516
- } catch (err) {
517
- if (err instanceof TimeoutError) {
518
- this.log.warn(`Timed out waiting for block source to sync to slot ${slot}`);
519
- return false;
520
- } else {
521
- throw err;
522
- }
523
- }
524
- }
525
629
  getReexecuteFailureReason(err) {
526
630
  if (err instanceof TransactionsNotAvailableError) {
527
631
  return 'txs_not_available';
@@ -548,7 +652,7 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
548
652
  // If we do not have all of the transactions, then we should fail
549
653
  if (txs.length !== txHashes.length) {
550
654
  const foundTxHashes = txs.map((tx)=>tx.getTxHash());
551
- const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.includes(txHash));
655
+ const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.some((h)=>h.equals(txHash)));
552
656
  throw new TransactionsNotAvailableError(missingTxHashes);
553
657
  }
554
658
  const timer = new Timer();
@@ -639,25 +743,53 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
639
743
  }
640
744
  }
641
745
  /**
642
- * Validates a checkpoint proposal and uploads blobs if configured.
643
- * Used by both non-validator nodes (via register) and the validator client (via delegation).
746
+ * Validates a checkpoint proposal, caches the result, and uploads blobs if configured.
747
+ * Returns a cached result if the same proposal (archive + slot) was already validated.
748
+ * Used by both the all-nodes callback (via register) and the validator client (via delegation).
644
749
  */ async handleCheckpointProposal(proposal, proposalInfo) {
750
+ const slot = proposal.slotNumber;
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) {
754
+ this.log.debug(`Returning cached validation result for checkpoint proposal at slot ${slot}`, proposalInfo);
755
+ return this.lastCheckpointValidationResult.result;
756
+ }
645
757
  const proposer = proposal.getSender();
758
+ let result;
646
759
  if (!proposer) {
647
760
  this.log.warn(`Received checkpoint proposal with invalid signature for slot ${proposal.slotNumber}`);
648
- return {
761
+ result = {
649
762
  isValid: false,
650
763
  reason: 'invalid_signature'
651
764
  };
652
- }
653
- if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
765
+ } else if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
654
766
  this.log.warn(`Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${proposal.slotNumber}`);
655
- return {
767
+ result = {
656
768
  isValid: false,
657
769
  reason: 'invalid_fee_asset_price_modifier'
658
770
  };
771
+ } else {
772
+ result = await this.validateCheckpointProposal(proposal, proposalInfo);
773
+ }
774
+ this.lastCheckpointValidationResult = {
775
+ payloadHash,
776
+ result
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);
659
792
  }
660
- const result = await this.validateCheckpointProposal(proposal, proposalInfo);
661
793
  // Upload blobs to filestore if validation passed (fire and forget)
662
794
  if (result.isValid) {
663
795
  this.tryUploadBlobsForCheckpoint(proposal, proposalInfo);
@@ -668,73 +800,123 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
668
800
  * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
669
801
  * @returns Validation result with isValid flag and reason if invalid.
670
802
  */ async validateCheckpointProposal(proposal, proposalInfo) {
671
- const slot = proposal.slotNumber;
672
- // Timeout block syncing at the start of the next slot
673
- const config = this.checkpointsBuilder.getConfig();
674
- const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
675
- const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
676
- // Wait for last block to sync by archive
677
- let lastBlockHeader;
803
+ const env = {
804
+ stack: [],
805
+ error: void 0,
806
+ hasError: false
807
+ };
678
808
  try {
679
- lastBlockHeader = await retryUntil(async ()=>{
680
- await this.blockSource.syncImmediate();
681
- return this.blockSource.getBlockHeaderByArchive(proposal.archive);
682
- }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, timeoutSeconds, 0.5);
683
- } catch (err) {
684
- if (err instanceof TimeoutError) {
685
- this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
809
+ const slot = proposal.slotNumber;
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));
819
+ // Wait for last block to sync by archive
820
+ let lastBlockData;
821
+ try {
822
+ lastBlockData = await retryUntil(async ()=>{
823
+ await this.blockSource.syncImmediate();
824
+ return await this.blockSource.getBlockData({
825
+ archive: proposal.archive
826
+ });
827
+ }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, timeoutSeconds, 0.5);
828
+ } catch (err) {
829
+ if (err instanceof TimeoutError) {
830
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
831
+ return {
832
+ isValid: false,
833
+ reason: 'last_block_not_found'
834
+ };
835
+ }
836
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
837
+ return {
838
+ isValid: false,
839
+ reason: 'block_fetch_error'
840
+ };
841
+ }
842
+ if (!lastBlockData) {
843
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
686
844
  return {
687
845
  isValid: false,
688
846
  reason: 'last_block_not_found'
689
847
  };
690
848
  }
691
- this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
692
- return {
693
- isValid: false,
694
- reason: 'block_fetch_error'
695
- };
696
- }
697
- if (!lastBlockHeader) {
698
- this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
699
- return {
700
- isValid: false,
701
- reason: 'last_block_not_found'
702
- };
703
- }
704
- // Get all full blocks for the slot and checkpoint
705
- const blocks = await this.blockSource.getBlocksForSlot(slot);
706
- if (blocks.length === 0) {
707
- this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
708
- return {
709
- isValid: false,
710
- reason: 'no_blocks_for_slot'
711
- };
712
- }
713
- // Ensure the last block for this slot matches the archive in the checkpoint proposal
714
- if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
715
- this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
716
- return {
717
- isValid: false,
718
- reason: 'last_block_archive_mismatch'
719
- };
720
- }
721
- this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
722
- ...proposalInfo,
723
- blockNumbers: blocks.map((b)=>b.number)
724
- });
725
- // Get checkpoint constants from first block
726
- const firstBlock = blocks[0];
727
- const constants = this.extractCheckpointConstants(firstBlock);
728
- const checkpointNumber = firstBlock.checkpointNumber;
729
- // Get L1-to-L2 messages for this checkpoint
730
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
731
- // Collect the out hashes of all the checkpoints before this one in the same epoch
732
- const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
733
- const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch)).filter((c)=>c.checkpointNumber < checkpointNumber).map((c)=>c.checkpointOutHash);
734
- // Fork world state at the block before the first block
735
- const parentBlockNumber = BlockNumber(firstBlock.number - 1);
736
- const fork = await this.worldState.fork(parentBlockNumber);
737
- try {
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
+ }
864
+ // Get all full blocks for the slot and checkpoint
865
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
866
+ if (blocks.length === 0) {
867
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
868
+ return {
869
+ isValid: false,
870
+ reason: 'no_blocks_for_slot',
871
+ checkpointNumber: lastBlockData.checkpointNumber
872
+ };
873
+ }
874
+ // Ensure the last block for this slot matches the archive in the checkpoint proposal
875
+ if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
876
+ this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
877
+ return {
878
+ isValid: false,
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
894
+ };
895
+ }
896
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
897
+ ...proposalInfo,
898
+ blockNumbers: blocks.map((b)=>b.number)
899
+ });
900
+ // Get checkpoint constants from first block
901
+ const firstBlock = blocks[0];
902
+ const constants = this.extractCheckpointConstants(firstBlock);
903
+ const checkpointNumber = firstBlock.checkpointNumber;
904
+ // Get L1-to-L2 messages for this checkpoint
905
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
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.
908
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
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
+ });
917
+ // Fork world state at the block before the first block
918
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
919
+ const fork = _ts_add_disposable_resource(env, await this.checkpointsBuilder.getFork(parentBlockNumber), true);
738
920
  // Create checkpoint builder with all existing blocks
739
921
  const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, proposal.feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks, this.log.getBindings());
740
922
  // Complete the checkpoint to get computed values
@@ -748,7 +930,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
748
930
  });
749
931
  return {
750
932
  isValid: false,
751
- reason: 'checkpoint_header_mismatch'
933
+ reason: 'checkpoint_header_mismatch',
934
+ checkpointNumber
752
935
  };
753
936
  }
754
937
  // Compare archive root with proposal
@@ -760,7 +943,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
760
943
  });
761
944
  return {
762
945
  isValid: false,
763
- reason: 'archive_mismatch'
946
+ reason: 'archive_mismatch',
947
+ checkpointNumber
764
948
  };
765
949
  }
766
950
  // Check that the accumulated epoch out hash matches the value in the proposal.
@@ -781,7 +965,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
781
965
  });
782
966
  return {
783
967
  isValid: false,
784
- reason: 'out_hash_mismatch'
968
+ reason: 'out_hash_mismatch',
969
+ checkpointNumber
785
970
  };
786
971
  }
787
972
  // Final round of validations on the checkpoint, just in case.
@@ -797,15 +982,21 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
797
982
  this.log.warn(`Checkpoint validation failed: ${err}`, proposalInfo);
798
983
  return {
799
984
  isValid: false,
800
- reason: 'checkpoint_validation_failed'
985
+ reason: 'checkpoint_validation_failed',
986
+ checkpointNumber
801
987
  };
802
988
  }
803
989
  this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
804
990
  return {
805
- isValid: true
991
+ isValid: true,
992
+ checkpointNumber
806
993
  };
994
+ } catch (e) {
995
+ env.error = e;
996
+ env.hasError = true;
807
997
  } finally{
808
- await fork.close();
998
+ const result = _ts_dispose_resources(env);
999
+ if (result) await result;
809
1000
  }
810
1001
  }
811
1002
  /** Extracts checkpoint global variables from a block. */ extractCheckpointConstants(block) {
@@ -827,7 +1018,9 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
827
1018
  }
828
1019
  /** Uploads blobs for a checkpoint to the filestore. */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
829
1020
  try {
830
- const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
1021
+ const lastBlockHeader = (await this.blockSource.getBlockData({
1022
+ archive: proposal.archive
1023
+ }))?.header;
831
1024
  if (!lastBlockHeader) {
832
1025
  this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
833
1026
  return;
@@ -849,4 +1042,31 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
849
1042
  this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
850
1043
  }
851
1044
  }
1045
+ /**
1046
+ * Derives proposed checkpoint data from validated blocks and sets it on the archiver.
1047
+ * Used after successful validation of a foreign proposal.
1048
+ * Does not retry since we already waited for the block during validation.
1049
+ */ async setProposedCheckpointFromValidation(proposal) {
1050
+ if (!this.archiver) {
1051
+ return false;
1052
+ }
1053
+ const blockData = await this.blockSource.getBlockData({
1054
+ archive: proposal.archive
1055
+ });
1056
+ if (!blockData) {
1057
+ this.log.debug(`Block data not found for checkpoint proposal archive, cannot set proposed checkpoint`, {
1058
+ archive: proposal.archive.toString()
1059
+ });
1060
+ return false;
1061
+ }
1062
+ await this.archiver.addProposedCheckpoint({
1063
+ header: proposal.checkpointHeader,
1064
+ checkpointNumber: blockData.checkpointNumber,
1065
+ startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
1066
+ blockCount: blockData.indexWithinCheckpoint + 1,
1067
+ totalManaUsed: proposal.checkpointHeader.totalManaUsed.toBigInt(),
1068
+ feeAssetPriceModifier: proposal.feeAssetPriceModifier
1069
+ });
1070
+ return true;
1071
+ }
852
1072
  }