@aztec/validator-client 5.0.0-private.20260319 → 5.0.0-rc.1

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