@aztec/validator-client 0.0.1-commit.e3c1de76 → 0.0.1-commit.e588bc7e5

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.
Files changed (54) hide show
  1. package/README.md +60 -18
  2. package/dest/checkpoint_builder.d.ts +21 -8
  3. package/dest/checkpoint_builder.d.ts.map +1 -1
  4. package/dest/checkpoint_builder.js +124 -46
  5. package/dest/config.d.ts +1 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +26 -6
  8. package/dest/duties/validation_service.d.ts +2 -2
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +6 -12
  11. package/dest/factory.d.ts +7 -4
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +6 -5
  14. package/dest/index.d.ts +2 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +1 -2
  17. package/dest/key_store/ha_key_store.d.ts +1 -1
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -1
  19. package/dest/key_store/ha_key_store.js +3 -3
  20. package/dest/metrics.d.ts +10 -2
  21. package/dest/metrics.d.ts.map +1 -1
  22. package/dest/metrics.js +12 -0
  23. package/dest/proposal_handler.d.ts +107 -0
  24. package/dest/proposal_handler.d.ts.map +1 -0
  25. package/dest/proposal_handler.js +963 -0
  26. package/dest/validator.d.ts +39 -17
  27. package/dest/validator.d.ts.map +1 -1
  28. package/dest/validator.js +181 -191
  29. package/package.json +19 -19
  30. package/src/checkpoint_builder.ts +142 -39
  31. package/src/config.ts +26 -6
  32. package/src/duties/validation_service.ts +12 -11
  33. package/src/factory.ts +9 -3
  34. package/src/index.ts +1 -2
  35. package/src/key_store/ha_key_store.ts +3 -3
  36. package/src/metrics.ts +19 -1
  37. package/src/proposal_handler.ts +1027 -0
  38. package/src/validator.ts +243 -212
  39. package/dest/block_proposal_handler.d.ts +0 -63
  40. package/dest/block_proposal_handler.d.ts.map +0 -1
  41. package/dest/block_proposal_handler.js +0 -546
  42. package/dest/tx_validator/index.d.ts +0 -3
  43. package/dest/tx_validator/index.d.ts.map +0 -1
  44. package/dest/tx_validator/index.js +0 -2
  45. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  46. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  47. package/dest/tx_validator/nullifier_cache.js +0 -24
  48. package/dest/tx_validator/tx_validator_factory.d.ts +0 -19
  49. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  50. package/dest/tx_validator/tx_validator_factory.js +0 -54
  51. package/src/block_proposal_handler.ts +0 -555
  52. package/src/tx_validator/index.ts +0 -2
  53. package/src/tx_validator/nullifier_cache.ts +0 -30
  54. package/src/tx_validator/tx_validator_factory.ts +0 -154
