@aztec-labs/validator-client 6.0.0-nightly.20260829

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 (62) hide show
  1. package/README.md +327 -0
  2. package/dest/checkpoint_builder.d.ts +92 -0
  3. package/dest/checkpoint_builder.d.ts.map +1 -0
  4. package/dest/checkpoint_builder.js +272 -0
  5. package/dest/config.d.ts +17 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/config.js +102 -0
  8. package/dest/duties/validation_service.d.ts +65 -0
  9. package/dest/duties/validation_service.d.ts.map +1 -0
  10. package/dest/duties/validation_service.js +128 -0
  11. package/dest/factory.d.ts +41 -0
  12. package/dest/factory.d.ts.map +1 -0
  13. package/dest/factory.js +19 -0
  14. package/dest/index.d.ts +7 -0
  15. package/dest/index.d.ts.map +1 -0
  16. package/dest/index.js +6 -0
  17. package/dest/key_store/ha_key_store.d.ts +99 -0
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  19. package/dest/key_store/ha_key_store.js +208 -0
  20. package/dest/key_store/index.d.ts +6 -0
  21. package/dest/key_store/index.d.ts.map +1 -0
  22. package/dest/key_store/index.js +5 -0
  23. package/dest/key_store/interface.d.ts +104 -0
  24. package/dest/key_store/interface.d.ts.map +1 -0
  25. package/dest/key_store/interface.js +4 -0
  26. package/dest/key_store/local_key_store.d.ts +63 -0
  27. package/dest/key_store/local_key_store.d.ts.map +1 -0
  28. package/dest/key_store/local_key_store.js +83 -0
  29. package/dest/key_store/node_keystore_adapter.d.ts +151 -0
  30. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -0
  31. package/dest/key_store/node_keystore_adapter.js +330 -0
  32. package/dest/key_store/web3signer_key_store.d.ts +74 -0
  33. package/dest/key_store/web3signer_key_store.d.ts.map +1 -0
  34. package/dest/key_store/web3signer_key_store.js +147 -0
  35. package/dest/metrics.d.ts +31 -0
  36. package/dest/metrics.d.ts.map +1 -0
  37. package/dest/metrics.js +101 -0
  38. package/dest/proposal_handler.d.ts +188 -0
  39. package/dest/proposal_handler.d.ts.map +1 -0
  40. package/dest/proposal_handler.js +1438 -0
  41. package/dest/streaming_inbox_checks.d.ts +103 -0
  42. package/dest/streaming_inbox_checks.d.ts.map +1 -0
  43. package/dest/streaming_inbox_checks.js +112 -0
  44. package/dest/validator.d.ts +137 -0
  45. package/dest/validator.d.ts.map +1 -0
  46. package/dest/validator.js +771 -0
  47. package/package.json +110 -0
  48. package/src/checkpoint_builder.ts +449 -0
  49. package/src/config.ts +130 -0
  50. package/src/duties/validation_service.ts +224 -0
  51. package/src/factory.ts +95 -0
  52. package/src/index.ts +6 -0
  53. package/src/key_store/ha_key_store.ts +268 -0
  54. package/src/key_store/index.ts +5 -0
  55. package/src/key_store/interface.ts +120 -0
  56. package/src/key_store/local_key_store.ts +104 -0
  57. package/src/key_store/node_keystore_adapter.ts +397 -0
  58. package/src/key_store/web3signer_key_store.ts +188 -0
  59. package/src/metrics.ts +150 -0
  60. package/src/proposal_handler.ts +1598 -0
  61. package/src/streaming_inbox_checks.ts +198 -0
  62. package/src/validator.ts +1125 -0
