@aztec/validator-client 0.0.1-commit.9ef841308 → 0.0.1-commit.a4600f49

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.
@@ -66,21 +66,73 @@ function _ts_dispose_resources(env) {
66
66
  import { encodeCheckpointBlobDataFromBlocks, getBlobsPerL1Block } from '@aztec/blob-lib';
67
67
  import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
68
68
  import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
69
- import { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
69
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
70
70
  import { pick } from '@aztec/foundation/collection';
71
71
  import { Fr } from '@aztec/foundation/curves/bn254';
72
72
  import { TimeoutError } from '@aztec/foundation/error';
73
+ import { FifoSet } from '@aztec/foundation/fifo-set';
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 } 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';
83
- /** Handles block and checkpoint proposals for both validator and non-validator nodes. */ export class ProposalHandler {
84
+ /**
85
+ * Mapping from a checkpoint-proposal validation failure reason to the tracker outcome that
86
+ * `handleCheckpointProposal` should record. `undefined` means do not record (signature
87
+ * couldn't be verified, or the checkpoint is already on L1 so the question is moot).
88
+ */ /* eslint-disable camelcase */ const CHECKPOINT_VALIDATION_REASON_TO_OUTCOME = {
89
+ invalid_signature: undefined,
90
+ invalid_fee_asset_price_modifier: 'invalid',
91
+ checkpoint_already_published: undefined,
92
+ last_block_not_found: 'unvalidated',
93
+ block_fetch_error: 'unvalidated',
94
+ no_blocks_for_slot: 'unvalidated',
95
+ last_block_archive_mismatch: 'invalid',
96
+ too_many_blocks_in_checkpoint: 'invalid',
97
+ checkpoint_header_mismatch: 'invalid',
98
+ archive_mismatch: 'invalid',
99
+ out_hash_mismatch: 'invalid',
100
+ checkpoint_validation_failed: 'invalid'
101
+ };
102
+ const MAX_TRACKED_INVALID_PROPOSAL_SLOTS = 1000;
103
+ /** Block-proposal validation failures that constitute a slashable invalid-block offense. */ export const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
104
+ 'state_mismatch',
105
+ 'failed_txs',
106
+ 'global_variables_mismatch',
107
+ 'invalid_proposal',
108
+ 'parent_block_wrong_slot',
109
+ 'in_hash_mismatch'
110
+ ];
111
+ /** Checkpoint-proposal validation failures that constitute a slashable invalid-checkpoint offense. */ export const SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT = {
112
+ // enabled
113
+ ['invalid_fee_asset_price_modifier']: true,
114
+ ['checkpoint_header_mismatch']: true,
115
+ // These late mismatches should normally be caught by earlier checks, but if reached after validating the local
116
+ // checkpoint inputs, the proposer-signed payload disagrees with deterministic recomputation.
117
+ ['archive_mismatch']: true,
118
+ ['out_hash_mismatch']: true,
119
+ ['no_blocks_for_slot']: true,
120
+ ['too_many_blocks_in_checkpoint']: true,
121
+ ['checkpoint_validation_failed']: true,
122
+ ['last_block_archive_mismatch']: true,
123
+ // disabled
124
+ ['invalid_signature']: false,
125
+ ['last_block_not_found']: false,
126
+ ['block_fetch_error']: false,
127
+ ['checkpoint_already_published']: false
128
+ };
129
+ /**
130
+ * Handles block and checkpoint proposals for both validator and non-validator nodes. Also tracks which slots
131
+ * had a slashable invalid proposal or a proposal equivocation, exposing them via the
132
+ * `InvalidProposalSlotSource` interface consumed by the attested-invalid-proposal slashing watcher. The
133
+ * tracking is populated as a side effect of validating/re-executing proposals, so any node that re-executes
134
+ * proposals (the default) can serve it — not only validators.
135
+ */ export class ProposalHandler {
84
136
  checkpointsBuilder;
85
137
  worldState;
86
138
  blockSource;
@@ -88,13 +140,24 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
88
140
  txProvider;
89
141
  blockProposalValidator;
90
142
  epochCache;
143
+ timetable;
91
144
  config;
92
145
  blobClient;
146
+ reexecutionTracker;
93
147
  metrics;
94
148
  dateProvider;
95
149
  log;
96
150
  tracer;
97
- constructor(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, config, blobClient, metrics, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator:proposal-handler')){
151
+ /** Cached last checkpoint validation result to avoid double-validation on validator nodes.
152
+ * Keyed by signed-payload hash so two proposals at the same (slot, archive) but with a
153
+ * different `feeAssetPriceModifier` (or any other signed field) are validated independently. */ lastCheckpointValidationResult;
154
+ /** Archiver reference for setting proposed checkpoints (pipelining). Set via register(). */ archiver;
155
+ /** Returns current validator addresses for own-proposal detection. Set via register(). */ getOwnValidatorAddresses;
156
+ /** P2P proposal pool access for deciding when retained proposals should block archiver processing. */ p2pClient;
157
+ checkpointProposalValidationFailureCallback;
158
+ /** Slots at which a slashable invalid block or checkpoint proposal was observed. */ slotsWithInvalidProposals;
159
+ /** Slots at which a proposal equivocation was observed; suppresses attested-to-invalid-proposal slashing. */ slotsWithProposalEquivocation;
160
+ constructor(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, blockProposalValidator, epochCache, timetable, config, blobClient, reexecutionTracker, metrics, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator:proposal-handler')){
98
161
  this.checkpointsBuilder = checkpointsBuilder;
99
162
  this.worldState = worldState;
100
163
  this.blockSource = blockSource;
@@ -102,20 +165,65 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
102
165
  this.txProvider = txProvider;
103
166
  this.blockProposalValidator = blockProposalValidator;
104
167
  this.epochCache = epochCache;
168
+ this.timetable = timetable;
105
169
  this.config = config;
106
170
  this.blobClient = blobClient;
171
+ this.reexecutionTracker = reexecutionTracker;
107
172
  this.metrics = metrics;
108
173
  this.dateProvider = dateProvider;
109
174
  this.log = log;
175
+ this.slotsWithInvalidProposals = FifoSet.withLimit(MAX_TRACKED_INVALID_PROPOSAL_SLOTS);
176
+ this.slotsWithProposalEquivocation = FifoSet.withLimit(MAX_TRACKED_INVALID_PROPOSAL_SLOTS);
110
177
  if (config.fishermanMode) {
111
178
  this.log = this.log.createChild('[FISHERMAN]');
112
179
  }
113
180
  this.tracer = telemetry.getTracer('ProposalHandler');
114
181
  }
182
+ updateConfig(config) {
183
+ this.config = {
184
+ ...this.config,
185
+ ...config
186
+ };
187
+ }
188
+ setCheckpointProposalValidationFailureCallback(callback) {
189
+ this.checkpointProposalValidationFailureCallback = callback;
190
+ }
115
191
  /**
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) {
192
+ * Records the proposer's own checkpoint proposal as a `valid` outcome in the re-execution
193
+ * tracker. Without this, the node's own checkpoint proposals never flow through
194
+ * `handleCheckpointProposal` (proposers don't validate their own proposals), so its sentinel
195
+ * sees no outcome for slots where it was the proposer and reports itself as inactive.
196
+ *
197
+ * `archive` should be the locally-computed archive (NOT the broadcast archive, which may have
198
+ * been deliberately corrupted in tests via `broadcastInvalidBlockProposal` /
199
+ * `broadcastInvalidCheckpointProposalOnly`). Recording the local archive correctly models the
200
+ * proposer's own view of its own work.
201
+ */ recordOwnCheckpointProposalAsValid(slot, archive, checkpointNumber) {
202
+ this.reexecutionTracker.recordOutcome(slot, archive, 'valid', checkpointNumber);
203
+ }
204
+ /** Whether a slashable invalid block or checkpoint proposal was observed at the given slot (InvalidProposalSlotSource). */ hasInvalidProposals(slotNumber) {
205
+ return this.slotsWithInvalidProposals.has(slotNumber);
206
+ }
207
+ /** Whether a proposal equivocation was observed at the given slot (InvalidProposalSlotSource). */ hasProposalEquivocation(slotNumber) {
208
+ return this.slotsWithProposalEquivocation.has(slotNumber);
209
+ }
210
+ /** Records a slot as having a slashable invalid proposal, for offense observers (sentinel/slasher watchers). */ markInvalidProposalSlot(slotNumber) {
211
+ this.slotsWithInvalidProposals.add(slotNumber);
212
+ }
213
+ /** Records a slot as having a proposal equivocation, which suppresses attested-to-invalid-proposal slashing. */ markProposalEquivocation(slotNumber) {
214
+ this.slotsWithProposalEquivocation.add(slotNumber);
215
+ }
216
+ /**
217
+ * Registers handlers for block and checkpoint proposals on the p2p client.
218
+ * Records the p2p client so validation can inspect retained proposals.
219
+ * Block proposals are registered for non-validator nodes (validators register their own enhanced handler).
220
+ * The all-nodes checkpoint proposal handler is always registered for validation, caching, and pipelining.
221
+ * @param archiver - Archiver reference for setting proposed checkpoints (pipelining)
222
+ * @param getOwnValidatorAddresses - Returns current validator addresses for own-proposal detection
223
+ */ register(p2pClient, shouldReexecute, archiver, getOwnValidatorAddresses) {
224
+ this.p2pClient = p2pClient;
225
+ this.archiver = archiver;
226
+ this.getOwnValidatorAddresses = getOwnValidatorAddresses;
119
227
  // Non-validator handler that processes or re-executes for monitoring but does not attest.
120
228
  // Returns boolean indicating whether the proposal was valid.
121
229
  const blockHandler = async (proposal, proposalSender)=>{
@@ -133,6 +241,15 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
133
241
  });
134
242
  return true;
135
243
  } else {
244
+ // Track invalid proposals / equivocations so offense observers (the attested-invalid-proposal
245
+ // watcher) work on non-validator nodes too. Validators populate these via their own handlers.
246
+ // Skip invalid-proposal marking while the escape hatch is open, matching the validator path,
247
+ // which intentionally disables invalid-block slashing then.
248
+ if (result.reason === 'checkpoint_proposal_equivocation') {
249
+ this.markProposalEquivocation(slotNumber);
250
+ } else if (SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(result.reason) && !await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
251
+ this.markInvalidProposalSlot(slotNumber);
252
+ }
136
253
  this.log.warn(`Non-validator block proposal ${blockNumber} at slot ${slotNumber} failed processing with ${result.reason}`, {
137
254
  blockNumber: result.blockNumber,
138
255
  slotNumber,
@@ -146,41 +263,81 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
146
263
  }
147
264
  };
148
265
  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);
266
+ // p2p detects duplicate (equivocated) proposals without routing them through the handlers above, so mark
267
+ // the slot as equivocated here. This suppresses false-positive attested-to-invalid-proposal slashing on
268
+ // non-validator offense collectors. Validators overwrite this with their own richer handler.
269
+ p2pClient.registerDuplicateProposalCallback((info)=>this.markProposalEquivocation(info.slot));
270
+ // All-nodes checkpoint proposal handler: validates, caches, and sets proposed checkpoint for pipelining.
271
+ // Runs for all nodes (validators and non-validators). Validators get the cached result in the
272
+ // validator-specific callback (attestToCheckpointProposal) which runs after this one.
273
+ const checkpointHandler = async (proposal, _sender)=>{
274
+ try {
275
+ const pipeliningTimer = new Timer();
276
+ const proposalInfo = {
277
+ slot: proposal.slotNumber,
278
+ archive: proposal.archive.toString(),
279
+ proposer: proposal.getSender()?.toString()
280
+ };
281
+ if (this.config.skipCheckpointProposalValidation) {
282
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposal.slotNumber}`, proposalInfo);
283
+ return undefined;
284
+ }
285
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposal.slotNumber)) {
286
+ this.log.warn(`Escape hatch open for slot ${proposal.slotNumber}, skipping checkpoint proposal validation`, proposalInfo);
287
+ return undefined;
288
+ }
289
+ // A proposal is "own" when it was signed by a validator key this node also owns. The true local
290
+ // proposer already built, validated, and stored this checkpoint before broadcasting, so a matching
291
+ // proposed checkpoint is already in its archiver — skip the redundant re-validation. An HA peer that
292
+ // shares the proposer's keys sees the same "own" proposal over gossip but never built it, so it has
293
+ // nothing stored; it falls through to the normal validate-and-persist path below to hydrate the
294
+ // proposed-checkpoint metadata it needs to build the next slot on top of this checkpoint.
295
+ const proposer = proposal.getSender();
296
+ const ownAddresses = this.getOwnValidatorAddresses?.();
297
+ const isOwnProposal = proposer && ownAddresses?.some((addr)=>addr === proposer.toString());
298
+ if (isOwnProposal) {
299
+ const existing = await this.archiver?.getProposedCheckpointData({
300
+ slot: proposal.slotNumber
301
+ });
302
+ if (existing?.archive.root.equals(proposal.archive)) {
303
+ this.log.debug(`Skipping sync for existing own checkpoint proposal at slot ${proposal.slotNumber}`);
304
+ return undefined;
163
305
  }
164
- } catch (error) {
165
- this.log.error('Error processing checkpoint proposal in non-validator handler', error);
166
306
  }
167
- // Non-validators don't attest
168
- return undefined;
169
- };
170
- p2pClient.registerCheckpointProposalHandler(checkpointHandler);
171
- }
307
+ const result = await this.handleCheckpointProposal(proposal, proposalInfo);
308
+ if (!result.isValid) {
309
+ // Track invalid checkpoint proposals so offense observers (the attested-invalid-proposal watcher)
310
+ // work on non-validator nodes too. This handler runs for all nodes; validators also mark via the
311
+ // failure callback below (idempotent).
312
+ if (SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT[result.reason]) {
313
+ this.markInvalidProposalSlot(proposal.slotNumber);
314
+ }
315
+ await this.checkpointProposalValidationFailureCallback?.(proposal, result, proposalInfo);
316
+ } else if (this.archiver) {
317
+ const set = await this.setProposedCheckpoint(proposal);
318
+ if (set) {
319
+ this.metrics?.recordCheckpointProposalToPipelinedStateDuration(pipeliningTimer.ms());
320
+ }
321
+ }
322
+ } catch (err) {
323
+ this.log.warn(`Error handling checkpoint proposal for slot ${proposal.slotNumber}`, {
324
+ err
325
+ });
326
+ }
327
+ return undefined;
328
+ };
329
+ p2pClient.registerAllNodesCheckpointProposalHandler(checkpointHandler);
172
330
  return this;
173
331
  }
174
332
  async handleBlockProposal(proposal, proposalSender, shouldReexecute) {
175
333
  const slotNumber = proposal.slotNumber;
176
334
  const proposer = proposal.getSender();
177
- const config = this.checkpointsBuilder.getConfig();
178
335
  // Reject proposals with invalid signatures
179
336
  if (!proposer) {
180
337
  this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
181
338
  return {
182
339
  isValid: false,
183
- reason: 'invalid_proposal'
340
+ reason: 'invalid_signature'
184
341
  };
185
342
  }
186
343
  const proposalInfo = {
@@ -203,23 +360,22 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
203
360
  reason: 'invalid_proposal'
204
361
  };
205
362
  }
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
- // When pipelining is enabled, the proposer builds ahead of L1 submission, so the
211
- // block source won't have synced to the proposed slot yet. Skip the sync wait to
212
- // avoid eating into the attestation window.
213
- if (!this.epochCache.isProposerPipeliningEnabled()) {
214
- const blockSourceSync = await this.waitForBlockSourceSync(slotNumber);
215
- if (!blockSourceSync) {
216
- this.log.warn(`Block source is not synced, skipping processing`, proposalInfo);
217
- return {
218
- isValid: false,
219
- reason: 'block_source_not_synced'
220
- };
221
- }
363
+ const retainedSlotValidation = await this.validateNewBlockInSlot(proposal);
364
+ if (!retainedSlotValidation.isValid) {
365
+ this.log.info(`Block proposal conflicts with retained proposals, skipping archiver processing`, {
366
+ ...proposalInfo,
367
+ indexWithinCheckpoint: proposal.indexWithinCheckpoint,
368
+ reason: retainedSlotValidation.reason
369
+ });
370
+ return {
371
+ isValid: false,
372
+ blockNumber: proposal.blockNumber,
373
+ reason: retainedSlotValidation.reason
374
+ };
222
375
  }
376
+ // The proposer builds ahead of L1 submission under pipelining, so the block source won't have
377
+ // synced to the proposed slot yet. We deliberately do not wait for it to sync here, to avoid
378
+ // eating into the attestation window.
223
379
  // Check that the parent proposal is a block we know, otherwise reexecution would fail.
224
380
  // If we don't find it immediately, we keep retrying for a while; it may be we still
225
381
  // need to process other block proposals to get to it.
@@ -246,8 +402,12 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
246
402
  // Compute the block number based on the parent block
247
403
  const blockNumber = parentBlock === 'genesis' ? BlockNumber(INITIAL_L2_BLOCK_NUM) : BlockNumber(parentBlock.header.getBlockNumber() + 1);
248
404
  proposalInfo.blockNumber = blockNumber;
249
- // Check that this block number does not exist already
250
- const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
405
+ // Check that this block number does not exist already. During a reorg the archiver can still hold a
406
+ // stale block at this number (a different archive, about to be pruned) while the proposal carries the
407
+ // rebuilt replacement; resolveExistingBlockAtNumber waits for the local prune in that case so the
408
+ // rebuilt block is processed in time to attest, rather than being permanently dropped on a bare
409
+ // number collision.
410
+ const existingBlock = await this.resolveExistingBlockAtNumber(blockNumber, proposal.archive, slotNumber);
251
411
  if (existingBlock) {
252
412
  this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
253
413
  return {
@@ -260,8 +420,10 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
260
420
  // and we do it even if we don't plan to re-execute the txs, so that we have them if another node needs them.
261
421
  const { txs, missingTxs } = await this.txProvider.getTxsForBlockProposal(proposal, blockNumber, {
262
422
  pinnedPeer: proposalSender,
263
- deadline: this.getReexecutionDeadline(slotNumber, config)
423
+ deadline: this.getReexecutionDeadline(slotNumber)
264
424
  });
425
+ // Record the tx-collection outcome on the re-execution tracker
426
+ this.reexecutionTracker.recordTxsCollected(slotNumber, proposal.indexWithinCheckpoint, missingTxs.length === 0);
265
427
  // If reexecution is disabled, bail. We were just interested in triggering tx collection.
266
428
  if (!shouldReexecute) {
267
429
  this.log.info(`Received valid block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, proposalInfo);
@@ -309,9 +471,18 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
309
471
  reason: 'txs_not_available'
310
472
  };
311
473
  }
312
- // Collect the out hashes of all the checkpoints before this one in the same epoch
474
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
475
+ // Mirror the proposer-side fallback: under pipelining the immediately-preceding cp may not
476
+ // yet be on L1, in which case the helper grafts the locally-known proposed cp's outHash.
313
477
  const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
314
- const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch)).filter((c)=>c.checkpointNumber < checkpointNumber).map((c)=>c.checkpointOutHash);
478
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
479
+ blockSource: this.blockSource,
480
+ epoch,
481
+ checkpointNumber,
482
+ l1Constants: this.epochCache.getL1Constants(),
483
+ pipeliningEnabled: true,
484
+ log: this.log
485
+ });
315
486
  // Try re-executing the transactions in the proposal if needed