@@ -0,0 +1,1027 @@
1
+ import type { Archiver } from '@aztec/archiver';
2
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
3
+ import { type Blob, encodeCheckpointBlobDataFromBlocks, getBlobsPerL1Block } from '@aztec/blob-lib';
4
+ import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
5
+ import type { EpochCache } from '@aztec/epoch-cache';
6
+ import { validateFeeAssetPriceModifier } from '@aztec/ethereum/contracts';
7
+ import { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
8
+ import { pick } from '@aztec/foundation/collection';
9
+ import { Fr } from '@aztec/foundation/curves/bn254';
10
+ import { TimeoutError } from '@aztec/foundation/error';
11
+ import type { LogData } from '@aztec/foundation/log';
12
+ import { createLogger } from '@aztec/foundation/log';
13
+ import { retryUntil } from '@aztec/foundation/retry';
14
+ import { DateProvider, Timer } from '@aztec/foundation/timer';
15
+ import type { P2P, PeerId } from '@aztec/p2p';
16
+ import { BlockProposalValidator } from '@aztec/p2p/msg_validators';
17
+ import type { BlockData, L2Block, L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
18
+ import { validateCheckpoint } from '@aztec/stdlib/checkpoint';
19
+ import { getEpochAtSlot, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
20
+ import { Gas } from '@aztec/stdlib/gas';
21
+ import type { ITxProvider, ValidatorClientFullConfig, WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
22
+ import {
23
+ type L1ToL2MessageSource,
24
+ accumulateCheckpointOutHashes,
25
+ computeInHashFromL1ToL2Messages,
26
+ } from '@aztec/stdlib/messaging';
27
+ import type { BlockProposal, CheckpointAttestation, CheckpointProposalCore } from '@aztec/stdlib/p2p';
28
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
29
+ import type { CheckpointGlobalVariables, FailedTx, Tx } from '@aztec/stdlib/tx';
30
+ import {
31
+ ReExFailedTxsError,
32
+ ReExInitialStateMismatchError,
33
+ ReExStateMismatchError,
34
+ ReExTimeoutError,
35
+ TransactionsNotAvailableError,
36
+ } from '@aztec/stdlib/validators';
37
+ import { type TelemetryClient, type Tracer, getTelemetryClient } from '@aztec/telemetry-client';
38
+
39
+ import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
40
+ import type { ValidatorMetrics } from './metrics.js';
41
+
42
+ export type BlockProposalValidationFailureReason =
43
+ | 'invalid_proposal'
44
+ | 'parent_block_not_found'
45
+ | 'block_source_not_synced'
46
+ | 'parent_block_wrong_slot'
47
+ | 'in_hash_mismatch'
48
+ | 'global_variables_mismatch'
49
+ | 'block_number_already_exists'
50
+ | 'txs_not_available'
51
+ | 'state_mismatch'
52
+ | 'failed_txs'
53
+ | 'initial_state_mismatch'
54
+ | 'timeout'
55
+ | 'unknown_error';
56
+
57
+ type ReexecuteTransactionsResult = {
58
+ block: L2Block;
59
+ failedTxs: FailedTx[];
60
+ reexecutionTimeMs: number;
61
+ totalManaUsed: number;
62
+ };
63
+
64
+ export type BlockProposalValidationSuccessResult = {
65
+ isValid: true;
66
+ blockNumber: BlockNumber;
67
+ reexecutionResult?: ReexecuteTransactionsResult;
68
+ };
69
+
70
+ export type BlockProposalValidationFailureResult = {
71
+ isValid: false;
72
+ reason: BlockProposalValidationFailureReason;
73
+ blockNumber?: BlockNumber;
74
+ reexecutionResult?: ReexecuteTransactionsResult;
75
+ };
76
+
77
+ export type BlockProposalValidationResult = BlockProposalValidationSuccessResult | BlockProposalValidationFailureResult;
78
+
79
+ export type CheckpointProposalValidationResult = { isValid: true } | { isValid: false; reason: string };
80
+
81
+ type CheckpointComputationResult =
82
+ | { checkpointNumber: CheckpointNumber; reason?: undefined }
83
+ | { checkpointNumber?: undefined; reason: 'invalid_proposal' | 'global_variables_mismatch' };
84
+
85
+ /** Handles block and checkpoint proposals for both validator and non-validator nodes. */
86
+ export class ProposalHandler {
87
+ public readonly tracer: Tracer;
88
+
89
+ /** Cached last checkpoint validation result to avoid double-validation on validator nodes. */
90
+ private lastCheckpointValidationResult?: {
91
+ archive: Fr;
92
+ slotNumber: SlotNumber;
93
+ result: CheckpointProposalValidationResult;
94
+ };
95
+
96
+ /** Archiver reference for setting proposed checkpoints (pipelining). Set via register(). */
97
+ private archiver?: Pick<Archiver, 'setProposedCheckpoint' | 'getL1Constants'>;
98
+
99
+ /** Returns current validator addresses for own-proposal detection. Set via register(). */
100
+ private getOwnValidatorAddresses?: () => string[];
101
+
102
+ constructor(
103
+ private checkpointsBuilder: FullNodeCheckpointsBuilder,
104
+ private worldState: WorldStateSynchronizer,
105
+ private blockSource: L2BlockSource & L2BlockSink,
106
+ private l1ToL2MessageSource: L1ToL2MessageSource,
107
+ private txProvider: ITxProvider,
108
+ private blockProposalValidator: BlockProposalValidator,
109
+ private epochCache: EpochCache,
110
+ private config: ValidatorClientFullConfig,
111
+ private blobClient: BlobClientInterface,
112
+ private metrics?: ValidatorMetrics,
113
+ private dateProvider: DateProvider = new DateProvider(),
114
+ telemetry: TelemetryClient = getTelemetryClient(),
115
+ private log = createLogger('validator:proposal-handler'),
116
+ ) {
117
+ if (config.fishermanMode) {
118
+ this.log = this.log.createChild('[FISHERMAN]');
119
+ }
120
+ this.tracer = telemetry.getTracer('ProposalHandler');
121
+ }
122
+
123
+ /**
124
+ * Registers handlers for block and checkpoint proposals on the p2p client.
125
+ * Block proposals are registered for non-validator nodes (validators register their own enhanced handler).
126
+ * The all-nodes checkpoint proposal handler is always registered for validation, caching, and pipelining.
127
+ * @param archiver - Archiver reference for setting proposed checkpoints (pipelining)
128
+ * @param getOwnValidatorAddresses - Returns current validator addresses for own-proposal detection
129
+ */
130
+ register(
131
+ p2pClient: P2P,
132
+ shouldReexecute: boolean,
133
+ archiver?: Pick<Archiver, 'setProposedCheckpoint' | 'getL1Constants'>,
134
+ getOwnValidatorAddresses?: () => string[],
135
+ ): ProposalHandler {
136
+ this.archiver = archiver;
137
+ this.getOwnValidatorAddresses = getOwnValidatorAddresses;
138
+
139
+ // Non-validator handler that processes or re-executes for monitoring but does not attest.
140
+ // Returns boolean indicating whether the proposal was valid.
141
+ const blockHandler = async (proposal: BlockProposal, proposalSender: PeerId): Promise<boolean> => {
142
+ try {
143
+ const { slotNumber, blockNumber } = proposal;
144
+ const result = await this.handleBlockProposal(proposal, proposalSender, shouldReexecute);
145
+ if (result.isValid) {
146
+ this.log.info(`Non-validator block proposal ${blockNumber} at slot ${slotNumber} handled`, {
147
+ blockNumber: result.blockNumber,
148
+ slotNumber,
149
+ reexecutionTimeMs: result.reexecutionResult?.reexecutionTimeMs,
150
+ totalManaUsed: result.reexecutionResult?.totalManaUsed,
151
+ numTxs: result.reexecutionResult?.block?.body?.txEffects?.length ?? 0,
152
+ reexecuted: shouldReexecute,
153
+ });
154
+ return true;
155
+ } else {
156
+ this.log.warn(
157
+ `Non-validator block proposal ${blockNumber} at slot ${slotNumber} failed processing with ${result.reason}`,
158
+ { blockNumber: result.blockNumber, slotNumber, reason: result.reason },
159
+ );
160
+ return false;
161
+ }
162
+ } catch (error) {
163
+ this.log.error('Error processing block proposal in non-validator handler', error);
164
+ return false;
165
+ }
166
+ };
167
+
168
+ p2pClient.registerBlockProposalHandler(blockHandler);
169
+
170
+ // All-nodes checkpoint proposal handler: validates, caches, and sets proposed checkpoint for pipelining.
171
+ // Runs for all nodes (validators and non-validators). Validators get the cached result in the
172
+ // validator-specific callback (attestToCheckpointProposal) which runs after this one.
173
+ const checkpointHandler = async (
174
+ proposal: CheckpointProposalCore,
175
+ _sender: PeerId,
176
+ ): Promise<CheckpointAttestation[] | undefined> => {
177
+ try {
178
+ const proposalInfo: LogData = {
179
+ slot: proposal.slotNumber,
180
+ archive: proposal.archive.toString(),
181
+ proposer: proposal.getSender()?.toString(),
182
+ };
183
+
184
+ // For own proposals, skip validation — the proposer already built and validated the checkpoint
185
+ const proposer = proposal.getSender();
186
+ const ownAddresses = this.getOwnValidatorAddresses?.();
187
+ const isOwnProposal = proposer && ownAddresses?.some(addr => addr === proposer.toString());
188
+
189
+ if (isOwnProposal) {
190
+ this.log.debug(`Skipping validation for own checkpoint proposal at slot ${proposal.slotNumber}`);
191
+ if (this.archiver && this.epochCache.isProposerPipeliningEnabled()) {
192
+ await this.setProposedCheckpointFromBlocks(proposal);
193
+ }
194
+ return undefined;
195
+ }
196
+
197
+ const result = await this.handleCheckpointProposal(proposal, proposalInfo);
198
+ if (result.isValid && this.archiver && this.epochCache.isProposerPipeliningEnabled()) {
199
+ await this.setProposedCheckpointFromValidation(proposal);
200
+ }
201
+ } catch (err) {
202
+ this.log.warn(`Error handling checkpoint proposal for slot ${proposal.slotNumber}`, { err });
203
+ }
204
+ return undefined;
205
+ };
206
+
207
+ p2pClient.registerAllNodesCheckpointProposalHandler(checkpointHandler);
208
+
209
+ return this;
210
+ }
211
+
212
+ async handleBlockProposal(
213
+ proposal: BlockProposal,
214
+ proposalSender: PeerId,
215
+ shouldReexecute: boolean,
216
+ ): Promise<BlockProposalValidationResult> {
217
+ const slotNumber = proposal.slotNumber;
218
+ const proposer = proposal.getSender();
219
+ const config = this.checkpointsBuilder.getConfig();
220
+
221
+ // Reject proposals with invalid signatures
222
+ if (!proposer) {
223
+ this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
224
+ return { isValid: false, reason: 'invalid_proposal' };
225
+ }
226
+
227
+ const proposalInfo = {
228
+ ...proposal.toBlockInfo(),
229
+ proposer: proposer.toString(),
230
+ blockNumber: undefined as BlockNumber | undefined,
231
+ checkpointNumber: undefined as CheckpointNumber | undefined,
232
+ };
233
+
234
+ this.log.info(`Processing proposal for slot ${slotNumber}`, {
235
+ ...proposalInfo,
236
+ txHashes: proposal.txHashes.map(t => t.toString()),
237
+ });
238
+
239
+ // Check that the proposal is from the current proposer, or the next proposer
240
+ // This should have been handled by the p2p layer, but we double check here out of caution
241
+ const validationResult = await this.blockProposalValidator.validate(proposal);
242
+ if (validationResult.result !== 'accept') {
243
+ this.log.warn(`Proposal is not valid, skipping processing`, proposalInfo);
244
+ return { isValid: false, reason: 'invalid_proposal' };
245
+ }
246
+
247
+ // Ensure the block source is synced before checking for existing blocks,
248
+ // since a proposed checkpoint prune may remove blocks we'd otherwise find.
249
+ // This affects mostly the block_number_already_exists check, since a pending
250
+ // checkpoint prune could remove a block that would conflict with this proposal.
251
+ // When pipelining is enabled, the proposer builds ahead of L1 submission, so the
252
+ // block source won't have synced to the proposed slot yet. Skip the sync wait to
253
+ // avoid eating into the attestation window.
254
+ if (!this.epochCache.isProposerPipeliningEnabled()) {
255
+ const blockSourceSync = await this.waitForBlockSourceSync(slotNumber);
256
+ if (!blockSourceSync) {
257
+ this.log.warn(`Block source is not synced, skipping processing`, proposalInfo);
258
+ return { isValid: false, reason: 'block_source_not_synced' };
259
+ }
260
+ }
261
+
262
+ // Check that the parent proposal is a block we know, otherwise reexecution would fail.
263
+ // If we don't find it immediately, we keep retrying for a while; it may be we still
264
+ // need to process other block proposals to get to it.
265
+ const parentBlock = await this.getParentBlock(proposal);
266
+ if (parentBlock === undefined) {
267
+ this.log.warn(`Parent block for proposal not found, skipping processing`, proposalInfo);
268
+ return { isValid: false, reason: 'parent_block_not_found' };
269
+ }
270
+
271
+ // Check that the parent block's slot is not greater than the proposal's slot.
272
+ if (parentBlock !== 'genesis' && parentBlock.header.getSlot() > slotNumber) {
273
+ this.log.warn(`Parent block slot is greater than proposal slot, skipping processing`, {
274
+ parentBlockSlot: parentBlock.header.getSlot().toString(),
275
+ proposalSlot: slotNumber.toString(),
276
+ ...proposalInfo,
277
+ });
278
+ return { isValid: false, reason: 'parent_block_wrong_slot' };
279
+ }
280
+
281
+ // Compute the block number based on the parent block
282
+ const blockNumber =
283
+ parentBlock === 'genesis'
284
+ ? BlockNumber(INITIAL_L2_BLOCK_NUM)
285
+ : BlockNumber(parentBlock.header.getBlockNumber() + 1);
286
+ proposalInfo.blockNumber = blockNumber;
287
+
288
+ // Check that this block number does not exist already
289
+ const existingBlock = await this.blockSource.getBlockHeader(blockNumber);
290
+ if (existingBlock) {
291
+ this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
292
+ return { isValid: false, blockNumber, reason: 'block_number_already_exists' };
293
+ }
294
+
295
+ // Collect txs from the proposal. We start doing this as early as possible,
296
+ // 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.
297
+ const { txs, missingTxs } = await this.txProvider.getTxsForBlockProposal(proposal, blockNumber, {
298
+ pinnedPeer: proposalSender,
299
+ deadline: this.getReexecutionDeadline(slotNumber, config),
300
+ });
301
+
302
+ // If reexecution is disabled, bail. We were just interested in triggering tx collection.
303
+ if (!shouldReexecute) {
304
+ this.log.info(
305
+ `Received valid block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`,
306
+ proposalInfo,
307
+ );
308
+ return { isValid: true, blockNumber };
309
+ }
310
+
311
+ // Compute the checkpoint number for this block and validate checkpoint consistency
312
+ const checkpointResult = this.computeCheckpointNumber(proposal, parentBlock, proposalInfo);
313
+ if (checkpointResult.reason) {
314
+ return { isValid: false, blockNumber, reason: checkpointResult.reason };
315
+ }
316
+ const checkpointNumber = checkpointResult.checkpointNumber;
317
+ proposalInfo.checkpointNumber = checkpointNumber;
318
+
319
+ // Check that I have the same set of l1ToL2Messages as the proposal
320
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
321
+ const computedInHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
322
+ const proposalInHash = proposal.inHash;
323
+ if (!computedInHash.equals(proposalInHash)) {
324
+ this.log.warn(`L1 to L2 messages in hash mismatch, skipping processing`, {
325
+ proposalInHash: proposalInHash.toString(),
326
+ computedInHash: computedInHash.toString(),
327
+ ...proposalInfo,
328
+ });
329
+ return { isValid: false, blockNumber, reason: 'in_hash_mismatch' };
330
+ }
331
+
332
+ // Check that all of the transactions in the proposal are available
333
+ if (missingTxs.length > 0) {
334
+ this.log.warn(`Missing ${missingTxs.length} txs to process proposal`, { ...proposalInfo, missingTxs });
335
+ return { isValid: false, blockNumber, reason: 'txs_not_available' };
336
+ }
337
+
338
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
339
+ const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
340
+ const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch))
341
+ .filter(c => c.checkpointNumber < checkpointNumber)
342
+ .map(c => c.checkpointOutHash);
343
+
344
+ // Try re-executing the transactions in the proposal if needed
345
+ let reexecutionResult;
346
+ try {
347
+ this.log.verbose(`Re-executing transactions in the proposal`, proposalInfo);
348
+ reexecutionResult = await this.reexecuteTransactions(
349
+ proposal,
350
+ blockNumber,
351
+ checkpointNumber,
352
+ txs,
353
+ l1ToL2Messages,
354
+ previousCheckpointOutHashes,
355
+ );
356
+ } catch (error) {
357
+ this.log.error(`Error reexecuting txs while processing block proposal`, error, proposalInfo);
358
+ const reason = this.getReexecuteFailureReason(error);
359
+ return { isValid: false, blockNumber, reason, reexecutionResult };
360
+ }
361
+
362
+ // If we succeeded, push this block into the archiver (unless disabled)
363
+ if (reexecutionResult?.block && this.config.skipPushProposedBlocksToArchiver === false) {
364
+ await this.blockSource.addBlock(reexecutionResult.block);
365
+ }
366
+
367
+ this.log.info(
368
+ `Successfully re-executed block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`,
369
+ { ...proposalInfo, ...pick(reexecutionResult, 'reexecutionTimeMs', 'totalManaUsed') },
370
+ );
371
+
372
+ return { isValid: true, blockNumber, reexecutionResult };
373
+ }
374
+
375
+ private async getParentBlock(proposal: BlockProposal): Promise<'genesis' | BlockData | undefined> {
376
+ const parentArchive = proposal.blockHeader.lastArchive.root;
377
+ const slot = proposal.slotNumber;
378
+ const config = this.checkpointsBuilder.getConfig();
379
+ const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
380
+
381
+ if (parentArchive.equals(genesisArchiveRoot)) {
382
+ return 'genesis';
383
+ }
384
+
385
+ const deadline = this.getReexecutionDeadline(slot, config);
386
+ const currentTime = this.dateProvider.now();
387
+ const timeoutDurationMs = deadline.getTime() - currentTime;
388
+
389
+ try {
390
+ return (
391
+ (await this.blockSource.getBlockDataByArchive(parentArchive)) ??
392
+ (timeoutDurationMs <= 0
393
+ ? undefined
394
+ : await retryUntil(
395
+ () => this.blockSource.syncImmediate().then(() => this.blockSource.getBlockDataByArchive(parentArchive)),
396
+ 'force archiver sync',
397
+ timeoutDurationMs / 1000,
398
+ 0.5,
399
+ ))
400
+ );
401
+ } catch (err) {
402
+ if (err instanceof TimeoutError) {
403
+ this.log.debug(`Timed out getting parent block by archive root`, { parentArchive });
404
+ } else {
405
+ this.log.error('Error getting parent block by archive root', err, { parentArchive });
406
+ }
407
+ return undefined;
408
+ }
409
+ }
410
+
411
+ private computeCheckpointNumber(
412
+ proposal: BlockProposal,
413
+ parentBlock: 'genesis' | BlockData,
414
+ proposalInfo: object,
415
+ ): CheckpointComputationResult {
416
+ if (parentBlock === 'genesis') {
417
+ // First block is in checkpoint 1
418
+ if (proposal.indexWithinCheckpoint !== 0) {
419
+ this.log.warn(`First block proposal has non-zero indexWithinCheckpoint`, proposalInfo);
420
+ return { reason: 'invalid_proposal' };
421
+ }
422
+ return { checkpointNumber: CheckpointNumber.INITIAL };
423
+ }
424
+
425
+ if (proposal.indexWithinCheckpoint === 0) {
426
+ // If this is the first block in a new checkpoint, increment the checkpoint number
427
+ if (!(proposal.blockHeader.getSlot() > parentBlock.header.getSlot())) {
428
+ this.log.warn(`Slot should be greater than parent block slot for first block in checkpoint`, proposalInfo);
429
+ return { reason: 'invalid_proposal' };
430
+ }
431
+ return { checkpointNumber: CheckpointNumber(parentBlock.checkpointNumber + 1) };
432
+ }
433
+
434
+ // Otherwise it should follow the previous block in the same checkpoint
435
+ if (proposal.indexWithinCheckpoint !== parentBlock.indexWithinCheckpoint + 1) {
436
+ this.log.warn(`Non-sequential indexWithinCheckpoint`, proposalInfo);
437
+ return { reason: 'invalid_proposal' };
438
+ }
439
+ if (proposal.blockHeader.getSlot() !== parentBlock.header.getSlot()) {
440
+ this.log.warn(`Slot should be equal to parent block slot for non-first block in checkpoint`, proposalInfo);
441
+ return { reason: 'invalid_proposal' };
442
+ }
443
+
444
+ // For non-first blocks in a checkpoint, validate global variables match parent (except blockNumber)
445
+ const validationResult = this.validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo);
446
+ if (validationResult) {
447
+ return validationResult;
448
+ }
449
+
450
+ return { checkpointNumber: parentBlock.checkpointNumber };
451
+ }
452
+
453
+ /**
454
+ * Validates that a non-first block in a checkpoint has consistent global variables with its parent.
455
+ * For blocks with indexWithinCheckpoint > 0, all global variables except blockNumber must match the parent.
456
+ * @returns A failure result if validation fails, undefined if validation passes
457
+ */
458
+ private validateNonFirstBlockInCheckpoint(
459
+ proposal: BlockProposal,
460
+ parentBlock: BlockData,
461
+ proposalInfo: object,
462
+ ): CheckpointComputationResult | undefined {
463
+ const proposalGlobals = proposal.blockHeader.globalVariables;
464
+ const parentGlobals = parentBlock.header.globalVariables;
465
+
466
+ // All global variables except blockNumber should match the parent
467
+ // blockNumber naturally increments between blocks
468
+ if (!proposalGlobals.chainId.equals(parentGlobals.chainId)) {
469
+ this.log.warn(`Non-first block in checkpoint has mismatched chainId`, {
470
+ ...proposalInfo,
471
+ proposalChainId: proposalGlobals.chainId.toString(),
472
+ parentChainId: parentGlobals.chainId.toString(),
473
+ });
474
+ return { reason: 'global_variables_mismatch' };
475
+ }
476
+
477
+ if (!proposalGlobals.version.equals(parentGlobals.version)) {
478
+ this.log.warn(`Non-first block in checkpoint has mismatched version`, {
479
+ ...proposalInfo,
480
+ proposalVersion: proposalGlobals.version.toString(),
481
+ parentVersion: parentGlobals.version.toString(),
482
+ });
483
+ return { reason: 'global_variables_mismatch' };
484
+ }
485
+
486
+ if (proposalGlobals.slotNumber !== parentGlobals.slotNumber) {
487
+ this.log.warn(`Non-first block in checkpoint has mismatched slotNumber`, {
488
+ ...proposalInfo,
489
+ proposalSlotNumber: proposalGlobals.slotNumber,
490
+ parentSlotNumber: parentGlobals.slotNumber,
491
+ });
492
+ return { reason: 'global_variables_mismatch' };
493
+ }
494
+
495
+ if (proposalGlobals.timestamp !== parentGlobals.timestamp) {
496
+ this.log.warn(`Non-first block in checkpoint has mismatched timestamp`, {
497
+ ...proposalInfo,
498
+ proposalTimestamp: proposalGlobals.timestamp.toString(),
499
+ parentTimestamp: parentGlobals.timestamp.toString(),
500
+ });
501
+ return { reason: 'global_variables_mismatch' };
502
+ }
503
+
504
+ if (!proposalGlobals.coinbase.equals(parentGlobals.coinbase)) {
505
+ this.log.warn(`Non-first block in checkpoint has mismatched coinbase`, {
506
+ ...proposalInfo,
507
+ proposalCoinbase: proposalGlobals.coinbase.toString(),
508
+ parentCoinbase: parentGlobals.coinbase.toString(),
509
+ });
510
+ return { reason: 'global_variables_mismatch' };
511
+ }
512
+
513
+ if (!proposalGlobals.feeRecipient.equals(parentGlobals.feeRecipient)) {
514
+ this.log.warn(`Non-first block in checkpoint has mismatched feeRecipient`, {
515
+ ...proposalInfo,
516
+ proposalFeeRecipient: proposalGlobals.feeRecipient.toString(),
517
+ parentFeeRecipient: parentGlobals.feeRecipient.toString(),
518
+ });
519
+ return { reason: 'global_variables_mismatch' };
520
+ }
521
+
522
+ if (!proposalGlobals.gasFees.equals(parentGlobals.gasFees)) {
523
+ this.log.warn(`Non-first block in checkpoint has mismatched gasFees`, {
524
+ ...proposalInfo,
525
+ proposalGasFees: proposalGlobals.gasFees.toInspect(),
526
+ parentGasFees: parentGlobals.gasFees.toInspect(),
527
+ });
528
+ return { reason: 'global_variables_mismatch' };
529
+ }
530
+
531
+ return undefined;
532
+ }
533
+
534
+ private getReexecutionDeadline(slot: SlotNumber, config: { l1GenesisTime: bigint; slotDuration: number }): Date {
535
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
536
+ return new Date(nextSlotTimestampSeconds * 1000);
537
+ }
538
+
539
+ /** Waits for the block source to sync L1 data up to at least the slot before the given one. */
540
+ private async waitForBlockSourceSync(slot: SlotNumber): Promise<boolean> {
541
+ const deadline = this.getReexecutionDeadline(slot, this.checkpointsBuilder.getConfig());
542
+ const timeoutMs = deadline.getTime() - this.dateProvider.now();
543
+ if (slot === 0) {
544
+ return true;
545
+ }
546
+
547
+ // Make a quick check before triggering an archiver sync
548
+ const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
549
+ if (syncedSlot !== undefined && syncedSlot + 1 >= slot) {
550
+ return true;
551
+ }
552
+
553
+ try {
554
+ // Trigger an immediate sync of the block source, and wait until it reports being synced to the required slot
555
+ return await retryUntil(
556
+ async () => {
557
+ await this.blockSource.syncImmediate();
558
+ const syncedSlot = await this.blockSource.getSyncedL2SlotNumber();
559
+ return syncedSlot !== undefined && syncedSlot + 1 >= slot;
560
+ },
561
+ 'wait for block source sync',
562
+ timeoutMs / 1000,
563
+ 0.5,
564
+ );
565
+ } catch (err) {
566
+ if (err instanceof TimeoutError) {
567
+ this.log.warn(`Timed out waiting for block source to sync to slot ${slot}`);
568
+ return false;
569
+ } else {
570
+ throw err;
571
+ }
572
+ }
573
+ }
574
+
575
+ private getReexecuteFailureReason(err: any): BlockProposalValidationFailureReason {
576
+ if (err instanceof TransactionsNotAvailableError) {
577
+ return 'txs_not_available';
578
+ } else if (err instanceof ReExInitialStateMismatchError) {
579
+ return 'initial_state_mismatch';
580
+ } else if (err instanceof ReExStateMismatchError) {
581
+ return 'state_mismatch';
582
+ } else if (err instanceof ReExFailedTxsError) {
583
+ return 'failed_txs';
584
+ } else if (err instanceof ReExTimeoutError) {
585
+ return 'timeout';
586
+ } else {
587
+ return 'unknown_error';
588
+ }
589
+ }
590
+
591
+ async reexecuteTransactions(
592
+ proposal: BlockProposal,
593
+ blockNumber: BlockNumber,
594
+ checkpointNumber: CheckpointNumber,
595
+ txs: Tx[],
596
+ l1ToL2Messages: Fr[],
597
+ previousCheckpointOutHashes: Fr[],
598
+ ): Promise<ReexecuteTransactionsResult> {
599
+ const { blockHeader, txHashes } = proposal;
600
+
601
+ // If we do not have all of the transactions, then we should fail
602
+ if (txs.length !== txHashes.length) {
603
+ const foundTxHashes = txs.map(tx => tx.getTxHash());
604
+ const missingTxHashes = txHashes.filter(txHash => !foundTxHashes.includes(txHash));
605
+ throw new TransactionsNotAvailableError(missingTxHashes);
606
+ }
607
+
608
+ const timer = new Timer();
609
+ const slot = proposal.slotNumber;
610
+ const config = this.checkpointsBuilder.getConfig();
611
+
612
+ // Get prior blocks in this checkpoint (same slot before current block)
613
+ const allBlocksInSlot = await this.blockSource.getBlocksForSlot(slot);
614
+ const priorBlocks = allBlocksInSlot.filter(b => b.number < blockNumber && b.header.getSlot() === slot);
615
+
616
+ // Fork before the block to be built
617
+ const parentBlockNumber = BlockNumber(blockNumber - 1);
618
+ await this.worldState.syncImmediate(parentBlockNumber);
619
+ await using fork = await this.worldState.fork(parentBlockNumber);
620
+
621
+ // Verify the fork's archive root matches the proposal's expected last archive.
622
+ // If they don't match, our world state synced to a different chain and reexecution would fail.
623
+ const forkArchiveRoot = new Fr((await fork.getTreeInfo(MerkleTreeId.ARCHIVE)).root);
624
+ if (!forkArchiveRoot.equals(proposal.blockHeader.lastArchive.root)) {
625
+ throw new ReExInitialStateMismatchError(proposal.blockHeader.lastArchive.root, forkArchiveRoot);
626
+ }
627
+
628
+ // Build checkpoint constants from proposal (excludes blockNumber which is per-block)
629
+ const constants: CheckpointGlobalVariables = {
630
+ chainId: new Fr(config.l1ChainId),
631
+ version: new Fr(config.rollupVersion),
632
+ slotNumber: slot,
633
+ timestamp: blockHeader.globalVariables.timestamp,
634
+ coinbase: blockHeader.globalVariables.coinbase,
635
+ feeRecipient: blockHeader.globalVariables.feeRecipient,
636
+ gasFees: blockHeader.globalVariables.gasFees,
637
+ };
638
+
639
+ // Create checkpoint builder with prior blocks
640
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(
641
+ checkpointNumber,
642
+ constants,
643
+ 0n, // only takes effect in the following checkpoint.
644
+ l1ToL2Messages,
645
+ previousCheckpointOutHashes,
646
+ fork,
647
+ priorBlocks,
648
+ this.log.getBindings(),
649
+ );
650
+
651
+ // Build the new block
652
+ const deadline = this.getReexecutionDeadline(slot, config);
653
+ const maxBlockGas =
654
+ this.config.validateMaxL2BlockGas !== undefined || this.config.validateMaxDABlockGas !== undefined
655
+ ? new Gas(this.config.validateMaxDABlockGas ?? Infinity, this.config.validateMaxL2BlockGas ?? Infinity)
656
+ : undefined;
657
+ const result = await checkpointBuilder.buildBlock(txs, blockNumber, blockHeader.globalVariables.timestamp, {
658
+ isBuildingProposal: false,
659
+ minValidTxs: 0,
660
+ deadline,
661
+ expectedEndState: blockHeader.state,
662
+ maxTransactions: this.config.validateMaxTxsPerBlock,
663
+ maxBlockGas,
664
+ });
665
+
666
+ const { block, failedTxs } = result;
667
+ const numFailedTxs = failedTxs.length;
668
+
669
+ this.log.verbose(`Block proposal ${blockNumber} at slot ${slot} transaction re-execution complete`, {
670
+ numFailedTxs,
671
+ numProposalTxs: txHashes.length,
672
+ numProcessedTxs: block.body.txEffects.length,
673
+ blockNumber,
674
+ slot,
675
+ });
676
+
677
+ if (numFailedTxs > 0) {
678
+ this.metrics?.recordFailedReexecution(proposal);
679
+ throw new ReExFailedTxsError(numFailedTxs);
680
+ }
681
+
682
+ if (block.body.txEffects.length !== txHashes.length) {
683
+ this.metrics?.recordFailedReexecution(proposal);
684
+ throw new ReExTimeoutError();
685
+ }
686
+
687
+ // Throw a ReExStateMismatchError error if state updates do not match
688
+ // Compare the full block structure (archive and header) from the built block with the proposal
689
+ const archiveMatches = proposal.archive.equals(block.archive.root);
690
+ const headerMatches = proposal.blockHeader.equals(block.header);
691
+ if (!archiveMatches || !headerMatches) {
692
+ this.log.warn(`Re-execution state mismatch for slot ${slot}`, {
693
+ expectedArchive: block.archive.root.toString(),
694
+ actualArchive: proposal.archive.toString(),
695
+ expectedHeader: block.header.toInspect(),
696
+ actualHeader: proposal.blockHeader.toInspect(),
697
+ });
698
+ this.metrics?.recordFailedReexecution(proposal);
699
+ throw new ReExStateMismatchError(proposal.archive, block.archive.root);
700
+ }
701
+
702
+ const reexecutionTimeMs = timer.ms();
703
+ const totalManaUsed = block.header.totalManaUsed.toNumber() / 1e6;
704
+
705
+ this.metrics?.recordReex(reexecutionTimeMs, txs.length, totalManaUsed);
706
+
707
+ return {
708
+ block,
709
+ failedTxs,
710
+ reexecutionTimeMs,
711
+ totalManaUsed,
712
+ };
713
+ }
714
+
715
+ /**
716
+ * Validates a checkpoint proposal, caches the result, and uploads blobs if configured.
717
+ * Returns a cached result if the same proposal (archive + slot) was already validated.
718
+ * Used by both the all-nodes callback (via register) and the validator client (via delegation).
719
+ */
720
+ async handleCheckpointProposal(
721
+ proposal: CheckpointProposalCore,
722
+ proposalInfo: LogData,
723
+ ): Promise<CheckpointProposalValidationResult> {
724
+ const slot = proposal.slotNumber;
725
+
726
+ // Check cache: same archive+slot means we already validated this proposal
727
+ if (
728
+ this.lastCheckpointValidationResult &&
729
+ this.lastCheckpointValidationResult.archive.equals(proposal.archive) &&
730
+ this.lastCheckpointValidationResult.slotNumber === slot
731
+ ) {
732
+ this.log.debug(`Returning cached validation result for checkpoint proposal at slot ${slot}`, proposalInfo);
733
+ return this.lastCheckpointValidationResult.result;
734
+ }
735
+
736
+ const proposer = proposal.getSender();
737
+ if (!proposer) {
738
+ this.log.warn(`Received checkpoint proposal with invalid signature for slot ${proposal.slotNumber}`);
739
+ const result: CheckpointProposalValidationResult = { isValid: false, reason: 'invalid_signature' };
740
+ this.lastCheckpointValidationResult = { archive: proposal.archive, slotNumber: slot, result };
741
+ return result;
742
+ }
743
+
744
+ if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
745
+ this.log.warn(
746
+ `Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${proposal.slotNumber}`,
747
+ );
748
+ const result: CheckpointProposalValidationResult = { isValid: false, reason: 'invalid_fee_asset_price_modifier' };
749
+ this.lastCheckpointValidationResult = { archive: proposal.archive, slotNumber: slot, result };
750
+ return result;
751
+ }
752
+
753
+ const result = await this.validateCheckpointProposal(proposal, proposalInfo);
754
+ this.lastCheckpointValidationResult = { archive: proposal.archive, slotNumber: slot, result };
755
+
756
+ // Upload blobs to filestore if validation passed (fire and forget)
757
+ if (result.isValid) {
758
+ this.tryUploadBlobsForCheckpoint(proposal, proposalInfo);
759
+ }
760
+
761
+ return result;
762
+ }
763
+
764
+ /**
765
+ * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
766
+ * @returns Validation result with isValid flag and reason if invalid.
767
+ */
768
+ async validateCheckpointProposal(
769
+ proposal: CheckpointProposalCore,
770
+ proposalInfo: LogData,
771
+ ): Promise<CheckpointProposalValidationResult> {
772
+ const slot = proposal.slotNumber;
773
+
774
+ // Timeout block syncing at the start of the next slot
775
+ const config = this.checkpointsBuilder.getConfig();
776
+ const nextSlotTimestampSeconds = Number(getTimestampForSlot(SlotNumber(slot + 1), config));
777
+ const timeoutSeconds = Math.max(1, nextSlotTimestampSeconds - Math.floor(this.dateProvider.now() / 1000));
778
+
779
+ // Wait for last block to sync by archive
780
+ let lastBlockHeader;
781
+ try {
782
+ lastBlockHeader = await retryUntil(
783
+ async () => {
784
+ await this.blockSource.syncImmediate();
785
+ return this.blockSource.getBlockHeaderByArchive(proposal.archive);
786
+ },
787
+ `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`,
788
+ timeoutSeconds,
789
+ 0.5,
790
+ );
791
+ } catch (err) {
792
+ if (err instanceof TimeoutError) {
793
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
794
+ return { isValid: false, reason: 'last_block_not_found' };
795
+ }
796
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
797
+ return { isValid: false, reason: 'block_fetch_error' };
798
+ }
799
+
800
+ if (!lastBlockHeader) {
801
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
802
+ return { isValid: false, reason: 'last_block_not_found' };
803
+ }
804
+
805
+ // Get all full blocks for the slot and checkpoint
806
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
807
+ if (blocks.length === 0) {
808
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
809
+ return { isValid: false, reason: 'no_blocks_for_slot' };
810
+ }
811
+
812
+ // Ensure the last block for this slot matches the archive in the checkpoint proposal
813
+ if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
814
+ this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
815
+ return { isValid: false, reason: 'last_block_archive_mismatch' };
816
+ }
817
+
818
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
819
+ ...proposalInfo,
820
+ blockNumbers: blocks.map(b => b.number),
821
+ });
822
+
823
+ // Get checkpoint constants from first block
824
+ const firstBlock = blocks[0];
825
+ const constants = this.extractCheckpointConstants(firstBlock);
826
+ const checkpointNumber = firstBlock.checkpointNumber;
827
+
828
+ // Get L1-to-L2 messages for this checkpoint
829
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(checkpointNumber);
830
+
831
+ // Collect the out hashes of all the checkpoints before this one in the same epoch
832
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
833
+ const previousCheckpointOutHashes = (await this.blockSource.getCheckpointsDataForEpoch(epoch))
834
+ .filter(c => c.checkpointNumber < checkpointNumber)
835
+ .map(c => c.checkpointOutHash);
836
+
837
+ // Fork world state at the block before the first block
838
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
839
+ await using fork = await this.checkpointsBuilder.getFork(parentBlockNumber);
840
+
841
+ // Create checkpoint builder with all existing blocks
842
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(
843
+ checkpointNumber,
844
+ constants,
845
+ proposal.feeAssetPriceModifier,
846
+ l1ToL2Messages,
847
+ previousCheckpointOutHashes,
848
+ fork,
849
+ blocks,
850
+ this.log.getBindings(),
851
+ );
852
+
853
+ // Complete the checkpoint to get computed values
854
+ const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
855
+
856
+ // Compare checkpoint header with proposal
857
+ if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
858
+ this.log.warn(`Checkpoint header mismatch`, {
859
+ ...proposalInfo,
860
+ computed: computedCheckpoint.header.toInspect(),
861
+ proposal: proposal.checkpointHeader.toInspect(),
862
+ });
863
+ return { isValid: false, reason: 'checkpoint_header_mismatch' };
864
+ }
865
+
866
+ // Compare archive root with proposal
867
+ if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
868
+ this.log.warn(`Archive root mismatch`, {
869
+ ...proposalInfo,
870
+ computed: computedCheckpoint.archive.root.toString(),
871
+ proposal: proposal.archive.toString(),
872
+ });
873
+ return { isValid: false, reason: 'archive_mismatch' };
874
+ }
875
+
876
+ // Check that the accumulated epoch out hash matches the value in the proposal.
877
+ // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
878
+ const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
879
+ const computedEpochOutHash = accumulateCheckpointOutHashes([...previousCheckpointOutHashes, checkpointOutHash]);
880
+ const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
881
+ if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
882
+ this.log.warn(`Epoch out hash mismatch`, {
883
+ proposalEpochOutHash: proposalEpochOutHash.toString(),
884
+ computedEpochOutHash: computedEpochOutHash.toString(),
885
+ checkpointOutHash: checkpointOutHash.toString(),
886
+ previousCheckpointOutHashes: previousCheckpointOutHashes.map(h => h.toString()),
887
+ ...proposalInfo,
888
+ });
889
+ return { isValid: false, reason: 'out_hash_mismatch' };
890
+ }
891
+
892
+ // Final round of validations on the checkpoint, just in case.
893
+ try {
894
+ validateCheckpoint(computedCheckpoint, {
895
+ rollupManaLimit: this.checkpointsBuilder.getConfig().rollupManaLimit,
896
+ maxDABlockGas: this.config.validateMaxDABlockGas,
897
+ maxL2BlockGas: this.config.validateMaxL2BlockGas,
898
+ maxTxsPerBlock: this.config.validateMaxTxsPerBlock,
899
+ maxTxsPerCheckpoint: this.config.validateMaxTxsPerCheckpoint,
900
+ });
901
+ } catch (err) {
902
+ this.log.warn(`Checkpoint validation failed: ${err}`, proposalInfo);
903
+ return { isValid: false, reason: 'checkpoint_validation_failed' };
904
+ }
905
+
906
+ this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
907
+ return { isValid: true };
908
+ }
909
+
910
+ /** Extracts checkpoint global variables from a block. */
911
+ private extractCheckpointConstants(block: L2Block): CheckpointGlobalVariables {
912
+ const gv = block.header.globalVariables;
913
+ return {
914
+ chainId: gv.chainId,
915
+ version: gv.version,
916
+ slotNumber: gv.slotNumber,
917
+ timestamp: gv.timestamp,
918
+ coinbase: gv.coinbase,
919
+ feeRecipient: gv.feeRecipient,
920
+ gasFees: gv.gasFees,
921
+ };
922
+ }
923
+
924
+ /** Triggers blob upload for a checkpoint if the blob client can upload (fire and forget). */
925
+ protected tryUploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): void {
926
+ if (this.blobClient.canUpload()) {
927
+ void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
928
+ }
929
+ }
930
+
931
+ /** Uploads blobs for a checkpoint to the filestore. */
932
+ protected async uploadBlobsForCheckpoint(proposal: CheckpointProposalCore, proposalInfo: LogData): Promise<void> {
933
+ try {
934
+ const lastBlockHeader = await this.blockSource.getBlockHeaderByArchive(proposal.archive);
935
+ if (!lastBlockHeader) {
936
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
937
+ return;
938
+ }
939
+
940
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
941
+ if (blocks.length === 0) {
942
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
943
+ return;
944
+ }
945
+
946
+ const blockBlobData = blocks.map(b => b.toBlockBlobData());
947
+ const blobFields = encodeCheckpointBlobDataFromBlocks(blockBlobData);
948
+ const blobs: Blob[] = await getBlobsPerL1Block(blobFields);
949
+ await this.blobClient.sendBlobsToFilestore(blobs);
950
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
951
+ ...proposalInfo,
952
+ numBlobs: blobs.length,
953
+ });
954
+ } catch (err) {
955
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
956
+ }
957
+ }
958
+
959
+ /**
960
+ * Derives proposed checkpoint data from validated blocks and sets it on the archiver.
961
+ * Used after successful validation of a foreign proposal.
962
+ * Does not retry since we already waited for the block during validation.
963
+ */
964
+ private async setProposedCheckpointFromValidation(proposal: CheckpointProposalCore): Promise<void> {
965
+ if (!this.archiver) {
966
+ return;
967
+ }
968
+ const blockData = await this.blockSource.getBlockDataByArchive(proposal.archive);
969
+ if (!blockData) {
970
+ this.log.debug(`Block data not found for checkpoint proposal archive, cannot set proposed checkpoint`, {
971
+ archive: proposal.archive.toString(),
972
+ });
973
+ return;
974
+ }
975
+
976
+ await this.archiver.setProposedCheckpoint({
977
+ header: proposal.checkpointHeader,
978
+ checkpointNumber: blockData.checkpointNumber,
979
+ startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
980
+ blockCount: blockData.indexWithinCheckpoint + 1,
981
+ totalManaUsed: proposal.checkpointHeader.totalManaUsed.toBigInt(),
982
+ feeAssetPriceModifier: proposal.feeAssetPriceModifier,
983
+ });
984
+ }
985
+
986
+ /**
987
+ * Sets proposed checkpoint from blocks for own proposals (skips full validation).
988
+ * Retries fetching block data since the checkpoint proposal often arrives before the last block
989
+ * finishes re-execution.
990
+ */
991
+ private async setProposedCheckpointFromBlocks(proposal: CheckpointProposalCore): Promise<void> {
992
+ if (!this.archiver) {
993
+ return;
994
+ }
995
+ let blockData = await this.blockSource.getBlockDataByArchive(proposal.archive);
996
+
997
+ if (!blockData) {
998
+ // The checkpoint proposal often arrives before the last block finishes re-execution.
999
+ // Retry until we find the data or give up at the end of the slot.
1000
+ const nextSlot = this.epochCache.getSlotNow() + 1;
1001
+ const timeOfNextSlot = getTimestampForSlot(SlotNumber(nextSlot), await this.archiver.getL1Constants());
1002
+ const timeoutSeconds = Math.max(1, Number(timeOfNextSlot) - Math.floor(this.dateProvider.now() / 1000));
1003
+
1004
+ blockData = await retryUntil(
1005
+ () => this.blockSource.getBlockDataByArchive(proposal.archive),
1006
+ 'block data for own checkpoint proposal',
1007
+ timeoutSeconds,
1008
+ 0.25,
1009
+ ).catch(() => undefined);
1010
+ }
1011
+
1012
+ if (blockData) {
1013
+ await this.archiver.setProposedCheckpoint({
1014
+ header: proposal.checkpointHeader,
1015
+ checkpointNumber: blockData.checkpointNumber,
1016
+ startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
1017
+ blockCount: blockData.indexWithinCheckpoint + 1,
1018
+ totalManaUsed: proposal.checkpointHeader.totalManaUsed.toBigInt(),
1019
+ feeAssetPriceModifier: proposal.feeAssetPriceModifier,
1020
+ });
1021
+ } else {
1022
+ this.log.debug(`Block data not found for own checkpoint proposal archive, cannot set proposed checkpoint`, {
1023
+ archive: proposal.archive.toString(),
1024
+ });
1025
+ }
1026
+ }
1027
+ }