@@ -0,0 +1,1438 @@
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-labs/blob-lib';
67
+ import { INITIAL_L2_BLOCK_NUM, MAX_BLOCKS_PER_CHECKPOINT, MAX_L1_TO_L2_MSGS_PER_BLOCK, MAX_L1_TO_L2_MSGS_PER_CHECKPOINT } from '@aztec-labs/constants';
68
+ import { validateFeeAssetPriceModifier } from '@aztec-labs/ethereum/contracts';
69
+ import { BlockNumber, CheckpointNumber } from '@aztec-labs/foundation/branded-types';
70
+ import { pick } from '@aztec-labs/foundation/collection';
71
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
72
+ import { TimeoutError } from '@aztec-labs/foundation/error';
73
+ import { FifoSet } from '@aztec-labs/foundation/fifo-set';
74
+ import { createLogger } from '@aztec-labs/foundation/log';
75
+ import { retryUntil } from '@aztec-labs/foundation/retry';
76
+ import { DateProvider, Timer } from '@aztec-labs/foundation/timer';
77
+ import { isErrorClass } from '@aztec-labs/foundation/types';
78
+ import { getPreviousCheckpointInboxRollingHash, getPreviousCheckpointOutHashes, validateCheckpoint } from '@aztec-labs/stdlib/checkpoint';
79
+ import { getEpochAtSlot } from '@aztec-labs/stdlib/epoch-helpers';
80
+ import { Gas } from '@aztec-labs/stdlib/gas';
81
+ import { accumulateCheckpointOutHashes, getInboxCutoffTimestamp, isInboxConsumptionSufficient } from '@aztec-labs/stdlib/messaging';
82
+ import { MerkleTreeId } from '@aztec-labs/stdlib/trees';
83
+ import { InvalidBlockProposalTxsError, ReExFailedTxsError, ReExInitialStateMismatchError, ReExStateMismatchError, ReExTimeoutError, TransactionsNotAvailableError } from '@aztec-labs/stdlib/validators';
84
+ import { getTelemetryClient } from '@aztec-labs/telemetry-client';
85
+ import { checkStreamingBlockProposalMetadata, getStreamingBlockBundle } from './streaming_inbox_checks.js';
86
+ /**
87
+ * Mapping from a checkpoint-proposal validation failure reason to the tracker outcome that
88
+ * `handleCheckpointProposal` should record. `undefined` means do not record (signature
89
+ * couldn't be verified, or the checkpoint is already on L1 so the question is moot).
90
+ */ /* eslint-disable camelcase */ const CHECKPOINT_VALIDATION_REASON_TO_OUTCOME = {
91
+ invalid_signature: undefined,
92
+ invalid_fee_asset_price_modifier: 'invalid',
93
+ checkpoint_already_published: undefined,
94
+ last_block_not_found: 'unvalidated',
95
+ block_fetch_error: 'unvalidated',
96
+ world_state_not_synced: 'unvalidated',
97
+ initial_archive_mismatch: 'unvalidated',
98
+ no_blocks_for_slot: 'unvalidated',
99
+ last_block_archive_mismatch: 'invalid',
100
+ too_many_blocks_in_checkpoint: 'invalid',
101
+ checkpoint_header_mismatch: 'invalid',
102
+ archive_mismatch: 'invalid',
103
+ out_hash_mismatch: 'invalid',
104
+ inbox_consumption_insufficient: 'invalid',
105
+ checkpoint_validation_failed: 'invalid'
106
+ };
107
+ const MAX_TRACKED_INVALID_PROPOSAL_SLOTS = 1000;
108
+ /** Block-proposal validation failures that constitute a slashable invalid-block offense. */ export const SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT = [
109
+ 'state_mismatch',
110
+ 'failed_txs',
111
+ 'global_variables_mismatch',
112
+ 'invalid_proposal',
113
+ 'parent_block_wrong_slot',
114
+ 'duplicate_txs',
115
+ 'invalid_embedded_txs'
116
+ ];
117
+ /** Checkpoint-proposal validation failures that constitute a slashable invalid-checkpoint offense. */ export const SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT = {
118
+ // enabled
119
+ ['invalid_fee_asset_price_modifier']: true,
120
+ ['checkpoint_header_mismatch']: true,
121
+ // These late mismatches should normally be caught by earlier checks, but if reached after validating the local
122
+ // checkpoint inputs, the proposer-signed payload disagrees with deterministic recomputation.
123
+ ['archive_mismatch']: true,
124
+ ['out_hash_mismatch']: true,
125
+ ['no_blocks_for_slot']: true,
126
+ ['too_many_blocks_in_checkpoint']: true,
127
+ ['checkpoint_validation_failed']: true,
128
+ ['last_block_archive_mismatch']: true,
129
+ // disabled
130
+ // Streaming Inbox last-block censorship: kept out of slashing while the streaming path is new; L1 `propose` is the
131
+ // authoritative reject (Rollup__UnconsumedInboxMessages).
132
+ ['inbox_consumption_insufficient']: false,
133
+ ['invalid_signature']: false,
134
+ ['last_block_not_found']: false,
135
+ ['block_fetch_error']: false,
136
+ ['world_state_not_synced']: false,
137
+ // A reorg / divergent local chain, not a proposer offense (mirrors the block path's initial_state_mismatch).
138
+ ['initial_archive_mismatch']: false,
139
+ ['checkpoint_already_published']: false
140
+ };
141
+ /**
142
+ * Handles block and checkpoint proposals for both validator and non-validator nodes. Also tracks which slots
143
+ * had a slashable invalid proposal or a proposal equivocation, exposing them via the
144
+ * `InvalidProposalSlotSource` interface consumed by the attested-invalid-proposal slashing watcher. The
145
+ * tracking is populated as a side effect of validating/re-executing proposals, so any node that re-executes
146
+ * proposals (the default) can serve it — not only validators.
147
+ */ export class ProposalHandler {
148
+ checkpointsBuilder;
149
+ worldState;
150
+ blockSource;
151
+ l1ToL2MessageSource;
152
+ txProvider;
153
+ epochCache;
154
+ timetable;
155
+ config;
156
+ blobClient;
157
+ reexecutionTracker;
158
+ metrics;
159
+ dateProvider;
160
+ log;
161
+ tracer;
162
+ /** Cached last checkpoint validation result to avoid double-validation on validator nodes.
163
+ * Keyed by signed-payload hash so two proposals at the same (slot, archive) but with a
164
+ * different `feeAssetPriceModifier` (or any other signed field) are validated independently. */ lastCheckpointValidationResult;
165
+ /** Archiver reference for setting proposed checkpoints (pipelining). Set via register(). */ archiver;
166
+ /** Returns current validator addresses for own-proposal detection. Set via register(). */ getOwnValidatorAddresses;
167
+ /** P2P proposal pool access for deciding when retained proposals should block archiver processing. */ p2pClient;
168
+ checkpointProposalValidationFailureCallback;
169
+ /** Slots at which a slashable invalid block or checkpoint proposal was observed. */ slotsWithInvalidProposals;
170
+ /** Slots at which a proposal equivocation was observed; suppresses attested-to-invalid-proposal slashing. */ slotsWithProposalEquivocation;
171
+ constructor(checkpointsBuilder, worldState, blockSource, l1ToL2MessageSource, txProvider, epochCache, timetable, config, blobClient, reexecutionTracker, metrics, dateProvider = new DateProvider(), telemetry = getTelemetryClient(), log = createLogger('validator:proposal-handler')){
172
+ this.checkpointsBuilder = checkpointsBuilder;
173
+ this.worldState = worldState;
174
+ this.blockSource = blockSource;
175
+ this.l1ToL2MessageSource = l1ToL2MessageSource;
176
+ this.txProvider = txProvider;
177
+ this.epochCache = epochCache;
178
+ this.timetable = timetable;
179
+ this.config = config;
180
+ this.blobClient = blobClient;
181
+ this.reexecutionTracker = reexecutionTracker;
182
+ this.metrics = metrics;
183
+ this.dateProvider = dateProvider;
184
+ this.log = log;
185
+ this.slotsWithInvalidProposals = FifoSet.withLimit(MAX_TRACKED_INVALID_PROPOSAL_SLOTS);
186
+ this.slotsWithProposalEquivocation = FifoSet.withLimit(MAX_TRACKED_INVALID_PROPOSAL_SLOTS);
187
+ if (config.fishermanMode) {
188
+ this.log = this.log.createChild('[FISHERMAN]');
189
+ }
190
+ this.tracer = telemetry.getTracer('ProposalHandler');
191
+ }
192
+ updateConfig(config) {
193
+ this.config = {
194
+ ...this.config,
195
+ ...config
196
+ };
197
+ }
198
+ setCheckpointProposalValidationFailureCallback(callback) {
199
+ this.checkpointProposalValidationFailureCallback = callback;
200
+ }
201
+ /**
202
+ * Records the proposer's own checkpoint proposal as a `valid` outcome in the re-execution
203
+ * tracker. Without this, the node's own checkpoint proposals never flow through
204
+ * `handleCheckpointProposal` (proposers don't validate their own proposals), so its sentinel
205
+ * sees no outcome for slots where it was the proposer and reports itself as inactive.
206
+ *
207
+ * `archive` should be the locally-computed archive (NOT the broadcast archive, which may have
208
+ * been deliberately corrupted in tests via `broadcastInvalidBlockProposal` /
209
+ * `broadcastInvalidCheckpointProposalOnly`). Recording the local archive correctly models the
210
+ * proposer's own view of its own work.
211
+ */ recordOwnCheckpointProposalAsValid(slot, archive, checkpointNumber) {
212
+ this.reexecutionTracker.recordOutcome(slot, archive, 'valid', checkpointNumber);
213
+ }
214
+ /** Whether a slashable invalid block or checkpoint proposal was observed at the given slot (InvalidProposalSlotSource). */ hasInvalidProposals(slotNumber) {
215
+ return this.slotsWithInvalidProposals.has(slotNumber);
216
+ }
217
+ /** Whether a proposal equivocation was observed at the given slot (InvalidProposalSlotSource). */ hasProposalEquivocation(slotNumber) {
218
+ return this.slotsWithProposalEquivocation.has(slotNumber);
219
+ }
220
+ /** Records a slot as having a slashable invalid proposal, for offense observers (sentinel/slasher watchers). */ markInvalidProposalSlot(slotNumber) {
221
+ this.slotsWithInvalidProposals.add(slotNumber);
222
+ }
223
+ /** Records a slot as having a proposal equivocation, which suppresses attested-to-invalid-proposal slashing. */ markProposalEquivocation(slotNumber) {
224
+ this.slotsWithProposalEquivocation.add(slotNumber);
225
+ }
226
+ /**
227
+ * Registers handlers for block and checkpoint proposals on the p2p client.
228
+ * Records the p2p client so validation can inspect retained proposals.
229
+ * Block proposals are registered for non-validator nodes (validators register their own enhanced handler).
230
+ * The all-nodes checkpoint proposal handler is always registered for validation, caching, and pipelining.
231
+ * @param archiver - Archiver reference for setting proposed checkpoints (pipelining)
232
+ * @param getOwnValidatorAddresses - Returns current validator addresses for own-proposal detection
233
+ */ register(p2pClient, shouldReexecute, archiver, getOwnValidatorAddresses) {
234
+ this.p2pClient = p2pClient;
235
+ this.archiver = archiver;
236
+ this.getOwnValidatorAddresses = getOwnValidatorAddresses;
237
+ // Non-validator handler that processes or re-executes for monitoring but does not attest.
238
+ // Returns boolean indicating whether the proposal was valid.
239
+ const blockHandler = async (proposal, proposalSender)=>{
240
+ try {
241
+ const { slotNumber, blockNumber } = proposal;
242
+ const result = await this.handleBlockProposal(proposal, proposalSender, shouldReexecute);
243
+ if (result.isValid) {
244
+ this.log.info(`Non-validator block proposal ${blockNumber} at slot ${slotNumber} handled`, {
245
+ blockNumber: result.blockNumber,
246
+ slotNumber,
247
+ reexecutionTimeMs: result.reexecutionResult?.reexecutionTimeMs,
248
+ totalManaUsed: result.reexecutionResult?.totalManaUsed,
249
+ numTxs: result.reexecutionResult?.block?.body?.txEffects?.length ?? 0,
250
+ reexecuted: shouldReexecute
251
+ });
252
+ return true;
253
+ } else {
254
+ // Track invalid proposals / equivocations so offense observers (the attested-invalid-proposal
255
+ // watcher) work on non-validator nodes too. Validators populate these via their own handlers.
256
+ // Skip invalid-proposal marking while the escape hatch is open, matching the validator path,
257
+ // which intentionally disables invalid-block slashing then.
258
+ if (result.reason === 'checkpoint_proposal_equivocation') {
259
+ this.markProposalEquivocation(slotNumber);
260
+ } else if (SLASHABLE_BLOCK_PROPOSAL_VALIDATION_RESULT.includes(result.reason) && !await this.epochCache.isEscapeHatchOpenAtSlot(slotNumber)) {
261
+ this.markInvalidProposalSlot(slotNumber);
262
+ }
263
+ this.log.warn(`Non-validator block proposal ${blockNumber} at slot ${slotNumber} failed processing with ${result.reason}`, {
264
+ blockNumber: result.blockNumber,
265
+ slotNumber,
266
+ reason: result.reason
267
+ });
268
+ return false;
269
+ }
270
+ } catch (error) {
271
+ this.log.error('Error processing block proposal in non-validator handler', error);
272
+ return false;
273
+ }
274
+ };
275
+ p2pClient.registerBlockProposalHandler(blockHandler);
276
+ // p2p detects duplicate (equivocated) proposals without routing them through the handlers above, so mark
277
+ // the slot as equivocated here. This suppresses false-positive attested-to-invalid-proposal slashing on
278
+ // non-validator offense collectors. Validators overwrite this with their own richer handler.
279
+ p2pClient.registerDuplicateProposalCallback((info)=>this.markProposalEquivocation(info.slot));
280
+ // All-nodes checkpoint proposal handler: validates, caches, and sets proposed checkpoint for pipelining.
281
+ // Runs for all nodes (validators and non-validators). Validators get the cached result in the
282
+ // validator-specific callback (attestToCheckpointProposal) which runs after this one.
283
+ const checkpointHandler = async (proposal, _sender)=>{
284
+ try {
285
+ const pipeliningTimer = new Timer();
286
+ const proposalInfo = {
287
+ slot: proposal.slotNumber,
288
+ archive: proposal.archive.toString(),
289
+ proposer: proposal.getSender()?.toString()
290
+ };
291
+ if (this.config.skipCheckpointProposalValidation) {
292
+ this.log.warn(`Skipping checkpoint proposal validation for slot ${proposal.slotNumber}`, proposalInfo);
293
+ return undefined;
294
+ }
295
+ if (await this.epochCache.isEscapeHatchOpenAtSlot(proposal.slotNumber)) {
296
+ this.log.warn(`Escape hatch open for slot ${proposal.slotNumber}, skipping checkpoint proposal validation`, proposalInfo);
297
+ return undefined;
298
+ }
299
+ // A proposal is "own" when it was signed by a validator key this node also owns. The true local
300
+ // proposer already built, validated, and stored this checkpoint before broadcasting, so a matching
301
+ // proposed checkpoint is already in its archiver — skip the redundant re-validation. An HA peer that
302
+ // shares the proposer's keys sees the same "own" proposal over gossip but never built it, so it has
303
+ // nothing stored; it falls through to the normal validate-and-persist path below to hydrate the
304
+ // proposed-checkpoint metadata it needs to build the next slot on top of this checkpoint.
305
+ const proposer = proposal.getSender();
306
+ const ownAddresses = this.getOwnValidatorAddresses?.();
307
+ const isOwnProposal = proposer && ownAddresses?.some((addr)=>addr === proposer.toString());
308
+ if (isOwnProposal) {
309
+ const existing = await this.archiver?.getProposedCheckpointData({
310
+ slot: proposal.slotNumber
311
+ });
312
+ if (existing?.archive.root.equals(proposal.archive)) {
313
+ this.log.debug(`Skipping sync for existing own checkpoint proposal at slot ${proposal.slotNumber}`);
314
+ return undefined;
315
+ }
316
+ }
317
+ const result = await this.handleCheckpointProposal(proposal, proposalInfo);
318
+ if (!result.isValid) {
319
+ // Track invalid checkpoint proposals so offense observers (the attested-invalid-proposal watcher)
320
+ // work on non-validator nodes too. This handler runs for all nodes; validators also mark via the
321
+ // failure callback below (idempotent).
322
+ if (SLASHABLE_CHECKPOINT_PROPOSAL_VALIDATION_RESULT[result.reason]) {
323
+ this.markInvalidProposalSlot(proposal.slotNumber);
324
+ }
325
+ await this.checkpointProposalValidationFailureCallback?.(proposal, result, proposalInfo);
326
+ } else if (this.archiver) {
327
+ const set = await this.setProposedCheckpoint(proposal);
328
+ if (set) {
329
+ this.metrics?.recordCheckpointProposalToPipelinedStateDuration(pipeliningTimer.ms());
330
+ }
331
+ }
332
+ } catch (err) {
333
+ this.log.warn(`Error handling checkpoint proposal for slot ${proposal.slotNumber}`, {
334
+ err
335
+ });
336
+ }
337
+ return undefined;
338
+ };
339
+ p2pClient.registerAllNodesCheckpointProposalHandler(checkpointHandler);
340
+ return this;
341
+ }
342
+ /**
343
+ * Processes a block proposal: collects its txs and, if requested, re-executes them to check the resulting
344
+ * block against the proposal. Expects the proposal to have already passed p2p ingress validation (signature
345
+ * context, signature, expected proposer, index within checkpoint, tx field checks, and the receive-window
346
+ * timeliness check) — none of those are re-applied here, and only deterministic properties of the payload
347
+ * are validated before processing.
348
+ */ async handleBlockProposal(proposal, proposalSender, shouldReexecute) {
349
+ const slotNumber = proposal.slotNumber;
350
+ const proposer = proposal.getSender();
351
+ // Reject proposals with invalid signatures
352
+ if (!proposer) {
353
+ this.log.warn(`Received proposal with invalid signature for slot ${slotNumber}`);
354
+ return {
355
+ isValid: false,
356
+ reason: 'invalid_signature'
357
+ };
358
+ }
359
+ const proposalInfo = {
360
+ ...proposal.toBlockInfo(),
361
+ proposer: proposer.toString(),
362
+ blockNumber: undefined,
363
+ checkpointNumber: undefined
364
+ };
365
+ this.log.info(`Processing proposal for slot ${slotNumber}`, {
366
+ ...proposalInfo,
367
+ txHashes: proposal.txHashes.map((t)=>t.toString())
368
+ });
369
+ // The receive-window check from p2p ingress is deliberately not re-applied here: its outcome depends on
370
+ // the wall clock at evaluation time, so re-running it turned node-local processing latency into an
371
+ // invalid-proposal verdict against an honest proposer, which then fed the invalid-block slashing path.
372
+ // A tx can only appear once in a block: the second copy would emit nullifiers already emitted by the
373
+ // first. This is not a relaying-peer fault, so it passes gossip validation and is classified here as
374
+ // proposer misbehavior. Tx collection also reconciles a deduplicated hash set against the full list,
375
+ // so it must not be handed a proposal with repeated hashes.
376
+ const uniqueTxHashes = new Set(proposal.txHashes.map((txHash)=>txHash.toString()));
377
+ if (uniqueTxHashes.size !== proposal.txHashes.length) {
378
+ this.log.warn(`Proposal lists duplicate tx hashes, skipping processing`, {
379
+ ...proposalInfo,
380
+ txCount: proposal.txHashes.length,
381
+ uniqueTxCount: uniqueTxHashes.size
382
+ });
383
+ return {
384
+ isValid: false,
385
+ reason: 'duplicate_txs'
386
+ };
387
+ }
388
+ const retainedSlotValidation = await this.validateNewBlockInSlot(proposal);
389
+ if (!retainedSlotValidation.isValid) {
390
+ this.log.info(`Block proposal conflicts with retained proposals, skipping archiver processing`, {
391
+ ...proposalInfo,
392
+ indexWithinCheckpoint: proposal.indexWithinCheckpoint,
393
+ reason: retainedSlotValidation.reason
394
+ });
395
+ return {
396
+ isValid: false,
397
+ blockNumber: proposal.blockNumber,
398
+ reason: retainedSlotValidation.reason
399
+ };
400
+ }
401
+ // The proposer builds ahead of L1 submission under pipelining, so the block source won't have
402
+ // synced to the proposed slot yet. We deliberately do not wait for it to sync here, to avoid
403
+ // eating into the attestation window.
404
+ // Check that the parent proposal is a block we know, otherwise reexecution would fail.
405
+ // If we don't find it immediately, we keep retrying for a while; it may be we still
406
+ // need to process other block proposals to get to it.
407
+ const parentBlock = await this.getParentBlock(proposal);
408
+ if (parentBlock === undefined) {
409
+ this.log.warn(`Parent block for proposal not found, skipping processing`, proposalInfo);
410
+ return {
411
+ isValid: false,
412
+ reason: 'parent_block_not_found'
413
+ };
414
+ }
415
+ // Check that the parent block's slot is not greater than the proposal's slot.
416
+ if (parentBlock !== 'genesis' && parentBlock.header.getSlot() > slotNumber) {
417
+ this.log.warn(`Parent block slot is greater than proposal slot, skipping processing`, {
418
+ parentBlockSlot: parentBlock.header.getSlot().toString(),
419
+ proposalSlot: slotNumber.toString(),
420
+ ...proposalInfo
421
+ });
422
+ return {
423
+ isValid: false,
424
+ reason: 'parent_block_wrong_slot'
425
+ };
426
+ }
427
+ // Compute the block number based on the parent block
428
+ const blockNumber = parentBlock === 'genesis' ? BlockNumber(INITIAL_L2_BLOCK_NUM) : BlockNumber(parentBlock.header.getBlockNumber() + 1);
429
+ proposalInfo.blockNumber = blockNumber;
430
+ // Check that this block number does not exist already. During a reorg the archiver can still hold a
431
+ // stale block at this number (a different archive, about to be pruned) while the proposal carries the
432
+ // rebuilt replacement; resolveExistingBlockAtNumber waits for the local prune in that case so the
433
+ // rebuilt block is processed in time to attest, rather than being permanently dropped on a bare
434
+ // number collision.
435
+ const existingBlock = await this.resolveExistingBlockAtNumber(blockNumber, proposal.archive, slotNumber);
436
+ if (existingBlock) {
437
+ this.log.warn(`Block number ${blockNumber} already exists, skipping processing`, proposalInfo);
438
+ return {
439
+ isValid: false,
440
+ blockNumber,
441
+ reason: 'block_number_already_exists'
442
+ };
443
+ }
444
+ // Streaming Inbox: run the metadata checks before committing to any network work. They are point lookups
445
+ // against our own Inbox view, so a proposal carrying a bucket reference that does not resolve locally is
446
+ // rejected without a proposer being able to make us spend the validation window collecting its txs.
447
+ const streamingMetadata = await this.checkStreamingBlockMetadata(proposal, blockNumber, parentBlock);
448
+ if (!streamingMetadata.accepted) {
449
+ this.log.warn(`Streaming Inbox block acceptance check failed, skipping processing`, {
450
+ reason: streamingMetadata.reason,
451
+ bucketRef: proposal.bucketRef?.toInspect(),
452
+ ...proposalInfo
453
+ });
454
+ return {
455
+ isValid: false,
456
+ blockNumber,
457
+ reason: streamingMetadata.reason
458
+ };
459
+ }
460
+ // Collect txs from the proposal. We start doing this as early as possible,
461
+ // 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.
462
+ // The block's message bundle is an independent read, so derive it concurrently with the collection.
463
+ const txsPromise = this.collectProposalTxs(proposal, blockNumber, proposalSender, proposalInfo);
464
+ const bundlePromise = getStreamingBlockBundle(this.l1ToL2MessageSource, streamingMetadata);
465
+ // Promise.all settles on the first rejection, so without a handler of its own the loser's later rejection
466
+ // would surface as an unhandled rejection. Awaiting below still observes whichever rejected first.
467
+ txsPromise.catch(()=>{});
468
+ bundlePromise.catch(()=>{});
469
+ const [collected, l1ToL2Messages] = await Promise.all([
470
+ txsPromise,
471
+ bundlePromise
472
+ ]);
473
+ if (collected === 'invalid_embedded_txs') {
474
+ return {
475
+ isValid: false,
476
+ blockNumber,
477
+ reason: collected
478
+ };
479
+ }
480
+ const { txs, missingTxs } = collected;
481
+ // Record the tx-collection outcome on the re-execution tracker
482
+ this.reexecutionTracker.recordTxsCollected(slotNumber, proposal.indexWithinCheckpoint, missingTxs.length === 0);
483
+ // If reexecution is disabled, bail. We were just interested in triggering tx collection.
484
+ if (!shouldReexecute) {
485
+ this.log.info(`Received valid block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, proposalInfo);
486
+ return {
487
+ isValid: true,
488
+ blockNumber
489
+ };
490
+ }
491
+ // Compute the checkpoint number for this block and validate checkpoint consistency
492
+ const checkpointResult = this.computeCheckpointNumber(proposal, parentBlock, proposalInfo);
493
+ if (checkpointResult.reason) {
494
+ return {
495
+ isValid: false,
496
+ blockNumber,
497
+ reason: checkpointResult.reason
498
+ };
499
+ }
500
+ const checkpointNumber = checkpointResult.checkpointNumber;
501
+ proposalInfo.checkpointNumber = checkpointNumber;
502
+ // Check that all of the transactions in the proposal are available
503
+ if (missingTxs.length > 0) {
504
+ this.log.warn(`Missing ${missingTxs.length} txs to process proposal`, {
505
+ ...proposalInfo,
506
+ missingTxs
507
+ });
508
+ return {
509
+ isValid: false,
510
+ blockNumber,
511
+ reason: 'txs_not_available'
512
+ };
513
+ }
514
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
515
+ // Mirror the proposer-side fallback: under pipelining the immediately-preceding cp may not
516
+ // yet be on L1, in which case the helper grafts the locally-known proposed cp's outHash.
517
+ const epoch = getEpochAtSlot(slotNumber, this.epochCache.getL1Constants());
518
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
519
+ blockSource: this.blockSource,
520
+ epoch,
521
+ checkpointNumber,
522
+ l1Constants: this.epochCache.getL1Constants(),
523
+ pipeliningEnabled: true,
524
+ log: this.log
525
+ });
526
+ const previousInboxRollingHash = await getPreviousCheckpointInboxRollingHash({
527
+ blockSource: this.blockSource,
528
+ checkpointNumber,
529
+ log: this.log
530
+ });
531
+ // Try re-executing the transactions in the proposal if needed
532
+ let reexecutionResult;
533
+ try {
534
+ this.log.verbose(`Re-executing transactions in the proposal`, proposalInfo);
535
+ reexecutionResult = await this.reexecuteTransactions(proposal, blockNumber, checkpointNumber, txs, l1ToL2Messages, previousCheckpointOutHashes, previousInboxRollingHash);
536
+ } catch (error) {
537
+ this.log.error(`Error reexecuting txs while processing block proposal`, error, proposalInfo);
538
+ const reason = this.getReexecuteFailureReason(error);
539
+ return {
540
+ isValid: false,
541
+ blockNumber,
542
+ reason,
543
+ reexecutionResult
544
+ };
545
+ }
546
+ // If we succeeded, push this block into the archiver (unless disabled)
547
+ if (reexecutionResult?.block && !this.config.skipPushProposedBlocksToArchiver) {
548
+ await this.blockSource.addBlock(reexecutionResult.block);
549
+ }
550
+ this.log.info(`Successfully re-executed block ${blockNumber} proposal at index ${proposal.indexWithinCheckpoint} on slot ${slotNumber}`, {
551
+ ...proposalInfo,
552
+ ...pick(reexecutionResult, 'reexecutionTimeMs', 'totalManaUsed')
553
+ });
554
+ return {
555
+ isValid: true,
556
+ blockNumber,
557
+ reexecutionResult
558
+ };
559
+ }
560
+ /**
561
+ * Collects the txs for a proposal, returning `invalid_embedded_txs` if the proposal carries a tx that fails
562
+ * minimum integrity validation. That is proposer misbehavior — the proposal signs both the tx hashes and the
563
+ * tx objects — so the caller turns it into an invalid-proposal result that reaches slashing and invalid-slot
564
+ * accounting, rather than letting it escape as an exception. Any other collection error is a local failure
565
+ * and keeps propagating.
566
+ */ async collectProposalTxs(proposal, blockNumber, proposalSender, proposalInfo) {
567
+ try {
568
+ return await this.txProvider.getTxsForBlockProposal(proposal, blockNumber, {
569
+ pinnedPeer: proposalSender,
570
+ deadline: this.getReexecutionDeadline(proposal.slotNumber)
571
+ });
572
+ } catch (error) {
573
+ if (!isErrorClass(error, InvalidBlockProposalTxsError)) {
574
+ throw error;
575
+ }
576
+ this.log.warn(`Block proposal carries ${error.invalidTxs.length} invalid txs`, {
577
+ ...proposalInfo,
578
+ invalidTxs: error.invalidTxs.map(({ txHash, reasons })=>({
579
+ txHash: txHash.toString(),
580
+ reasons
581
+ }))
582
+ });
583
+ return 'invalid_embedded_txs';
584
+ }
585
+ }
586
+ async validateNewBlockInSlot(blockProposal) {
587
+ if (!this.p2pClient) {
588
+ return {
589
+ isValid: true
590
+ };
591
+ }
592
+ const { blockProposals, checkpointProposals } = await this.p2pClient.getProposalsForSlot(blockProposal.slotNumber);
593
+ if (checkpointProposals.length === 0) {
594
+ return {
595
+ isValid: true
596
+ };
597
+ } else if (checkpointProposals.length > 1) {
598
+ return {
599
+ isValid: false,
600
+ reason: 'checkpoint_proposal_equivocation'
601
+ };
602
+ } else {
603
+ const checkpointProposal = checkpointProposals[0];
604
+ const terminalBlock = blockProposals.find((block)=>block.archive.equals(checkpointProposal.archive));
605
+ return terminalBlock !== undefined && blockProposal.indexWithinCheckpoint > terminalBlock.indexWithinCheckpoint ? {
606
+ isValid: false,
607
+ reason: 'block_proposal_beyond_checkpoint'
608
+ } : {
609
+ isValid: true
610
+ };
611
+ }
612
+ }
613
+ async getParentBlock(proposal) {
614
+ const parentArchive = proposal.blockHeader.lastArchive.root;
615
+ const { genesisArchiveRoot } = await this.blockSource.getGenesisValues();
616
+ if (parentArchive.equals(genesisArchiveRoot)) {
617
+ return 'genesis';
618
+ }
619
+ const deadline = this.getReexecutionDeadline(proposal.slotNumber);
620
+ const timeoutDurationMs = deadline.getTime() - this.dateProvider.now();
621
+ try {
622
+ return await this.blockSource.getBlockData({
623
+ archive: parentArchive
624
+ }) ?? (timeoutDurationMs <= 0 ? undefined : await retryUntil(()=>this.blockSource.syncImmediate().then(()=>this.blockSource.getBlockData({
625
+ archive: parentArchive
626
+ })), 'force archiver sync', {
627
+ deadline,
628
+ dateProvider: this.dateProvider
629
+ }, 0.5));
630
+ } catch (err) {
631
+ if (err instanceof TimeoutError) {
632
+ this.log.debug(`Timed out getting parent block by archive root`, {
633
+ parentArchive
634
+ });
635
+ } else {
636
+ this.log.error('Error getting parent block by archive root', err, {
637
+ parentArchive
638
+ });
639
+ }
640
+ return undefined;
641
+ }
642
+ }
643
+ /**
644
+ * Resolves whether a block genuinely already exists at `blockNumber`. Returns the existing block only if
645
+ * it is a true duplicate of the proposal (matching archive). During a reorg the archiver can still hold a
646
+ * stale fork at this number (different archive) that is about to be pruned; in that case this forces L1
647
+ * sync and waits, bounded by the re-execution deadline, for the prune to land, then returns `undefined` so
648
+ * the rebuilt block proposal can be processed in time to attest. If the prune does not complete before the
649
+ * deadline it returns the stale block, so the caller falls back to the safe `block_number_already_exists`
650
+ * rejection.
651
+ */ async resolveExistingBlockAtNumber(blockNumber, proposalArchive, slotNumber) {
652
+ const existingBlock = await this.blockSource.getBlockData({
653
+ number: blockNumber
654
+ });
655
+ if (!existingBlock || existingBlock.archive.root.equals(proposalArchive)) {
656
+ return existingBlock;
657
+ }
658
+ // A different block already occupies this number: it may be a stale fork being pruned during a reorg, not a
659
+ // genuine duplicate. Wait for the local prune rather than permanently rejecting the proposal.
660
+ const deadline = this.getReexecutionDeadline(slotNumber);
661
+ if (deadline.getTime() - this.dateProvider.now() <= 0) {
662
+ return existingBlock;
663
+ }
664
+ this.log.warn(`Block number ${blockNumber} already exists, awaiting potential prune`, {
665
+ blockNumber,
666
+ existingArchive: existingBlock.archive.root.toString(),
667
+ proposalArchive: proposalArchive.toString()
668
+ });
669
+ try {
670
+ const { block } = await retryUntil(async ()=>{
671
+ await this.blockSource.syncImmediate();
672
+ const block = await this.blockSource.getBlockData({
673
+ number: blockNumber
674
+ });
675
+ // Resolve once the existing block is gone (pruned) or has been replaced by one matching the
676
+ // proposal — the same condition as the early return above. A matching block is returned so the
677
+ // caller still treats it as a genuine duplicate; an `undefined` (pruned) block lets the proposal
678
+ // be processed. Wrap in an object so the `undefined` case is still a truthy retry result.
679
+ return block === undefined || block.archive.root.equals(proposalArchive) ? {
680
+ block
681
+ } : undefined;
682
+ }, `prune of stale block ${blockNumber}`, {
683
+ deadline,
684
+ dateProvider: this.dateProvider
685
+ }, 0.5);
686
+ return block;
687
+ } catch (err) {
688
+ if (err instanceof TimeoutError) {
689
+ this.log.warn(`Timed out waiting for stale block ${blockNumber} to be pruned`, {
690
+ blockNumber
691
+ });
692
+ return existingBlock;
693
+ }
694
+ throw err;
695
+ }
696
+ }
697
+ computeCheckpointNumber(proposal, parentBlock, proposalInfo) {
698
+ if (parentBlock === 'genesis') {
699
+ // First block is in checkpoint 1
700
+ if (proposal.indexWithinCheckpoint !== 0) {
701
+ this.log.warn(`First block proposal has non-zero indexWithinCheckpoint`, proposalInfo);
702
+ return {
703
+ reason: 'invalid_proposal'
704
+ };
705
+ }
706
+ return {
707
+ checkpointNumber: CheckpointNumber.INITIAL
708
+ };
709
+ }
710
+ if (proposal.indexWithinCheckpoint === 0) {
711
+ // If this is the first block in a new checkpoint, increment the checkpoint number
712
+ if (!(proposal.blockHeader.getSlot() > parentBlock.header.getSlot())) {
713
+ this.log.warn(`Slot should be greater than parent block slot for first block in checkpoint`, proposalInfo);
714
+ return {
715
+ reason: 'invalid_proposal'
716
+ };
717
+ }
718
+ return {
719
+ checkpointNumber: CheckpointNumber(parentBlock.checkpointNumber + 1)
720
+ };
721
+ }
722
+ // Otherwise it should follow the previous block in the same checkpoint
723
+ if (proposal.indexWithinCheckpoint !== parentBlock.indexWithinCheckpoint + 1) {
724
+ this.log.warn(`Non-sequential indexWithinCheckpoint`, proposalInfo);
725
+ return {
726
+ reason: 'invalid_proposal'
727
+ };
728
+ }
729
+ if (proposal.blockHeader.getSlot() !== parentBlock.header.getSlot()) {
730
+ this.log.warn(`Slot should be equal to parent block slot for non-first block in checkpoint`, proposalInfo);
731
+ return {
732
+ reason: 'invalid_proposal'
733
+ };
734
+ }
735
+ // For non-first blocks in a checkpoint, validate global variables match parent (except blockNumber)
736
+ const validationResult = this.validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo);
737
+ if (validationResult) {
738
+ return validationResult;
739
+ }
740
+ return {
741
+ checkpointNumber: parentBlock.checkpointNumber
742
+ };
743
+ }
744
+ /**
745
+ * Validates that a non-first block in a checkpoint has consistent global variables with its parent.
746
+ * For blocks with indexWithinCheckpoint > 0, all global variables except blockNumber must match the parent.
747
+ * @returns A failure result if validation fails, undefined if validation passes
748
+ */ validateNonFirstBlockInCheckpoint(proposal, parentBlock, proposalInfo) {
749
+ const proposalGlobals = proposal.blockHeader.globalVariables;
750
+ const parentGlobals = parentBlock.header.globalVariables;
751
+ // All global variables except blockNumber should match the parent
752
+ // blockNumber naturally increments between blocks
753
+ if (!proposalGlobals.chainId.equals(parentGlobals.chainId)) {
754
+ this.log.warn(`Non-first block in checkpoint has mismatched chainId`, {
755
+ ...proposalInfo,
756
+ proposalChainId: proposalGlobals.chainId.toString(),
757
+ parentChainId: parentGlobals.chainId.toString()
758
+ });
759
+ return {
760
+ reason: 'global_variables_mismatch'
761
+ };
762
+ }
763
+ if (!proposalGlobals.version.equals(parentGlobals.version)) {
764
+ this.log.warn(`Non-first block in checkpoint has mismatched version`, {
765
+ ...proposalInfo,
766
+ proposalVersion: proposalGlobals.version.toString(),
767
+ parentVersion: parentGlobals.version.toString()
768
+ });
769
+ return {
770
+ reason: 'global_variables_mismatch'
771
+ };
772
+ }
773
+ if (proposalGlobals.slotNumber !== parentGlobals.slotNumber) {
774
+ this.log.warn(`Non-first block in checkpoint has mismatched slotNumber`, {
775
+ ...proposalInfo,
776
+ proposalSlotNumber: proposalGlobals.slotNumber,
777
+ parentSlotNumber: parentGlobals.slotNumber
778
+ });
779
+ return {
780
+ reason: 'global_variables_mismatch'
781
+ };
782
+ }
783
+ if (proposalGlobals.timestamp !== parentGlobals.timestamp) {
784
+ this.log.warn(`Non-first block in checkpoint has mismatched timestamp`, {
785
+ ...proposalInfo,
786
+ proposalTimestamp: proposalGlobals.timestamp.toString(),
787
+ parentTimestamp: parentGlobals.timestamp.toString()
788
+ });
789
+ return {
790
+ reason: 'global_variables_mismatch'
791
+ };
792
+ }
793
+ if (!proposalGlobals.coinbase.equals(parentGlobals.coinbase)) {
794
+ this.log.warn(`Non-first block in checkpoint has mismatched coinbase`, {
795
+ ...proposalInfo,
796
+ proposalCoinbase: proposalGlobals.coinbase.toString(),
797
+ parentCoinbase: parentGlobals.coinbase.toString()
798
+ });
799
+ return {
800
+ reason: 'global_variables_mismatch'
801
+ };
802
+ }
803
+ if (!proposalGlobals.feeRecipient.equals(parentGlobals.feeRecipient)) {
804
+ this.log.warn(`Non-first block in checkpoint has mismatched feeRecipient`, {
805
+ ...proposalInfo,
806
+ proposalFeeRecipient: proposalGlobals.feeRecipient.toString(),
807
+ parentFeeRecipient: parentGlobals.feeRecipient.toString()
808
+ });
809
+ return {
810
+ reason: 'global_variables_mismatch'
811
+ };
812
+ }
813
+ if (!proposalGlobals.gasFees.equals(parentGlobals.gasFees)) {
814
+ this.log.warn(`Non-first block in checkpoint has mismatched gasFees`, {
815
+ ...proposalInfo,
816
+ proposalGasFees: proposalGlobals.gasFees.toInspect(),
817
+ parentGasFees: parentGlobals.gasFees.toInspect()
818
+ });
819
+ return {
820
+ reason: 'global_variables_mismatch'
821
+ };
822
+ }
823
+ return undefined;
824
+ }
825
+ /**
826
+ * Hard re-execution/validation deadline for any block or checkpoint proposal targeting `slotNumber`:
827
+ * the single consensus `attestation_deadline` (`target_slot_start + S - 2E`). This is the latest the
828
+ * checkpoint can land on L1 in the target slot; all nodes agree on it. Loosened from the previous
829
+ * next-wall-clock-slot-boundary bound (see the timetable spec / refactor notes).
830
+ */ getReexecutionDeadline(slotNumber) {
831
+ return new Date(this.timetable.getAttestationDeadline(slotNumber) * 1000);
832
+ }
833
+ getReexecuteFailureReason(err) {
834
+ if (err instanceof TransactionsNotAvailableError) {
835
+ return 'txs_not_available';
836
+ } else if (err instanceof ReExInitialStateMismatchError) {
837
+ return 'initial_state_mismatch';
838
+ } else if (err instanceof ReExStateMismatchError) {
839
+ return 'state_mismatch';
840
+ } else if (err instanceof ReExFailedTxsError) {
841
+ return 'failed_txs';
842
+ } else if (err instanceof ReExTimeoutError) {
843
+ return 'timeout';
844
+ } else {
845
+ return 'unknown_error';
846
+ }
847
+ }
848
+ /**
849
+ * Runs the streaming-Inbox per-block metadata checks for a block proposal, returning the bucket range its message
850
+ * bundle derives from or a rejection reason. The parent block's consumed total and the checkpoint's starting total
851
+ * are derived from L1-to-L2 tree leaf counts; a parent whose count does not sit on a bucket boundary is rejected
852
+ * inside {@link checkStreamingBlockProposalMetadata}.
853
+ */ async checkStreamingBlockMetadata(proposal, blockNumber, parentBlock) {
854
+ const parentTotalMsgCount = this.getConsumedMsgTotal(parentBlock);
855
+ const checkpointStartTotalMsgCount = await this.resolveCheckpointStartTotal(blockNumber, proposal.indexWithinCheckpoint, parentTotalMsgCount);
856
+ if (checkpointStartTotalMsgCount === undefined) {
857
+ // The block before the checkpoint's first block has not synced locally, so the per-checkpoint cap origin is
858
+ // unavailable: treat as an unknown local view. There is no bounded wait for the missing block yet.
859
+ return {
860
+ accepted: false,
861
+ reason: 'bucket_unknown'
862
+ };
863
+ }
864
+ const nowSeconds = BigInt(Math.floor(this.dateProvider.now() / 1000));
865
+ return checkStreamingBlockProposalMetadata({
866
+ messageSource: this.l1ToL2MessageSource,
867
+ bucketRef: proposal.bucketRef,
868
+ parentTotalMsgCount,
869
+ checkpointStartTotalMsgCount,
870
+ nowSeconds,
871
+ minBucketAgeSeconds: this.epochCache.getL1Constants().ethereumSlotDuration,
872
+ perBlockCap: MAX_L1_TO_L2_MSGS_PER_BLOCK,
873
+ perCheckpointCap: MAX_L1_TO_L2_MSGS_PER_CHECKPOINT
874
+ });
875
+ }
876
+ /** A block's L1-to-L2 message tree leaf count: the cumulative Inbox message count it consumed through. */ blockLeafCount(block) {
877
+ return BigInt(block.header.state.l1ToL2MessageTree.nextAvailableLeafIndex);
878
+ }
879
+ /** The cumulative Inbox message count consumed through a block: its L1-to-L2 tree leaf count (0 at genesis). */ getConsumedMsgTotal(block) {
880
+ return block === 'genesis' ? 0n : this.blockLeafCount(block);
881
+ }
882
+ /**
883
+ * The cumulative Inbox message count consumed as of the parent checkpoint (the per-checkpoint cap origin). For a
884
+ * checkpoint's first block this is the parent block's total; for a later block it is the leaf count of the block
885
+ * before the checkpoint's first block. Returns undefined when that block has not synced locally.
886
+ */ resolveCheckpointStartTotal(blockNumber, indexWithinCheckpoint, parentTotalMsgCount) {
887
+ return indexWithinCheckpoint === 0 ? Promise.resolve(parentTotalMsgCount) : this.getPreBlockConsumedTotal(blockNumber - indexWithinCheckpoint);
888
+ }
889
+ /**
890
+ * The cumulative Inbox message count consumed as of the block immediately before `firstBlockNumber` (its L1-to-L2
891
+ * tree leaf count): 0 when that block is genesis, undefined when it has not synced locally.
892
+ */ async getPreBlockConsumedTotal(firstBlockNumber) {
893
+ const preBlockNumber = firstBlockNumber - 1;
894
+ if (preBlockNumber < INITIAL_L2_BLOCK_NUM) {
895
+ return 0n;
896
+ }
897
+ const preBlock = await this.blockSource.getBlockData({
898
+ number: BlockNumber(preBlockNumber)
899
+ });
900
+ return preBlock === undefined ? undefined : this.blockLeafCount(preBlock);
901
+ }
902
+ /**
903
+ * Enforces the streaming-Inbox last-block minimum-consumption (censorship) rule for a checkpoint, mirroring
904
+ * `ProposeLib.validateInboxConsumption`: the first bucket the checkpoint left unconsumed must be absent, past the
905
+ * cutoff, or a cap-escape. Returns true (sufficient) when the checkpoint's consumption cannot be resolved against
906
+ * the local Inbox view, deferring to L1 `propose` as the authoritative reject.
907
+ */ async isLastBlockConsumptionSufficient(slot, blocks) {
908
+ const lastBlockTotal = this.blockLeafCount(blocks[blocks.length - 1]);
909
+ const checkpointStartTotal = await this.getPreBlockConsumedTotal(blocks[0].number);
910
+ const lastConsumedBucket = await this.l1ToL2MessageSource.getInboxBucketByTotalMsgCount(lastBlockTotal);
911
+ if (checkpointStartTotal === undefined || lastConsumedBucket === undefined) {
912
+ return true;
913
+ }
914
+ const nextBucket = await this.l1ToL2MessageSource.getInboxBucket(lastConsumedBucket.seq + 1n);
915
+ const cutoffTimestamp = getInboxCutoffTimestamp(slot, this.epochCache.getL1Constants());
916
+ return isInboxConsumptionSufficient({
917
+ nextBucket,
918
+ cutoffTimestamp,
919
+ checkpointStartTotalMsgCount: checkpointStartTotal,
920
+ perCheckpointCap: MAX_L1_TO_L2_MSGS_PER_CHECKPOINT
921
+ });
922
+ }
923
+ /**
924
+ * Derives the ordered list of L1-to-L2 messages a checkpoint consumed across its blocks, from the Inbox buckets
925
+ * between the parent checkpoint's consumed position and the checkpoint's last block. Empty when
926
+ * the checkpoint consumed nothing or its consumption cannot be resolved against the local Inbox view.
927
+ */ async deriveCheckpointConsumedMessages(blocks) {
928
+ const checkpointStartTotal = await this.getPreBlockConsumedTotal(blocks[0].number);
929
+ const lastBlockTotal = this.blockLeafCount(blocks[blocks.length - 1]);
930
+ if (checkpointStartTotal === undefined || lastBlockTotal <= checkpointStartTotal) {
931
+ return [];
932
+ }
933
+ const startBucket = await this.l1ToL2MessageSource.getInboxBucketByTotalMsgCount(checkpointStartTotal);
934
+ const endBucket = await this.l1ToL2MessageSource.getInboxBucketByTotalMsgCount(lastBlockTotal);
935
+ if (startBucket === undefined || endBucket === undefined) {
936
+ return [];
937
+ }
938
+ return this.l1ToL2MessageSource.getL1ToL2MessagesBetweenBuckets(startBucket.seq, endBucket.seq);
939
+ }
940
+ async reexecuteTransactions(proposal, blockNumber, checkpointNumber, txs, l1ToL2Messages, previousCheckpointOutHashes, previousInboxRollingHash) {
941
+ const env = {
942
+ stack: [],
943
+ error: void 0,
944
+ hasError: false
945
+ };
946
+ try {
947
+ const { blockHeader, txHashes } = proposal;
948
+ // If we do not have all of the transactions, then we should fail
949
+ if (txs.length !== txHashes.length) {
950
+ const foundTxHashes = txs.map((tx)=>tx.getTxHash());
951
+ const missingTxHashes = txHashes.filter((txHash)=>!foundTxHashes.some((h)=>h.equals(txHash)));
952
+ throw new TransactionsNotAvailableError(missingTxHashes);
953
+ }
954
+ const timer = new Timer();
955
+ const slot = proposal.slotNumber;
956
+ const config = this.checkpointsBuilder.getConfig();
957
+ // Get prior blocks in this checkpoint (same slot before current block)
958
+ const allBlocksInSlot = await this.blockSource.getBlocksForSlot(slot);
959
+ const priorBlocks = allBlocksInSlot.filter((b)=>b.number < blockNumber && b.header.getSlot() === slot);
960
+ // Fork before the block to be built
961
+ const parentBlockNumber = BlockNumber(blockNumber - 1);
962
+ await this.worldState.syncImmediate(parentBlockNumber);
963
+ const fork = _ts_add_disposable_resource(env, await this.worldState.fork(parentBlockNumber), true);
964
+ // Verify the fork's archive root matches the proposal's expected last archive.
965
+ // If they don't match, our world state synced to a different chain and reexecution would fail.
966
+ const forkArchiveRoot = new Fr((await fork.getTreeInfo(MerkleTreeId.ARCHIVE)).root);
967
+ if (!forkArchiveRoot.equals(proposal.blockHeader.lastArchive.root)) {
968
+ throw new ReExInitialStateMismatchError(proposal.blockHeader.lastArchive.root, forkArchiveRoot);
969
+ }
970
+ // Build checkpoint constants from proposal (excludes blockNumber which is per-block)
971
+ const constants = {
972
+ chainId: new Fr(config.l1ChainId),
973
+ version: new Fr(config.rollupVersion),
974
+ slotNumber: slot,
975
+ timestamp: blockHeader.globalVariables.timestamp,
976
+ coinbase: blockHeader.globalVariables.coinbase,
977
+ feeRecipient: blockHeader.globalVariables.feeRecipient,
978
+ gasFees: blockHeader.globalVariables.gasFees
979
+ };
980
+ // Create checkpoint builder with prior blocks. The messages the prior blocks consumed are not needed: this path
981
+ // only re-executes and compares the new block, never completing the checkpoint (whose rolling hash they seed).
982
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, 0n, [], previousCheckpointOutHashes, previousInboxRollingHash, fork, priorBlocks, this.log.getBindings());
983
+ // Build the new block
984
+ const deadline = this.getReexecutionDeadline(slot);
985
+ const maxBlockGas = this.config.validateMaxL2BlockGas !== undefined || this.config.validateMaxDABlockGas !== undefined ? new Gas(this.config.validateMaxDABlockGas ?? Infinity, this.config.validateMaxL2BlockGas ?? Infinity) : undefined;
986
+ const result = await checkpointBuilder.buildBlock(txs, blockNumber, blockHeader.globalVariables.timestamp, {
987
+ isBuildingProposal: false,
988
+ minValidTxs: 0,
989
+ deadline,
990
+ expectedEndState: blockHeader.state,
991
+ maxTransactions: this.config.validateMaxTxsPerBlock,
992
+ maxBlockGas,
993
+ l1ToL2Messages
994
+ });
995
+ const { block, failedTxs } = result;
996
+ const numFailedTxs = failedTxs.length;
997
+ this.log.verbose(`Block proposal ${blockNumber} at slot ${slot} transaction re-execution complete`, {
998
+ numFailedTxs,
999
+ numProposalTxs: txHashes.length,
1000
+ numProcessedTxs: block.body.txEffects.length,
1001
+ blockNumber,
1002
+ slot
1003
+ });
1004
+ if (numFailedTxs > 0) {
1005
+ this.metrics?.recordFailedReexecution(proposal);
1006
+ throw new ReExFailedTxsError(numFailedTxs);
1007
+ }
1008
+ if (block.body.txEffects.length !== txHashes.length) {
1009
+ this.metrics?.recordFailedReexecution(proposal);
1010
+ throw new ReExTimeoutError();
1011
+ }
1012
+ // Throw a ReExStateMismatchError error if state updates do not match
1013
+ // Compare the full block structure (archive and header) from the built block with the proposal
1014
+ const archiveMatches = proposal.archive.equals(block.archive.root);
1015
+ const headerMatches = proposal.blockHeader.equals(block.header);
1016
+ if (!archiveMatches || !headerMatches) {
1017
+ this.log.warn(`Re-execution state mismatch for slot ${slot}`, {
1018
+ expectedArchive: block.archive.root.toString(),
1019
+ actualArchive: proposal.archive.toString(),
1020
+ expectedHeader: block.header.toInspect(),
1021
+ actualHeader: proposal.blockHeader.toInspect()
1022
+ });
1023
+ this.metrics?.recordFailedReexecution(proposal);
1024
+ throw new ReExStateMismatchError(proposal.archive, block.archive.root);
1025
+ }
1026
+ const reexecutionTimeMs = timer.ms();
1027
+ const totalManaUsed = block.header.totalManaUsed.toNumber() / 1e6;
1028
+ this.metrics?.recordReex(reexecutionTimeMs, txs.length, totalManaUsed);
1029
+ return {
1030
+ block,
1031
+ failedTxs,
1032
+ reexecutionTimeMs,
1033
+ totalManaUsed
1034
+ };
1035
+ } catch (e) {
1036
+ env.error = e;
1037
+ env.hasError = true;
1038
+ } finally{
1039
+ const result = _ts_dispose_resources(env);
1040
+ if (result) await result;
1041
+ }
1042
+ }
1043
+ /**
1044
+ * Validates a checkpoint proposal, caches the result, and uploads blobs if configured.
1045
+ * Returns a cached result if the same proposal (archive + slot) was already validated.
1046
+ * Used by both the all-nodes callback (via register) and the validator client (via delegation).
1047
+ * Expects the proposal to have already passed p2p ingress validation (expected proposer and receive-window
1048
+ * timeliness); only deterministic properties of the signed payload are checked here.
1049
+ */ async handleCheckpointProposal(proposal, proposalInfo) {
1050
+ const slot = proposal.slotNumber;
1051
+ const payloadHash = proposal.getPayloadHash();
1052
+ // Check cache: same signed-payload hash means we already validated this exact proposal.
1053
+ if (this.lastCheckpointValidationResult && this.lastCheckpointValidationResult.payloadHash === payloadHash) {
1054
+ this.log.debug(`Returning cached validation result for checkpoint proposal at slot ${slot}`, proposalInfo);
1055
+ return this.lastCheckpointValidationResult.result;
1056
+ }
1057
+ const proposer = proposal.getSender();
1058
+ let result;
1059
+ if (!proposer) {
1060
+ this.log.warn(`Received checkpoint proposal with invalid signature for slot ${proposal.slotNumber}`);
1061
+ result = {
1062
+ isValid: false,
1063
+ reason: 'invalid_signature'
1064
+ };
1065
+ } else if (!validateFeeAssetPriceModifier(proposal.feeAssetPriceModifier)) {
1066
+ this.log.warn(`Received checkpoint proposal with invalid feeAssetPriceModifier ${proposal.feeAssetPriceModifier} for slot ${proposal.slotNumber}`);
1067
+ result = {
1068
+ isValid: false,
1069
+ reason: 'invalid_fee_asset_price_modifier'
1070
+ };
1071
+ } else {
1072
+ result = await this.validateCheckpointProposal(proposal, proposalInfo);
1073
+ }
1074
+ this.lastCheckpointValidationResult = {
1075
+ payloadHash,
1076
+ result
1077
+ };
1078
+ // Record the outcome on the re-execution tracker.
1079
+ const outcome = result.isValid ? 'valid' : CHECKPOINT_VALIDATION_REASON_TO_OUTCOME[result.reason];
1080
+ if (outcome !== undefined) {
1081
+ this.reexecutionTracker.recordOutcome(slot, proposal.archive, outcome, result.checkpointNumber);
1082
+ }
1083
+ // Drop tracker entries for checkpoints that have reached L1 finality.
1084
+ try {
1085
+ const tips = await this.blockSource.getL2Tips();
1086
+ const finalizedCheckpointNumber = tips.finalized.checkpoint.number;
1087
+ if (finalizedCheckpointNumber > 0) {
1088
+ this.reexecutionTracker.removeBefore(CheckpointNumber(finalizedCheckpointNumber + 1));
1089
+ }
1090
+ } catch (err) {
1091
+ this.log.error(`Error pruning reexecution tracker`, err, proposalInfo);
1092
+ }
1093
+ // Upload blobs to filestore if validation passed (fire and forget)
1094
+ if (result.isValid) {
1095
+ this.tryUploadBlobsForCheckpoint(proposal, proposalInfo);
1096
+ }
1097
+ return result;
1098
+ }
1099
+ /**
1100
+ * Validates a checkpoint proposal by building the full checkpoint and comparing it with the proposal.
1101
+ * @returns Validation result with isValid flag and reason if invalid.
1102
+ */ async validateCheckpointProposal(proposal, proposalInfo) {
1103
+ const env = {
1104
+ stack: [],
1105
+ error: void 0,
1106
+ hasError: false
1107
+ };
1108
+ try {
1109
+ const slot = proposal.slotNumber;
1110
+ // Block-sync/validation deadline = the single consensus attestation_deadline (target_slot_start + S
1111
+ // - 2E): the latest moment the proposer can submit this checkpoint and still have it land on L1 in
1112
+ // the target slot. Keeping validation/attestation alive until then lets validators keep attesting
1113
+ // right up to the proposer's real publish cutoff.
1114
+ const deadline = this.getReexecutionDeadline(slot);
1115
+ // Wait for last block to sync by archive. The deadline is passed to retryUntil as an absolute date so
1116
+ // the remaining budget is derived from the date provider; a deadline already in the past times out
1117
+ // after a single attempt instead of looping (the immediate-timeout semantics of the deadline overload).
1118
+ let lastBlockData;
1119
+ try {
1120
+ lastBlockData = await retryUntil(async ()=>{
1121
+ await this.blockSource.syncImmediate();
1122
+ return await this.blockSource.getBlockData({
1123
+ archive: proposal.archive
1124
+ });
1125
+ }, `waiting for block with archive ${proposal.archive.toString()} for slot ${slot}`, {
1126
+ deadline,
1127
+ dateProvider: this.dateProvider
1128
+ }, 0.5);
1129
+ } catch (err) {
1130
+ if (err instanceof TimeoutError) {
1131
+ this.log.warn(`Timed out waiting for block with archive matching checkpoint proposal`, proposalInfo);
1132
+ return {
1133
+ isValid: false,
1134
+ reason: 'last_block_not_found'
1135
+ };
1136
+ }
1137
+ this.log.error(`Error fetching last block for checkpoint proposal`, err, proposalInfo);
1138
+ return {
1139
+ isValid: false,
1140
+ reason: 'block_fetch_error'
1141
+ };
1142
+ }
1143
+ if (!lastBlockData) {
1144
+ this.log.warn(`Last block not found for checkpoint proposal`, proposalInfo);
1145
+ return {
1146
+ isValid: false,
1147
+ reason: 'last_block_not_found'
1148
+ };
1149
+ }
1150
+ // Refuse to attest if the block's enclosing checkpoint has already been published to L1.
1151
+ const existingCheckpoint = await this.blockSource.getCheckpointData({
1152
+ number: lastBlockData.checkpointNumber
1153
+ });
1154
+ if (existingCheckpoint) {
1155
+ this.log.warn(`Refusing to attest to checkpoint proposal whose checkpoint is already on L1`, {
1156
+ ...proposalInfo,
1157
+ checkpointNumber: lastBlockData.checkpointNumber
1158
+ });
1159
+ return {
1160
+ isValid: false,
1161
+ reason: 'checkpoint_already_published',
1162
+ checkpointNumber: lastBlockData.checkpointNumber
1163
+ };
1164
+ }
1165
+ // Get all full blocks for the slot and checkpoint
1166
+ const blocks = await this.blockSource.getBlocksForSlot(slot);
1167
+ if (blocks.length === 0) {
1168
+ this.log.warn(`No blocks found for slot ${slot}`, proposalInfo);
1169
+ return {
1170
+ isValid: false,
1171
+ reason: 'no_blocks_for_slot',
1172
+ checkpointNumber: lastBlockData.checkpointNumber
1173
+ };
1174
+ }
1175
+ // Ensure the last block for this slot matches the archive in the checkpoint proposal
1176
+ if (!blocks.at(-1)?.archive.root.equals(proposal.archive)) {
1177
+ this.log.warn(`Last block archive mismatch for checkpoint proposal`, proposalInfo);
1178
+ return {
1179
+ isValid: false,
1180
+ reason: 'last_block_archive_mismatch',
1181
+ checkpointNumber: lastBlockData.checkpointNumber
1182
+ };
1183
+ }
1184
+ // The checkpoint root circuit caps how many blocks a checkpoint may contain, and L1 cannot check it when the
1185
+ // checkpoint is proposed (`ProposedHeader` carries no block count, only `blockHeadersHash`). An over-cap
1186
+ // checkpoint would therefore be accepted on L1 and then be unprovable, forcing an epoch reorg, so validators
1187
+ // reject it before attesting. An operator-configured limit may only tighten the protocol cap, never relax it.
1188
+ const maxBlocksPerCheckpoint = Math.min(this.config.maxBlocksPerCheckpoint ?? MAX_BLOCKS_PER_CHECKPOINT, MAX_BLOCKS_PER_CHECKPOINT);
1189
+ if (blocks.length > maxBlocksPerCheckpoint) {
1190
+ this.log.warn(`Checkpoint proposal exceeds maxBlocksPerCheckpoint`, {
1191
+ ...proposalInfo,
1192
+ blocksInProposal: blocks.length,
1193
+ maxBlocksPerCheckpoint
1194
+ });
1195
+ return {
1196
+ isValid: false,
1197
+ reason: 'too_many_blocks_in_checkpoint',
1198
+ checkpointNumber: lastBlockData.checkpointNumber
1199
+ };
1200
+ }
1201
+ this.log.debug(`Found ${blocks.length} blocks for slot ${slot}`, {
1202
+ ...proposalInfo,
1203
+ blockNumbers: blocks.map((b)=>b.number)
1204
+ });
1205
+ // Get checkpoint constants from first block
1206
+ const firstBlock = blocks[0];
1207
+ const constants = this.extractCheckpointConstants(firstBlock);
1208
+ const checkpointNumber = firstBlock.checkpointNumber;
1209
+ // Streaming Inbox: on the last block of a checkpoint, enforce the minimum-consumption
1210
+ // (censorship) rule before attesting. Reject (no attestation) if a mandatory bucket was left unconsumed.
1211
+ if (!await this.isLastBlockConsumptionSufficient(slot, blocks)) {
1212
+ this.log.warn(`Streaming Inbox last-block censorship check failed, refusing to attest`, {
1213
+ ...proposalInfo,
1214
+ checkpointNumber
1215
+ });
1216
+ return {
1217
+ isValid: false,
1218
+ reason: 'inbox_consumption_insufficient',
1219
+ checkpointNumber
1220
+ };
1221
+ }
1222
+ // Derive the checkpoint's consumed L1-to-L2 message list from the Inbox buckets between the parent checkpoint's
1223
+ // consumed position and the last block's (compact indexing). The messages are already in the db from per-block
1224
+ // validation; this list only drives the checkpoint's rolling-hash recomputation in completeCheckpoint.
1225
+ const l1ToL2Messages = await this.deriveCheckpointConsumedMessages(blocks);
1226
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
1227
+ // See note on the analogous block-proposal site: the helper handles pipelining lag.
1228
+ const epoch = getEpochAtSlot(slot, this.epochCache.getL1Constants());
1229
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
1230
+ blockSource: this.blockSource,
1231
+ epoch,
1232
+ checkpointNumber,
1233
+ l1Constants: this.epochCache.getL1Constants(),
1234
+ pipeliningEnabled: true,
1235
+ log: this.log
1236
+ });
1237
+ const previousInboxRollingHash = await getPreviousCheckpointInboxRollingHash({
1238
+ blockSource: this.blockSource,
1239
+ checkpointNumber,
1240
+ log: this.log
1241
+ });
1242
+ // Fork world state at the block before the first block. getFork syncs world state to the parent block
1243
+ // first (see its doc): the block source (archiver) can already hold the block while world state still
1244
+ // trails it by one, and forking a not-yet-applied block throws a raw tree error that would otherwise
1245
+ // escape as an uncaught gossipsub error. We pass the parent's expected block hash so the sync detects a
1246
+ // world-state reorg (undefined for the genesis parent, where no block exists to pin). On failure we map
1247
+ // to a clean validation result rather than letting it escape.
1248
+ const parentBlockNumber = BlockNumber(firstBlock.number - 1);
1249
+ let forkResult;
1250
+ try {
1251
+ const parentBlockHash = (await this.blockSource.getBlockData({
1252
+ number: parentBlockNumber
1253
+ }))?.blockHash;
1254
+ forkResult = await this.checkpointsBuilder.getFork(parentBlockNumber, parentBlockHash);
1255
+ } catch (err) {
1256
+ this.log.warn(`Failed to fork world state at block ${parentBlockNumber} for checkpoint proposal`, {
1257
+ ...proposalInfo,
1258
+ parentBlockNumber,
1259
+ err
1260
+ });
1261
+ return {
1262
+ isValid: false,
1263
+ reason: 'world_state_not_synced',
1264
+ checkpointNumber
1265
+ };
1266
+ }
1267
+ const fork = _ts_add_disposable_resource(env, forkResult, true);
1268
+ // Verify the fork's archive root matches the checkpoint's expected starting archive (the archive after
1269
+ // the parent block). A mismatch means world state forked from a different chain than the proposal was
1270
+ // built on (e.g. a reorg), so recomputing the checkpoint against it would be meaningless. This mirrors
1271
+ // the block-proposal re-execution check and fails fast with a clean, non-slashable result instead of a
1272
+ // confusing downstream mismatch.
1273
+ const forkArchiveRoot = new Fr((await fork.getTreeInfo(MerkleTreeId.ARCHIVE)).root);
1274
+ if (!forkArchiveRoot.equals(proposal.checkpointHeader.lastArchiveRoot)) {
1275
+ this.log.warn(`Fork archive root does not match checkpoint proposal's last archive`, {
1276
+ ...proposalInfo,
1277
+ forkArchiveRoot: forkArchiveRoot.toString(),
1278
+ expectedLastArchiveRoot: proposal.checkpointHeader.lastArchiveRoot.toString()
1279
+ });
1280
+ return {
1281
+ isValid: false,
1282
+ reason: 'initial_archive_mismatch',
1283
+ checkpointNumber
1284
+ };
1285
+ }
1286
+ // Create checkpoint builder with all existing blocks
1287
+ const checkpointBuilder = await this.checkpointsBuilder.openCheckpoint(checkpointNumber, constants, proposal.feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, previousInboxRollingHash, fork, blocks, this.log.getBindings());
1288
+ // Complete the checkpoint to get computed values
1289
+ const computedCheckpoint = await checkpointBuilder.completeCheckpoint();
1290
+ // Compare checkpoint header with proposal
1291
+ if (!computedCheckpoint.header.equals(proposal.checkpointHeader)) {
1292
+ this.log.warn(`Checkpoint header mismatch`, {
1293
+ ...proposalInfo,
1294
+ computed: computedCheckpoint.header.toInspect(),
1295
+ proposal: proposal.checkpointHeader.toInspect()
1296
+ });
1297
+ return {
1298
+ isValid: false,
1299
+ reason: 'checkpoint_header_mismatch',
1300
+ checkpointNumber
1301
+ };
1302
+ }
1303
+ // Compare archive root with proposal
1304
+ if (!computedCheckpoint.archive.root.equals(proposal.archive)) {
1305
+ this.log.warn(`Archive root mismatch`, {
1306
+ ...proposalInfo,
1307
+ computed: computedCheckpoint.archive.root.toString(),
1308
+ proposal: proposal.archive.toString()
1309
+ });
1310
+ return {
1311
+ isValid: false,
1312
+ reason: 'archive_mismatch',
1313
+ checkpointNumber
1314
+ };
1315
+ }
1316
+ // Check that the accumulated epoch out hash matches the value in the proposal.
1317
+ // The epoch out hash is the accumulated hash of all checkpoint out hashes in the epoch.
1318
+ const checkpointOutHash = computedCheckpoint.getCheckpointOutHash();
1319
+ const computedEpochOutHash = accumulateCheckpointOutHashes([
1320
+ ...previousCheckpointOutHashes,
1321
+ checkpointOutHash
1322
+ ]);
1323
+ const proposalEpochOutHash = proposal.checkpointHeader.epochOutHash;
1324
+ if (!computedEpochOutHash.equals(proposalEpochOutHash)) {
1325
+ this.log.warn(`Epoch out hash mismatch`, {
1326
+ proposalEpochOutHash: proposalEpochOutHash.toString(),
1327
+ computedEpochOutHash: computedEpochOutHash.toString(),
1328
+ checkpointOutHash: checkpointOutHash.toString(),
1329
+ previousCheckpointOutHashes: previousCheckpointOutHashes.map((h)=>h.toString()),
1330
+ ...proposalInfo
1331
+ });
1332
+ return {
1333
+ isValid: false,
1334
+ reason: 'out_hash_mismatch',
1335
+ checkpointNumber
1336
+ };
1337
+ }
1338
+ // Final round of validations on the checkpoint, just in case.
1339
+ try {
1340
+ validateCheckpoint(computedCheckpoint, {
1341
+ rollupManaLimit: this.checkpointsBuilder.getConfig().rollupManaLimit,
1342
+ maxDABlockGas: this.config.validateMaxDABlockGas,
1343
+ maxL2BlockGas: this.config.validateMaxL2BlockGas,
1344
+ maxTxsPerBlock: this.config.validateMaxTxsPerBlock,
1345
+ maxTxsPerCheckpoint: this.config.validateMaxTxsPerCheckpoint
1346
+ });
1347
+ } catch (err) {
1348
+ this.log.warn(`Checkpoint validation failed: ${err}`, proposalInfo);
1349
+ return {
1350
+ isValid: false,
1351
+ reason: 'checkpoint_validation_failed',
1352
+ checkpointNumber
1353
+ };
1354
+ }
1355
+ this.log.verbose(`Checkpoint proposal validation successful for slot ${slot}`, proposalInfo);
1356
+ return {
1357
+ isValid: true,
1358
+ checkpointNumber
1359
+ };
1360
+ } catch (e) {
1361
+ env.error = e;
1362
+ env.hasError = true;
1363
+ } finally{
1364
+ const result = _ts_dispose_resources(env);
1365
+ if (result) await result;
1366
+ }
1367
+ }
1368
+ /** Extracts checkpoint global variables from a block. */ extractCheckpointConstants(block) {
1369
+ const gv = block.header.globalVariables;
1370
+ return {
1371
+ chainId: gv.chainId,
1372
+ version: gv.version,
1373
+ slotNumber: gv.slotNumber,
1374
+ timestamp: gv.timestamp,
1375
+ coinbase: gv.coinbase,
1376
+ feeRecipient: gv.feeRecipient,
1377
+ gasFees: gv.gasFees
1378
+ };
1379
+ }
1380
+ /** Triggers blob upload for a checkpoint if the blob client can upload (fire and forget). */ tryUploadBlobsForCheckpoint(proposal, proposalInfo) {
1381
+ if (this.blobClient.canUpload()) {
1382
+ void this.uploadBlobsForCheckpoint(proposal, proposalInfo);
1383
+ }
1384
+ }
1385
+ /** Uploads blobs for a checkpoint to the filestore. */ async uploadBlobsForCheckpoint(proposal, proposalInfo) {
1386
+ try {
1387
+ const lastBlockHeader = (await this.blockSource.getBlockData({
1388
+ archive: proposal.archive
1389
+ }))?.header;
1390
+ if (!lastBlockHeader) {
1391
+ this.log.warn(`Failed to get last block header for blob upload`, proposalInfo);
1392
+ return;
1393
+ }
1394
+ const blocks = await this.blockSource.getBlocksForSlot(proposal.slotNumber);
1395
+ if (blocks.length === 0) {
1396
+ this.log.warn(`No blocks found for blob upload`, proposalInfo);
1397
+ return;
1398
+ }
1399
+ const blockBlobData = blocks.map((b)=>b.toBlockBlobData());
1400
+ const blobFields = encodeCheckpointBlobDataFromBlocks(blockBlobData);
1401
+ const blobs = await getBlobsPerL1Block(blobFields);
1402
+ await this.blobClient.sendBlobsToFilestore(blobs);
1403
+ this.log.debug(`Uploaded ${blobs.length} blobs to filestore for checkpoint at slot ${proposal.slotNumber}`, {
1404
+ ...proposalInfo,
1405
+ numBlobs: blobs.length
1406
+ });
1407
+ } catch (err) {
1408
+ this.log.warn(`Failed to upload blobs for checkpoint: ${err}`, proposalInfo);
1409
+ }
1410
+ }
1411
+ /**
1412
+ * Derives proposed checkpoint data from validated blocks and sets it on the archiver, so this node can
1413
+ * pipeline building on top of the checkpoint. Does not retry, since validation already waited for the
1414
+ * last block to sync.
1415
+ */ async setProposedCheckpoint(proposal) {
1416
+ if (!this.archiver) {
1417
+ return false;
1418
+ }
1419
+ const blockData = await this.blockSource.getBlockData({
1420
+ archive: proposal.archive
1421
+ });
1422
+ if (!blockData) {
1423
+ this.log.debug(`Block data not found for checkpoint proposal archive, cannot set proposed checkpoint`, {
1424
+ archive: proposal.archive.toString()
1425
+ });
1426
+ return false;
1427
+ }
1428
+ await this.archiver.addProposedCheckpoint({
1429
+ header: proposal.checkpointHeader,
1430
+ checkpointNumber: blockData.checkpointNumber,
1431
+ startBlock: BlockNumber(blockData.header.getBlockNumber() - blockData.indexWithinCheckpoint),
1432
+ blockCount: blockData.indexWithinCheckpoint + 1,
1433
+ totalManaUsed: proposal.checkpointHeader.totalManaUsed.toBigInt(),
1434
+ feeAssetPriceModifier: proposal.feeAssetPriceModifier
1435
+ });
1436
+ return true;
1437
+ }
1438
+ }