316
487
  let reexecutionResult;
317
488
  try {
@@ -328,8 +499,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
328
499
  };
329
500
  }
330
501
  // If we succeeded, push this block into the archiver (unless disabled)
331
- if (reexecutionResult?.block && this.config.skipPushProposedBlocksToArchiver === false) {
332
- await this.blockSource.addBlock(reexecutionResult?.block);
502
+ if (reexecutionResult?.block && !this.config.skipPushProposedBlocksToArchiver) {
503
+ await this.blockSource.addBlock(reexecutionResult.block);
333
504
  }
334
505
  this.log.info(`Successfully re-executed block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, {
335
506
  ...proposalInfo,
@@ -341,19 +512,50 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
341
512
  reexecutionResult
342
513
  };
343
514
  }
515
+ async validateNewBlockInSlot(blockProposal) {
516
+ if (!this.p2pClient) {
517
+ return {
518
+ isValid: true
519
+ };
520
+ }
521
+ const { blockProposals, checkpointProposals } = await this.p2pClient.getProposalsForSlot(blockProposal.slotNumber);
522
+ if (checkpointProposals.length === 0) {
523
+ return {
524
+ isValid: true
525
+ };
526
+ } else if (checkpointProposals.length > 1) {
527
+ return {
528
+ isValid: false,
529
+ reason: 'checkpoint_proposal_equivocation'
530
+ };
531
+ } else {
532
+ const checkpointProposal = checkpointProposals[0];
533
+ const terminalBlock = blockProposals.find((block)=>block.archive.equals(checkpointProposal.archive));
534
+ return terminalBlock !== undefined && blockProposal.indexWithinCheckpoint > terminalBlock.indexWithinCheckpoint ? {
535
+ isValid: false,
536
+ reason: 'block_proposal_beyond_checkpoint'
537
+ } : {
538
+ isValid: true
539
+ };
540
+ }
541
+ }
344
542
  async getParentBlock(proposal) {
345
543
  const parentArchive = proposal.blockHeader.lastArchive.root;
346
- const slot = proposal.slotNumber;
347
- const config = this.checkpointsBuilder.getConfig();
348
544
  const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
349
545
  if (parentArchive.equals(genesisArchiveRoot)) {
350
546
  return 'genesis';
351
547
  }
352
- const deadline = this.getReexecutionDeadline(slot, config);
353
- const currentTime = this.dateProvider.now();
354
- const timeoutDurationMs = deadline.getTime() - currentTime;
548
+ const deadline = this.getReexecutionDeadline(proposal.slotNumber);
549
+ const timeoutDurationMs = deadline.getTime() - this.dateProvider.now();
355
550
  try {
356
- 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));
551
+ return await this.blockSource.getBlockData({
552
+ archive: parentArchive
553
+ }) ?? (timeoutDurationMs <= 0 ? undefined : await retryUntil(()=>this.blockSource.syncImmediate().then(()=>this.blockSource.getBlockData({
554
+ archive: parentArchive
555
+ })), 'force archiver sync', {
556
+ deadline,
557
+ dateProvider: this.dateProvider
558
+ }, 0.5));
357
559
  } catch (err) {
358
560
  if (err instanceof TimeoutError) {
359
561
  this.log.debug(`Timed out getting parent block by archive root`, {
@@ -367,6 +569,60 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
367
569
  return undefined;
368
570
  }
369
571
  }
572
+ /**
573
+ * Resolves whether a block genuinely already exists at `blockNumber`. Returns the existing block only if
574
+ * it is a true duplicate of the proposal (matching archive). During a reorg the archiver can still hold a
575
+ * stale fork at this number (different archive) that is about to be pruned; in that case this forces L1
576
+ * sync and waits, bounded by the re-execution deadline, for the prune to land, then returns `undefined` so
577
+ * the rebuilt block proposal can be processed in time to attest. If the prune does not complete before the
578
+ * deadline it returns the stale block, so the caller falls back to the safe `block_number_already_exists`
579
+ * rejection.
580
+ */ async resolveExistingBlockAtNumber(blockNumber, proposalArchive, slotNumber) {
581
+ const existingBlock = await this.blockSource.getBlockData({
582
+ number: blockNumber
583
+ });
584
+ if (!existingBlock || existingBlock.archive.root.equals(proposalArchive)) {
585
+ return existingBlock;
586
+ }
587
+ // A different block already occupies this number: it may be a stale fork being pruned during a reorg, not a
588
+ // genuine duplicate. Wait for the local prune rather than permanently rejecting the proposal.
589
+ const deadline = this.getReexecutionDeadline(slotNumber);
590
+ if (deadline.getTime() - this.dateProvider.now() <= 0) {
591
+ return existingBlock;
592
+ }
593
+ this.log.warn(`Block number ${blockNumber} already exists, awaiting potential prune`, {
594
+ blockNumber,
595
+ existingArchive: existingBlock.archive.root.toString(),
596
+ proposalArchive: proposalArchive.toString()
597
+ });
598
+ try {
599
+ const { block } = await retryUntil(async ()=>{
600
+ await this.blockSource.syncImmediate();
601
+ const block = await this.blockSource.getBlockData({
602
+ number: blockNumber
603
+ });
604
+ // Resolve once the existing block is gone (pruned) or has been replaced by one matching the
605
+ // proposal — the same condition as the early return above. A matching block is returned so the
606
+ // caller still treats it as a genuine duplicate; an `undefined` (pruned) block lets the proposal
607
+ // be processed. Wrap in an object so the `undefined` case is still a truthy retry result.
608
+ return block === undefined || block.archive.root.equals(proposalArchive) ? {
609
+ block
610
+ } : undefined;
611
+ }, `prune of stale block ${blockNumber}`, {
612
+ deadline,
613
+ dateProvider: this.dateProvider
614
+ }, 0.5);
615
+ return block;
616
+ } catch (err) {
617
+ if (err instanceof TimeoutError) {
618
+ this.log.warn(`Timed out waiting for stale block ${blockNumber} to be pruned`, {
619
+ blockNumber
620
+ });
621
+ return existingBlock;
622
+ }
623
+ throw err;
624
+ }
625
+ }
370
626
  computeCheckpointNumber(proposal, parentBlock, proposalInfo) {
371
627
  if (parentBlock === 'genesis') {
372
628
  // First block is in checkpoint 1
@@ -495,36 +751,13 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
495
751
  }
496
752
  return undefined;
497
753
  }
498
- getReexecutionDeadline(slot, config) {
499
- const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
500
- return new Date(nextSlotTimestampSeconds * 1000);
501
- }
502
- /** Waits for the block source to sync L1 data up to at least the slot before the given one. */ async waitForBlockSourceSync(slot) {
503
- const deadline = this.getReexecutionDeadline(slot, this.checkpointsBuilder.getConfig());
504
- const timeoutMs = deadline.getTime() - this.dateProvider.now();
505
- if (slot === 0) {
506
- return true;
507
- }
508
- // Make a quick check before triggering an archiver sync
509
- const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
510
- if (syncedSlot !== undefined && syncedSlot + 1 >= slot) {
511
- return true;
512
- }
513
- try {
514
- // Trigger an immediate sync of the block source, and wait until it reports being synced to the required slot
515
- return await retryUntil(async ()=>{
516
- await this.blockSource.syncImmediate();
517
- const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
518
- return syncedSlot !== undefined && syncedSlot + 1 >= slot;
519
- }, 'wait for block source sync', timeoutMs / 1000, 0.5);
520
- } catch (err) {
521
- if (err instanceof TimeoutError) {
522
- this.log.warn(`Timed out waiting for block source to sync to slot ${slot}`);
523
- return false;
524
- } else {
525
- throw err;
526
- }
527
- }
754
+ /**
755
+ * Hard re-execution/validation deadline for any block or checkpoint proposal targeting `slotNumber`:
756
+ * the single consensus `attestation_deadline` (`target_slot_start + S - 2E`). This is the latest the
757
+ * checkpoint can land on L1 in the target slot; all nodes agree on it. Loosened from the previous
758
+ * next-wall-clock-slot-boundary bound (see the timetable spec / refactor notes).
759
+ */ getReexecutionDeadline(slotNumber) {
760
+ return new Date(this.timetable.getAttestationDeadline(slotNumber) * 1000);
528
761
  }
529
762
  getReexecuteFailureReason(err) {
530
763
  if (err instanceof TransactionsNotAvailableError) {
@@ -552,7 +785,7 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
552
785
  // If we do not have all of the transactions, then we should fail
553
786
  if (txs.length !== txHashes.length) {
554
787
  const foundTxHashes = txs.map((tx)=>tx.getTxHash());
555
- const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.includes(txHash));
788
+ const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.some((h)=>h.equals(txHash)));
556
789
  throw new TransactionsNotAvailableError(missingTxHashes);
557
790
  }
558
791
  const timer = new Timer();
@@ -584,7 +817,7 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
584
817
  // Create checkpoint builder with prior blocks
585
818
  const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, 0n, l1ToL2Messages, previousCheckpointOutHashes, fork, priorBlocks, this.log.getBindings());
586
819
  // Build the new block
587
- const deadline = this.getReexecutionDeadline(slot, config);
820
+ const deadline = this.getReexecutionDeadline(slot);
588
821
  const maxBlockGas = this.config.validateMaxL2BlockGas !== undefined || this.config.validateMaxDABlockGas !== undefined ? new Gas(this.config.validateMaxDABlockGas ?? Infinity, this.config.validateMaxL2BlockGas ?? Infinity) : undefined;
589
822
  const result = await checkpointBuilder.buildBlock(txs, blockNumber, blockHeader.globalVariables.timestamp, {
590
823
  isBuildingProposal: false,
@@ -643,25 +876,53 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
643
876
  }
644
877
  }
645
878
  /**
646
- * Validates a checkpoint proposal and uploads blobs if configured.
647
- * Used by both non-validator nodes (via register) and the validator client (via delegation).
879
+ * Validates a checkpoint proposal, caches the result, and uploads blobs if configured.
880
+ * Returns a cached result if the same proposal (archive + slot) was already validated.
881
+ * Used by both the all-nodes callback (via register) and the validator client (via delegation).
648
882
  */ async handleCheckpointProposal(proposal, proposalInfo) {
883
+ const slot = proposal.slotNumber;
884
+ const payloadHash = proposal.getPayloadHash();
885
+ // Check cache: same signed-payload hash means we already validated this exact proposal.
886
+ if (this.lastCheckpointValidationResult && this.lastCheckpointValidationResult.payloadHash === payloadHash) {
887
+ this.log.debug(`Returning cached validation result for checkpoint proposal at slot ${slot}`, proposalInfo);
888
+ return this.lastCheckpointValidationResult.result;
889
+ }
649
890
  const proposer = proposal.getSender();
891
+ let result;
650
892
  if (!proposer) {
651
893
  this.log.warn(`Received checkpoint proposal with invalid signature for slot ${proposal.slotNumber}`);
652
- return {
894
+ result = {
653
895
  isValid: false,
654
896
  reason: 'invalid_signature'
655
897
  };
656
- }
657
- if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
898
+ } else if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
658
899
  this.log.warn(`Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${proposal.slotNumber}`);
659
- return {
900
+ result = {
660
901
  isValid: false,
661
902
  reason: 'invalid_fee_asset_price_modifier'
662
903
  };
904
+ } else {
905
+ result = await this.validateCheckpointProposal(proposal, proposalInfo);
906
+ }
907
+ this.lastCheckpointValidationResult = {
908
+ payloadHash,
909
+ result
910
+ };
911
+ // Record the outcome on the re-execution tracker.
912
+ const outcome = result.isValid ? 'valid' : CHECKPOINT_VALIDATION_REASON_TO_OUTCOME[result.reason];
913
+ if (outcome !== undefined) {
914
+ this.reexecutionTracker.recordOutcome(slot, proposal.archive, outcome, result.checkpointNumber);
915
+ }
916
+ // Drop tracker entries for checkpoints that have reached L1 finality.
917
+ try {
918
+ const tips = await this.blockSource.getL2Tips();
919
+ const finalizedCheckpointNumber = tips.finalized.checkpoint.number;
920
+ if (finalizedCheckpointNumber > 0) {
921
+ this.reexecutionTracker.removeBefore(CheckpointNumber(finalizedCheckpointNumber + 1));
922
+ }
923
+ } catch (err) {
924
+ this.log.error(`Error pruning reexecution tracker`, err, proposalInfo);
663
925
  }
664
- const result = await this.validateCheckpointProposal(proposal, proposalInfo);
665
926
  // Upload blobs to filestore if validation passed (fire and forget)
666
927
  if (result.isValid) {
667
928
  this.tryUploadBlobsForCheckpoint(proposal, proposalInfo);
@@ -672,73 +933,125 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
672
933
  * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
673
934
  * @returns Validation result with isValid flag and reason if invalid.
674
935
  */ async validateCheckpointProposal(proposal, proposalInfo) {
675
- const slot = proposal.slotNumber;
676
- // Timeout block syncing at the start of the next slot
677
- const config = this.checkpointsBuilder.getConfig();
678
- const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
679
- const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
680
- // Wait for last block to sync by archive
681
- let lastBlockHeader;
936
+ const env = {
937
+ stack: [],
938
+ error: void 0,
939
+ hasError: false
940
+ };
682
941
  try {
683
- lastBlockHeader = await retryUntil(async ()=>{
684
- await this.blockSource.syncImmediate();
685
- return this.blockSource.getBlockHeaderByArchive(proposal.archive);
686
- }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, timeoutSeconds, 0.5);
687
- } catch (err) {
688
- if (err instanceof TimeoutError) {
689
- this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
942
+ const slot = proposal.slotNumber;
943
+ // Block-sync/validation deadline = the single consensus attestation_deadline (target_slot_start + S
944
+ // - 2E): the latest moment the proposer can submit this checkpoint and still have it land on L1 in
945
+ // the target slot. Keeping validation/attestation alive until then lets validators keep attesting
946
+ // right up to the proposer's real publish cutoff.
947
+ const deadline = this.getReexecutionDeadline(slot);
948
+ // Wait for last block to sync by archive. The deadline is passed to retryUntil as an absolute date so
949
+ // the remaining budget is derived from the date provider; a deadline already in the past times out
950
+ // after a single attempt instead of looping (the immediate-timeout semantics of the deadline overload).
951
+ let lastBlockData;
952
+ try {
953
+ lastBlockData = await retryUntil(async ()=>{
954
+ await this.blockSource.syncImmediate();
955
+ return await this.blockSource.getBlockData({
956
+ archive: proposal.archive
957
+ });
958
+ }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, {
959
+ deadline,
960
+ dateProvider: this.dateProvider
961
+ }, 0.5);
962
+ } catch (err) {
963
+ if (err instanceof TimeoutError) {
964
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
965
+ return {
966
+ isValid: false,
967
+ reason: 'last_block_not_found'
968
+ };
969
+ }
970
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
971
+ return {
972
+ isValid: false,
973
+ reason: 'block_fetch_error'
974
+ };
975
+ }
976
+ if (!lastBlockData) {
977
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
690
978
  return {
691
979
  isValid: false,
692
980
  reason: 'last_block_not_found'
693
981
  };
694
982
  }
695
- this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
696
- return {
697
- isValid: false,
698
- reason: 'block_fetch_error'
699
- };
700
- }
701
- if (!lastBlockHeader) {
702
- this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
703
- return {
704
- isValid: false,
705
- reason: 'last_block_not_found'
706
- };
707
- }
708
- // Get all full blocks for the slot and checkpoint
709
- const blocks = await this.blockSource.getBlocksForSlot(slot);
710
- if (blocks.length === 0) {
711
- this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
712
- return {
713
- isValid: false,
714
- reason: 'no_blocks_for_slot'
715
- };
716
- }
717
- // Ensure the last block for this slot matches the archive in the checkpoint proposal
718
- if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
719
- this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
720
- return {
721
- isValid: false,
722
- reason: 'last_block_archive_mismatch'
723
- };
724
- }
725
- this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
726
- ...proposalInfo,
727
- blockNumbers: blocks.map((b)=>b.number)
728
- });
729
- // Get checkpoint constants from first block
730
- const firstBlock = blocks[0];
731
- const constants = this.extractCheckpointConstants(firstBlock);
732
- const checkpointNumber = firstBlock.checkpointNumber;
733
- // Get L1-to-L2 messages for this checkpoint
734
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
735
- // Collect the out hashes of all the checkpoints before this one in the same epoch
736
- const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
737
- const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch)).filter((c)=>c.checkpointNumber < checkpointNumber).map((c)=>c.checkpointOutHash);
738
- // Fork world state at the block before the first block
739
- const parentBlockNumber = BlockNumber(firstBlock.number - 1);
740
- const fork = await this.worldState.fork(parentBlockNumber);
741
- try {
983
+ // Refuse to attest if the block's enclosing checkpoint has already been published to L1.
984
+ const existingCheckpoint = await this.blockSource.getCheckpointData({
985
+ number: lastBlockData.checkpointNumber
986
+ });
987
+ if (existingCheckpoint) {
988
+ this.log.warn(`Refusing to attest to checkpoint proposal whose checkpoint is already on L1`, {
989
+ ...proposalInfo,
990
+ checkpointNumber: lastBlockData.checkpointNumber
991
+ });
992
+ return {
993
+ isValid: false,
994
+ reason: 'checkpoint_already_published',
995
+ checkpointNumber: lastBlockData.checkpointNumber
996
+ };
997
+ }
998
+ // Get all full blocks for the slot and checkpoint
999
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
1000
+ if (blocks.length === 0) {
1001
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
1002
+ return {
1003
+ isValid: false,
1004
+ reason: 'no_blocks_for_slot',
1005
+ checkpointNumber: lastBlockData.checkpointNumber
1006
+ };
1007
+ }
1008
+ // Ensure the last block for this slot matches the archive in the checkpoint proposal
1009
+ if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
1010
+ this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
1011
+ return {
1012
+ isValid: false,
1013
+ reason: 'last_block_archive_mismatch',
1014
+ checkpointNumber: lastBlockData.checkpointNumber
1015
+ };
1016
+ }
1017
+ // Note this condition should never trigger, since we dont process block proposals that exceed indexWithinCheckpoint
1018
+ const maxBlocksPerCheckpoint = this.config.maxBlocksPerCheckpoint;
1019
+ if (maxBlocksPerCheckpoint !== undefined && blocks.length > maxBlocksPerCheckpoint) {
1020
+ this.log.warn(`Checkpoint proposal exceeds maxBlocksPerCheckpoint`, {
1021
+ ...proposalInfo,
1022
+ blocksInProposal: blocks.length,
1023
+ maxBlocksPerCheckpoint
1024
+ });
1025
+ return {
1026
+ isValid: false,
1027
+ reason: 'too_many_blocks_in_checkpoint',
1028
+ checkpointNumber: lastBlockData.checkpointNumber
1029
+ };
1030
+ }
1031
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
1032
+ ...proposalInfo,
1033
+ blockNumbers: blocks.map((b)=>b.number)
1034
+ });
1035
+ // Get checkpoint constants from first block
1036
+ const firstBlock = blocks[0];
1037
+ const constants = this.extractCheckpointConstants(firstBlock);
1038
+ const checkpointNumber = firstBlock.checkpointNumber;
1039
+ // Get L1-to-L2 messages for this checkpoint
1040
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
1041
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
1042
+ // See note on the analogous block-proposal site: the helper handles pipelining lag.
1043
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
1044
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
1045
+ blockSource: this.blockSource,
1046
+ epoch,
1047
+ checkpointNumber,
1048
+ l1Constants: this.epochCache.getL1Constants(),
1049
+ pipeliningEnabled: true,
1050
+ log: this.log
1051
+ });
1052
+ // Fork world state at the block before the first block
1053
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
1054
+ const fork = _ts_add_disposable_resource(env, await this.checkpointsBuilder.getFork(parentBlockNumber), true);
742
1055
  // Create checkpoint builder with all existing blocks
743
1056
  const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, proposal.feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, blocks, this.log.getBindings());
744
1057
  // Complete the checkpoint to get computed values
@@ -752,7 +1065,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
752
1065
  });
753
1066
  return {
754
1067
  isValid: false,
755
- reason: 'checkpoint_header_mismatch'
1068
+ reason: 'checkpoint_header_mismatch',
1069
+ checkpointNumber
756
1070
  };
757
1071
  }
758
1072
  // Compare archive root with proposal
@@ -764,7 +1078,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
764
1078
  });
765
1079
  return {
766
1080
  isValid: false,
767
- reason: 'archive_mismatch'
1081
+ reason: 'archive_mismatch',
1082
+ checkpointNumber
768
1083
  };
769
1084
  }
770
1085
  // Check that the accumulated epoch out hash matches the value in the proposal.
@@ -785,7 +1100,8 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
785
1100
  });
786
1101
  return {
787
1102
  isValid: false,
788
- reason: 'out_hash_mismatch'
1103
+ reason: 'out_hash_mismatch',
1104
+ checkpointNumber
789
1105
  };
790
1106
  }
791
1107
  // Final round of validations on the checkpoint, just in case.
@@ -801,15 +1117,21 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
801
1117
  this.log.warn(`Checkpoint validation failed: ${err}`, proposalInfo);
802
1118
  return {
803
1119
  isValid: false,
804
- reason: 'checkpoint_validation_failed'
1120
+ reason: 'checkpoint_validation_failed',
1121
+ checkpointNumber
805
1122
  };
806
1123
  }
807
1124
  this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
808
1125
  return {
809
- isValid: true
1126
+ isValid: true,
1127
+ checkpointNumber
810
1128
  };
1129
+ } catch (e) {
1130
+ env.error = e;
1131
+ env.hasError = true;
811
1132
  } finally{
812
- await fork.close();
1133
+ const result = _ts_dispose_resources(env);
1134
+ if (result) await result;
813
1135
  }
814
1136
  }
815
1137
  /** Extracts checkpoint global variables from a block. */ extractCheckpointConstants(block) {
@@ -831,7 +1153,9 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
831
1153
  }
832
1154
  /** Uploads blobs for a checkpoint to the filestore. */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
833
1155
  try {
834
- const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
1156
+ const lastBlockHeader = (await this.blockSource.getBlockData({
1157
+ archive: proposal.archive
1158
+ }))?.header;
835
1159
  if (!lastBlockHeader) {
836
1160
  this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
837
1161
  return;
@@ -853,4 +1177,31 @@ import { getTelemetryClient } from '@aztec/telemetry-client';
853
1177
  this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
854
1178
  }
855
1179
  }
1180
+ /**
1181
+ * Derives proposed checkpoint data from validated blocks and sets it on the archiver, so this node can
1182
+ * pipeline building on top of the checkpoint. Does not retry, since validation already waited for the
1183
+ * last block to sync.
1184
+ */ async setProposedCheckpoint(proposal) {
1185
+ if (!this.archiver) {
1186
+ return false;
1187
+ }
1188
+ const blockData = await this.blockSource.getBlockData({
1189
+ archive: proposal.archive
1190
+ });
1191
+ if (!blockData) {
1192
+ this.log.debug(`Block data not found for checkpoint proposal archive, cannot set proposed checkpoint`, {
1193
+ archive: proposal.archive.toString()
1194
+ });
1195
+ return false;
1196
+ }
1197
+ await this.archiver.addProposedCheckpoint({
1198
+ header: proposal.checkpointHeader,
1199
+ checkpointNumber: blockData.checkpointNumber,
1200
+ startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
1201
+ blockCount: blockData.indexWithinCheckpoint + 1,
1202
+ totalManaUsed: proposal.checkpointHeader.totalManaUsed.toBigInt(),
1203
+ feeAssetPriceModifier: proposal.feeAssetPriceModifier
1204
+ });
1205
+ return true;
1206
+ }
856
1207
  }