@aztec/sequencer-client 0.0.1-commit.42ee6df9b → 0.0.1-commit.431c48d

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 (109) hide show
  1. package/README.md +283 -21
  2. package/dest/client/sequencer-client.d.ts +20 -5
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +26 -22
  5. package/dest/config.d.ts +13 -4
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +67 -26
  8. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  9. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  10. package/dest/global_variable_builder/fee_predictor.js +138 -0
  11. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  12. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_provider.js +80 -0
  14. package/dest/global_variable_builder/global_builder.d.ts +7 -26
  15. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  16. package/dest/global_variable_builder/global_builder.js +6 -67
  17. package/dest/global_variable_builder/index.d.ts +3 -1
  18. package/dest/global_variable_builder/index.d.ts.map +1 -1
  19. package/dest/global_variable_builder/index.js +2 -0
  20. package/dest/publisher/config.d.ts +7 -3
  21. package/dest/publisher/config.d.ts.map +1 -1
  22. package/dest/publisher/config.js +13 -3
  23. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  24. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  25. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  26. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +3 -4
  27. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -1
  28. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  29. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  30. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  31. package/dest/publisher/sequencer-publisher-factory.d.ts +1 -3
  32. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  33. package/dest/publisher/sequencer-publisher-factory.js +0 -1
  34. package/dest/publisher/sequencer-publisher.d.ts +65 -70
  35. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  36. package/dest/publisher/sequencer-publisher.js +413 -559
  37. package/dest/publisher/write_json.d.ts +11 -0
  38. package/dest/publisher/write_json.d.ts.map +1 -0
  39. package/dest/publisher/write_json.js +57 -0
  40. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  41. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  42. package/dest/sequencer/automine/automine_factory.js +85 -0
  43. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  44. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  45. package/dest/sequencer/automine/automine_sequencer.js +696 -0
  46. package/dest/sequencer/automine/index.d.ts +3 -0
  47. package/dest/sequencer/automine/index.d.ts.map +1 -0
  48. package/dest/sequencer/automine/index.js +2 -0
  49. package/dest/sequencer/checkpoint_proposal_job.d.ts +67 -36
  50. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  51. package/dest/sequencer/checkpoint_proposal_job.js +705 -256
  52. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  53. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  54. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  55. package/dest/sequencer/errors.d.ts +1 -8
  56. package/dest/sequencer/errors.d.ts.map +1 -1
  57. package/dest/sequencer/errors.js +0 -9
  58. package/dest/sequencer/events.d.ts +61 -5
  59. package/dest/sequencer/events.d.ts.map +1 -1
  60. package/dest/sequencer/metrics.d.ts +10 -11
  61. package/dest/sequencer/metrics.d.ts.map +1 -1
  62. package/dest/sequencer/metrics.js +34 -20
  63. package/dest/sequencer/requests_tracker.d.ts +22 -0
  64. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  65. package/dest/sequencer/requests_tracker.js +33 -0
  66. package/dest/sequencer/sequencer.d.ts +147 -33
  67. package/dest/sequencer/sequencer.d.ts.map +1 -1
  68. package/dest/sequencer/sequencer.js +543 -180
  69. package/dest/sequencer/types.d.ts +2 -2
  70. package/dest/sequencer/types.d.ts.map +1 -1
  71. package/dest/test/index.d.ts +3 -3
  72. package/dest/test/index.d.ts.map +1 -1
  73. package/dest/test/utils.d.ts +15 -1
  74. package/dest/test/utils.d.ts.map +1 -1
  75. package/dest/test/utils.js +25 -7
  76. package/package.json +28 -27
  77. package/src/client/sequencer-client.ts +37 -27
  78. package/src/config.ts +79 -26
  79. package/src/global_variable_builder/README.md +44 -0
  80. package/src/global_variable_builder/fee_predictor.ts +182 -0
  81. package/src/global_variable_builder/fee_provider.ts +97 -0
  82. package/src/global_variable_builder/global_builder.ts +11 -91
  83. package/src/global_variable_builder/index.ts +2 -0
  84. package/src/publisher/config.ts +30 -7
  85. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  86. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +3 -1
  87. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  88. package/src/publisher/sequencer-publisher-factory.ts +0 -3
  89. package/src/publisher/sequencer-publisher.ts +458 -622
  90. package/src/publisher/write_json.ts +78 -0
  91. package/src/sequencer/automine/README.md +60 -0
  92. package/src/sequencer/automine/automine_factory.ts +152 -0
  93. package/src/sequencer/automine/automine_sequencer.ts +800 -0
  94. package/src/sequencer/automine/index.ts +6 -0
  95. package/src/sequencer/checkpoint_proposal_job.ts +823 -316
  96. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  97. package/src/sequencer/errors.ts +0 -15
  98. package/src/sequencer/events.ts +66 -5
  99. package/src/sequencer/metrics.ts +49 -25
  100. package/src/sequencer/requests_tracker.ts +43 -0
  101. package/src/sequencer/sequencer.ts +607 -206
  102. package/src/sequencer/types.ts +1 -1
  103. package/src/test/index.ts +2 -2
  104. package/src/test/utils.ts +61 -10
  105. package/dest/sequencer/timetable.d.ts +0 -88
  106. package/dest/sequencer/timetable.d.ts.map +0 -1
  107. package/dest/sequencer/timetable.js +0 -222
  108. package/src/sequencer/README.md +0 -531
  109. package/src/sequencer/timetable.ts +0 -283
@@ -1,5 +1,5 @@
1
- import type { EpochCache } from '@aztec/epoch-cache';
2
- import { type FeeHeader, RollupContract } from '@aztec/ethereum/contracts';
1
+ import { type EpochCache, PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec/epoch-cache';
2
+ import type { SimulationOverridesPlan } from '@aztec/ethereum/contracts';
3
3
  import {
4
4
  BlockNumber,
5
5
  CheckpointNumber,
@@ -14,11 +14,12 @@ import {
14
14
  generateUnrecoverableSignature,
15
15
  } from '@aztec/foundation/crypto/secp256k1-signer';
16
16
  import { Fr } from '@aztec/foundation/curves/bn254';
17
+ import { InterruptError, TimeoutError } from '@aztec/foundation/error';
17
18
  import { EthAddress } from '@aztec/foundation/eth-address';
18
19
  import { Signature } from '@aztec/foundation/eth-signature';
19
20
  import { filter } from '@aztec/foundation/iterator';
20
21
  import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
21
- import { sleep, sleepUntil } from '@aztec/foundation/sleep';
22
+ import { InterruptibleSleep } from '@aztec/foundation/sleep';
22
23
  import { type DateProvider, Timer } from '@aztec/foundation/timer';
23
24
  import { type TypedEventEmitter, isErrorClass, unfreeze } from '@aztec/foundation/types';
24
25
  import type { P2P } from '@aztec/p2p';
@@ -30,9 +31,18 @@ import {
30
31
  type L2BlockSink,
31
32
  type L2BlockSource,
32
33
  MaliciousCommitteeAttestationsAndSigners,
34
+ MaliciousYParityCommitteeAttestationsAndSigners,
35
+ type ProposedCheckpointSink,
36
+ type ValidateCheckpointResult,
33
37
  } from '@aztec/stdlib/block';
34
- import { type Checkpoint, type ProposedCheckpointData, validateCheckpoint } from '@aztec/stdlib/checkpoint';
35
- import { computeQuorum, getSlotStartBuildTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
38
+ import {
39
+ type Checkpoint,
40
+ type ProposedCheckpointData,
41
+ buildCheckpointSimulationOverridesPlan,
42
+ getPreviousCheckpointOutHashes,
43
+ validateCheckpoint,
44
+ } from '@aztec/stdlib/checkpoint';
45
+ import { computeQuorum, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
36
46
  import { Gas } from '@aztec/stdlib/gas';
37
47
  import {
38
48
  type BlockBuilderOptions,
@@ -44,11 +54,14 @@ import { type L1ToL2MessageSource, computeInHashFromL1ToL2Messages } from '@azte
44
54
  import type {
45
55
  BlockProposal,
46
56
  BlockProposalOptions,
57
+ CheckpointAttestation,
47
58
  CheckpointProposal,
48
59
  CheckpointProposalOptions,
60
+ CoordinationSignatureContext,
49
61
  } from '@aztec/stdlib/p2p';
50
62
  import { orderAttestations, trimAttestations } from '@aztec/stdlib/p2p';
51
63
  import type { L2BlockBuiltStats } from '@aztec/stdlib/stats';
64
+ import type { ProposerTimetable } from '@aztec/stdlib/timetable';
52
65
  import { type FailedTx, Tx } from '@aztec/stdlib/tx';
53
66
  import { AttestationTimeoutError } from '@aztec/stdlib/validators';
54
67
  import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
@@ -57,18 +70,27 @@ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validato
57
70
 
58
71
  import type { GlobalVariableBuilder } from '../global_variable_builder/global_builder.js';
59
72
  import type { InvalidateCheckpointRequest, SequencerPublisher } from '../publisher/sequencer-publisher.js';
73
+ import type { CheckpointProposalJobMetricsRecorder } from './checkpoint_proposal_job_metrics.js';
60
74
  import { CheckpointVoter } from './checkpoint_voter.js';
61
75
  import { SequencerInterruptedError } from './errors.js';
62
76
  import type { SequencerEvents } from './events.js';
63
77
  import type { SequencerMetrics } from './metrics.js';
64
- import type { SequencerTimetable } from './timetable.js';
78
+ import type { RequestsTracker } from './requests_tracker.js';
65
79
  import type { SequencerRollupConstants } from './types.js';
66
80
  import { SequencerState } from './utils.js';
67
81
 
68
82
  /** How much time to sleep while waiting for min transactions to accumulate for a block */
69
83
  const TXS_POLLING_MS = 500;
84
+ const ARCHIVER_SYNC_POLLING_MS = 200;
70
85
 
71
- /** Result from proposeCheckpoint when a checkpoint was successfully built and attested. */
86
+ /** Result from proposeCheckpoint when a checkpoint was successfully built and broadcast. */
87
+ type CheckpointProposalBroadcast = {
88
+ checkpoint: Checkpoint;
89
+ proposal: CheckpointProposal;
90
+ blockProposedAt: number;
91
+ };
92
+
93
+ /** Result after attestation collection and signing, ready for L1 submission. */
72
94
  type CheckpointProposalResult = {
73
95
  checkpoint: Checkpoint;
74
96
  attestations: CommitteeAttestationsAndSigners;
@@ -83,19 +105,29 @@ type CheckpointProposalResult = {
83
105
  */
84
106
  export class CheckpointProposalJob implements Traceable {
85
107
  protected readonly log: Logger;
108
+ private readonly checkpointEventLog: Logger;
109
+
110
+ private readonly interruptibleSleep = new InterruptibleSleep();
111
+ private interrupted = false;
86
112
 
87
- /** Tracks the fire-and-forget L1 submission promise so it can be awaited during shutdown. */
88
- private pendingL1Submission: Promise<void> | undefined;
113
+ /**
114
+ * Chain state overrides built once per slot in proposeCheckpoint after the checkpoint is
115
+ * complete. Carries the pending parent override (archive + slot + fee header) for pipelining,
116
+ * or the invalidation pending override when rolling back. Consumed by
117
+ * publisher.validateCheckpointHeader before broadcast.
118
+ */
119
+ private checkpointSimulationOverridesPlan?: SimulationOverridesPlan;
89
120
 
90
- /** Fee header override computed during proposeCheckpoint, reused in enqueueCheckpointForSubmission. */
91
- private computedForceProposedFeeHeader?: { checkpointNumber: CheckpointNumber; feeHeader: FeeHeader };
121
+ private getSignatureContext(): CoordinationSignatureContext {
122
+ return this.signatureContext;
123
+ }
92
124
 
93
125
  constructor(
94
- private readonly slotNow: SlotNumber,
95
126
  private readonly targetSlot: SlotNumber,
96
127
  private readonly targetEpoch: EpochNumber,
97
128
  private readonly checkpointNumber: CheckpointNumber,
98
129
  private readonly syncedToBlockNumber: BlockNumber,
130
+ private readonly checkpointedCheckpointNumber: CheckpointNumber,
99
131
  // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
100
132
  private readonly proposer: EthAddress | undefined,
101
133
  private readonly publisher: SequencerPublisher,
@@ -108,36 +140,88 @@ export class CheckpointProposalJob implements Traceable {
108
140
  private readonly l1ToL2MessageSource: L1ToL2MessageSource,
109
141
  private readonly l2BlockSource: L2BlockSource,
110
142
  private readonly checkpointsBuilder: FullNodeCheckpointsBuilder,
111
- private readonly blockSink: L2BlockSink,
143
+ private readonly blockSink: L2BlockSink & ProposedCheckpointSink,
112
144
  private readonly l1Constants: SequencerRollupConstants,
145
+ private readonly signatureContext: CoordinationSignatureContext,
113
146
  protected config: ResolvedSequencerConfig,
114
- protected timetable: SequencerTimetable,
147
+ protected timetable: ProposerTimetable,
115
148
  private readonly slasherClient: SlasherClientInterface | undefined,
116
149
  private readonly epochCache: EpochCache,
117
150
  private readonly dateProvider: DateProvider,
118
151
  private readonly metrics: SequencerMetrics,
119
- private readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
120
- private readonly setStateFn: (state: SequencerState, slot?: SlotNumber) => void,
152
+ private readonly checkpointMetrics: CheckpointProposalJobMetricsRecorder,
153
+ protected readonly eventEmitter: TypedEventEmitter<SequencerEvents>,
154
+ // Shared with the owning sequencer, which drains it during shutdown; the fire-and-forget L1
155
+ // submission this job backgrounds is tracked here rather than in a job-local tracker.
156
+ protected readonly pendingRequests: RequestsTracker,
157
+ private readonly setStateFn: (state: SequencerState, slot: SlotNumber) => void,
121
158
  public readonly tracer: Tracer,
122
159
  bindings?: LoggerBindings,
123
160
  private readonly proposedCheckpointData?: ProposedCheckpointData,
124
161
  ) {
125
162
  this.log = createLogger('sequencer:checkpoint-proposal', {
126
163
  ...bindings,
127
- instanceId: `slot-${this.slotNow}`,
164
+ instanceId: `slot-${this.getBuildSlot()}`,
165
+ });
166
+ this.checkpointEventLog = createLogger('sequencer:checkpoint-events', {
167
+ ...bindings,
168
+ instanceId: `slot-${this.getBuildSlot()}`,
128
169
  });
129
170
  }
130
171
 
131
- /** Awaits the pending L1 submission if one is in progress. Call during shutdown. */
132
- public async awaitPendingSubmission(): Promise<void> {
133
- this.log.info('Awaiting pending L1 payload submission');
134
- await this.pendingL1Submission;
172
+ /**
173
+ * The wall-clock slot during which this job builds, i.e. the slot one before {@link targetSlot} under
174
+ * proposer pipelining. Also the slot of the parent checkpoint this job builds on top of.
175
+ */
176
+ private getBuildSlot(): SlotNumber {
177
+ return SlotNumber(this.targetSlot - PROPOSER_PIPELINING_SLOT_OFFSET);
178
+ }
179
+
180
+ /**
181
+ * Sets the sequencer state for this job, reporting the target slot the checkpoint is being proposed for
182
+ * (not the wall-clock build slot). The slot is informational on the event payload/metrics; the job knows
183
+ * its own target slot, so callers only pass the state.
184
+ */
185
+ private setState(state: SequencerState): void {
186
+ this.setStateFn(state, this.targetSlot);
187
+ }
188
+
189
+ /** Interrupts job-owned waits, including the publisher's send-at-slot sleep, so shutdown can finish. */
190
+ public interrupt(): void {
191
+ this.interrupted = true;
192
+ this.interruptibleSleep.interrupt(true);
193
+ this.publisher.interrupt();
194
+ }
195
+
196
+ private async awaitInterruptibleSleep(ms: number): Promise<void> {
197
+ if (this.interrupted) {
198
+ throw new SequencerInterruptedError();
199
+ }
200
+ if (ms <= 0) {
201
+ return;
202
+ }
203
+ try {
204
+ await this.interruptibleSleep.sleep(ms);
205
+ } catch (err) {
206
+ if (err instanceof InterruptError) {
207
+ throw new SequencerInterruptedError();
208
+ }
209
+ throw err;
210
+ }
211
+ }
212
+
213
+ private logCheckpointEvent(eventName: string, message: string, fields: Record<string, unknown>): void {
214
+ this.checkpointEventLog.debug(message, {
215
+ eventName: `sequencer-checkpoint-${eventName}`,
216
+ ...fields,
217
+ });
135
218
  }
136
219
 
137
220
  /**
138
221
  * Executes the checkpoint proposal job.
139
- * Builds blocks, collects attestations, enqueues requests, and schedules L1 submission as a
140
- * background task so the work loop can return to IDLE immediately.
222
+ * Builds blocks, assembles checkpoint, and broadcasts the proposal (blocking).
223
+ * Attestation collection, signing, and L1 submission are backgrounded so the
224
+ * work loop can return to IDLE immediately for consecutive slot proposals.
141
225
  * Returns the built checkpoint if successful, undefined otherwise.
142
226
  */
143
227
  @trackSpan('CheckpointProposalJob.execute')
@@ -157,83 +241,147 @@ export class CheckpointProposalJob implements Traceable {
157
241
  this.log,
158
242
  ).enqueueVotes();
159
243
 
160
- // Build and propose the checkpoint. Builds blocks, broadcasts, collects attestations, and signs.
161
- // Does NOT enqueue to L1 yet that happens after the pipeline sleep.
162
- const proposalResult = await this.proposeCheckpoint();
163
- const checkpoint = proposalResult?.checkpoint;
164
-
165
- // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
166
- await Promise.all(votesPromises);
167
-
168
- if (checkpoint) {
169
- this.metrics.recordCheckpointProposalSuccess();
244
+ // Build blocks, assemble checkpoint, and broadcast proposal (BLOCKING).
245
+ // Returns after broadcastattestation collection is deferred.
246
+ const broadcast = await this.proposeCheckpoint();
247
+
248
+ if (!broadcast) {
249
+ await Promise.all(votesPromises);
250
+ // Still submit votes even without a checkpoint.
251
+ // Under proposer pipelining, vote-offenses signatures are EIP-712-bound to `targetSlot`
252
+ // (the pipelined slot in which the multicall is expected to mine). Submitting at the
253
+ // wall-clock time would let the multicall mine in a different L2 slot, causing
254
+ // signature verification to fail silently inside Multicall3. Delay submission to the
255
+ // start of `targetSlot` so the tx mines in the slot the vote was signed for.
256
+ if (!this.config.fishermanMode) {
257
+ this.pendingRequests.trackRequest(this.publisher.sendRequestsAt(this.targetSlot), () => this.interrupt());
258
+ }
259
+ return undefined;
170
260
  }
171
261
 
262
+ const { checkpoint } = broadcast;
263
+ this.metrics.recordCheckpointProposalSuccess();
264
+
172
265
  // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
173
266
  if (this.config.fishermanMode) {
174
267
  await this.handleCheckpointEndAsFisherman(checkpoint);
175
- return;
268
+ return checkpoint;
176
269
  }
177
270
 
178
- // Enqueue the checkpoint for L1 submission
179
- if (proposalResult) {
180
- try {
181
- await this.enqueueCheckpointForSubmission(proposalResult);
182
- } catch (err) {
183
- this.log.error(`Failed to enqueue checkpoint for L1 submission at slot ${this.targetSlot}`, err);
184
- // Continue to sendRequestsAt so votes are still sent
271
+ // Background the attestation signing → L1 pipeline so the work loop is unblocked
272
+ this.pendingRequests.trackRequest(this.waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises), () =>
273
+ this.interrupt(),
274
+ );
275
+
276
+ // Return the built checkpoint immediately the work loop is now unblocked
277
+ return checkpoint;
278
+ }
279
+
280
+ /**
281
+ * Background pipeline: collects attestations, signs them, enqueues the checkpoint, and submits to L1.
282
+ * Runs as a fire-and-forget task tracked in the sequencer's shared tracker so the work loop is unblocked.
283
+ */
284
+ private async waitForAttestationsAndEnqueueSubmissionAsync(
285
+ broadcast: CheckpointProposalBroadcast,
286
+ votesPromises: Promise<unknown>[],
287
+ ): Promise<void> {
288
+ const { checkpoint } = broadcast;
289
+
290
+ try {
291
+ // Wait for all votes actions, enqueued at the beginning, to resolve
292
+ await Promise.all(votesPromises);
293
+
294
+ // Try to collect attestations from the committee
295
+ const signedAttestations = await this.getSignedCommitteeAttestations(broadcast);
296
+
297
+ // Wait for the previous checkpoint to land on L1 before submitting, so we can check it
298
+ // matches the proposed checkpoint we used as parent, and has valid attestations.
299
+ if (signedAttestations && (await this.waitForValidParentCheckpointOnL1())) {
300
+ await this.enqueueCheckpointForSubmission({ checkpoint, ...signedAttestations });
185
301
  }
186
- }
187
302
 
188
- // Compute the earliest time to submit: pipeline slot start when pipelining, now otherwise.
189
- const submitAfter = this.epochCache.isProposerPipeliningEnabled()
190
- ? new Date(Number(getTimestampForSlot(this.targetSlot, this.l1Constants)) * 1000)
191
- : new Date(this.dateProvider.now());
192
-
193
- // TODO(https://github.com/AztecProtocol/aztec-packages/pull/21250): should discard the pending submission if a reorg occurs underneath
194
-
195
- // Schedule L1 submission in the background so the work loop returns immediately.
196
- // The publisher will sleep until submitAfter, then send the bundled requests.
197
- // The promise is stored so it can be awaited during shutdown.
198
- this.pendingL1Submission = this.publisher
199
- .sendRequestsAt(submitAfter)
200
- .then(async l1Response => {
201
- const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
202
- if (proposedAction) {
203
- this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.targetSlot });
204
- const coinbase = checkpoint?.header.coinbase;
205
- await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
206
- } else if (checkpoint) {
207
- this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.targetSlot });
208
-
209
- if (this.epochCache.isProposerPipeliningEnabled()) {
210
- this.metrics.recordPipelineDiscard();
211
- }
212
- }
213
- })
214
- .catch(err => {
215
- this.log.error(`Background L1 submission failed for slot ${this.targetSlot}`, err);
216
- if (checkpoint) {
217
- this.eventEmitter.emit('checkpoint-publish-failed', { slot: this.targetSlot });
218
-
219
- if (this.epochCache.isProposerPipeliningEnabled()) {
220
- this.metrics.recordPipelineDiscard();
221
- }
303
+ // If we failed to collect attestations, at least check if we need to issue an invalidation
304
+ if (!signedAttestations && (await this.waitForSyncedL2SlotNumber(this.getBuildSlot()))) {
305
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
306
+ if (!validationStatus.valid) {
307
+ this.log.warn(
308
+ `Checkpoint ${validationStatus.checkpoint.checkpointNumber} has invalid attestations, enqueuing invalidation in spite of attestation collection failure`,
309
+ { checkpoint: validationStatus.checkpoint, reason: validationStatus.reason },
310
+ );
311
+ await this.enqueueInvalidation(validationStatus);
222
312
  }
223
- });
313
+ }
224
314
 
225
- // Return the built checkpoint immediately the work loop is now unblocked
226
- return checkpoint;
315
+ // Send whatever was enqueued: votes + (propose | invalidation | nothing).
316
+ const l1Response = await this.publisher.sendRequestsAt(this.targetSlot);
317
+ const proposedAction = l1Response?.successfulActions.find(a => a === 'propose');
318
+ if (proposedAction) {
319
+ this.logCheckpointEvent('published', `Checkpoint published for slot ${this.targetSlot}`, {
320
+ slot: this.targetSlot,
321
+ checkpointNumber: this.checkpointNumber,
322
+ successfulActions: l1Response?.successfulActions,
323
+ sentActions: l1Response?.sentActions,
324
+ });
325
+ this.eventEmitter.emit('checkpoint-published', { checkpoint: this.checkpointNumber, slot: this.targetSlot });
326
+ const coinbase = checkpoint.header.coinbase;
327
+ await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
328
+ } else {
329
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
330
+ slot: this.targetSlot,
331
+ checkpointNumber: this.checkpointNumber,
332
+ successfulActions: l1Response?.successfulActions,
333
+ failedActions: l1Response?.failedActions,
334
+ sentActions: l1Response?.sentActions,
335
+ expiredActions: l1Response?.expiredActions,
336
+ reason: 'propose_action_not_successful',
337
+ });
338
+ this.log.warn(`Checkpoint publish failed for slot ${this.targetSlot}`, {
339
+ slot: this.targetSlot,
340
+ checkpointNumber: this.checkpointNumber,
341
+ successfulActions: l1Response?.successfulActions,
342
+ failedActions: l1Response?.failedActions,
343
+ sentActions: l1Response?.sentActions,
344
+ expiredActions: l1Response?.expiredActions,
345
+ reason: 'propose_action_not_successful',
346
+ });
347
+ this.eventEmitter.emit('checkpoint-publish-failed', { ...l1Response, slot: this.targetSlot });
348
+ this.metrics.recordPipelineDiscard();
349
+ }
350
+ } catch (err) {
351
+ if (err instanceof SequencerInterruptedError) {
352
+ return;
353
+ }
354
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
355
+ slot: this.targetSlot,
356
+ checkpointNumber: this.checkpointNumber,
357
+ reason: err instanceof Error ? err.message : String(err),
358
+ });
359
+ this.log.error(`Background attestation/L1 pipeline failed for slot ${this.targetSlot}`, err, {
360
+ slot: this.targetSlot,
361
+ checkpointNumber: this.checkpointNumber,
362
+ reason: err instanceof Error ? err.message : String(err),
363
+ });
364
+ this.eventEmitter.emit('checkpoint-publish-failed', { slot: this.targetSlot });
365
+ this.metrics.recordPipelineDiscard();
366
+ }
227
367
  }
228
368
 
229
369
  /** Enqueues the checkpoint for L1 submission. Called after pipeline sleep in execute(). */
230
370
  private async enqueueCheckpointForSubmission(result: CheckpointProposalResult): Promise<void> {
231
371
  const { checkpoint, attestations, attestationsSignature } = result;
232
372
 
233
- this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.targetSlot);
234
- const aztecSlotDuration = this.l1Constants.slotDuration;
235
- const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
236
- const txTimeoutAt = new Date((submissionSlotStart + aztecSlotDuration) * 1000);
373
+ this.setState(SequencerState.PUBLISHING_CHECKPOINT);
374
+ // Latest L1 block the propose can still land in for the target slot: the last Ethereum block inside
375
+ // the target slot (`target_slot_start + S - E`). This is one ethereum slot later than
376
+ // `attestation_deadline` (= last_ethereum_block_in_target_slot - E), which bounds when validators must
377
+ // have signed, not when the proposer must have sent. Using the attestation deadline here is too tight:
378
+ // attestations are collected up to (and, when not enforcing, past) it, so the propose tx would be
379
+ // enqueued already expired and time out before it can mine.
380
+ const lastL1BlockInTargetSlot =
381
+ Number(getTimestampForSlot(this.targetSlot, this.l1Constants)) +
382
+ this.l1Constants.slotDuration -
383
+ this.l1Constants.ethereumSlotDuration;
384
+ const txTimeoutAt = new Date(lastL1BlockInTargetSlot * 1000);
237
385
 
238
386
  // If we have been configured to potentially skip publishing checkpoint then roll the dice here
239
387
  if (
@@ -249,13 +397,156 @@ export class CheckpointProposalJob implements Traceable {
249
397
  }
250
398
  }
251
399
 
252
- await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
253
- txTimeoutAt,
254
- forcePendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
255
- forceProposedFeeHeader: this.computedForceProposedFeeHeader,
400
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, { txTimeoutAt });
401
+ }
402
+
403
+ /**
404
+ * Wait until the archiver syncs past the given L2 slot number.
405
+ * The deadline is the end of `this.targetSlot`, beyond which any pipelined work would miss its
406
+ * L1 submission window and is no longer useful.
407
+ */
408
+ private async waitForSyncedL2SlotNumber(waitForSlot: SlotNumber): Promise<boolean> {
409
+ const targetSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
410
+ const targetSlotEndMs = (targetSlotStart + this.l1Constants.slotDuration) * 1000;
411
+ const syncDelayTolerance = this.l1Constants.ethereumSlotDuration * 2 * 1000;
412
+ const timeoutSeconds = Math.max(0.1, (targetSlotEndMs + syncDelayTolerance - this.dateProvider.now()) / 1000);
413
+
414
+ try {
415
+ const timer = new Timer();
416
+ while (true) {
417
+ const syncedSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
418
+ if (syncedSlot !== undefined && syncedSlot >= waitForSlot) {
419
+ return true;
420
+ }
421
+ if (timeoutSeconds && timer.s() > timeoutSeconds) {
422
+ throw new TimeoutError(`Timeout awaiting archiver sync past slot ${waitForSlot}`);
423
+ }
424
+ await this.awaitInterruptibleSleep(ARCHIVER_SYNC_POLLING_MS);
425
+ }
426
+ } catch (err) {
427
+ if (err instanceof SequencerInterruptedError) {
428
+ throw err;
429
+ }
430
+ this.log.warn(
431
+ `Archiver did not sync L1 past slot ${waitForSlot} before slot ${this.targetSlot} expired, discarding pipelined work`,
432
+ { checkpointNumber: this.checkpointNumber },
433
+ );
434
+ this.emitPipelinedCheckpointDiscarded('archiver-sync-timeout');
435
+ return false;
436
+ }
437
+ }
438
+
439
+ /**
440
+ * Waits for the parent checkpoint to land on L1 before submitting a pipelined checkpoint.
441
+ * Polls until the archiver has synced L1 past the parent's slot, then verifies:
442
+ * - If we built on a proposed parent: it must have landed on L1 with matching hash and valid attestations.
443
+ * - If we built without a proposed parent: no new checkpoint must have appeared for that slot.
444
+ * If the parent has invalid attestations, enqueues an invalidation. Returns whether to proceed with the proposal.
445
+ */
446
+ protected async waitForValidParentCheckpointOnL1(): Promise<boolean> {
447
+ if (this.config.skipWaitForValidParentCheckpointOnL1) {
448
+ this.log.warn(`Skipping waitForValidParentCheckpointOnL1 due to test configuration`, {
449
+ checkpointNumber: this.checkpointNumber,
450
+ });
451
+ return true;
452
+ }
453
+
454
+ const parentCheckpointNumber = CheckpointNumber(this.checkpointNumber - 1);
455
+
456
+ // Wait until archiver has synced L1 past the parent's slot (the build slot, one before targetSlot)
457
+ if (!(await this.waitForSyncedL2SlotNumber(this.getBuildSlot()))) {
458
+ return false;
459
+ }
460
+
461
+ const tips = await this.l2BlockSource.getL2Tips();
462
+ const checkpointedNumber = tips.checkpointed.checkpoint.number;
463
+
464
+ // We built on top of a proposed checkpoint. Verify it landed on L1 as expected.
465
+ if (this.proposedCheckpointData) {
466
+ // After syncing from L1 we see the chain tip has invalid attestations. This means the parent checkpoint was posted
467
+ // with invalid attestations, or it built on top of something with invalid attestations and didnt invalidate them.
468
+ // Either way, we thought our parent would be valid, so we have to throw away our work. But at least we'll try and
469
+ // invalidate on L1 so we clean up the chain for the next proposer. And we'll slash them, but that's handled elsewhere.
470
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
471
+ if (!validationStatus.valid) {
472
+ this.log.warn(
473
+ `Parent checkpoint ${parentCheckpointNumber} has invalid attestations, discarding pipelined work`,
474
+ { checkpointNumber: this.checkpointNumber, reason: validationStatus.reason },
475
+ );
476
+ this.emitPipelinedCheckpointDiscarded('parent-invalid-attestations');
477
+ await this.enqueueInvalidation(validationStatus);
478
+ return false;
479
+ }
480
+
481
+ // The pending chain is valid. But did the parent checkpoint land on L1 at all?
482
+ if (checkpointedNumber < parentCheckpointNumber) {
483
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} did not land on L1, discarding pipelined work`, {
484
+ checkpointNumber: this.checkpointNumber,
485
+ checkpointedNumber,
486
+ });
487
+ this.emitPipelinedCheckpointDiscarded('parent-not-on-l1');
488
+ return false;
489
+ }
490
+
491
+ // It landed. But is it the one we were expecting?
492
+ const expectedHash = this.proposedCheckpointData.header.hash().toString();
493
+ if (tips.checkpointed.checkpoint.hash !== expectedHash) {
494
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} hash mismatch on L1, discarding pipelined work`, {
495
+ checkpointNumber: this.checkpointNumber,
496
+ expectedHash,
497
+ actualHash: tips.checkpointed.checkpoint.hash,
498
+ });
499
+ this.emitPipelinedCheckpointDiscarded('parent-hash-mismatch');
500
+ return false;
501
+ }
502
+
503
+ return true;
504
+ } else {
505
+ // We didn't see a proposed checkpoint at build time, so we built on checkpointed parent from two slots ago.
506
+ // But if a new checkpoint for the previous slot appeared on L1 in the meantime, our checkpoint assumed the wrong parent,
507
+ // so we have to discard our work. This can happen if we're somehow cut off from p2p and fail to see the checkpoint
508
+ // proposal for the previous slot.
509
+ if (checkpointedNumber > parentCheckpointNumber) {
510
+ this.log.warn(
511
+ `Unexpected checkpoint ${checkpointedNumber} landed on L1 after we built on top of parent ${parentCheckpointNumber}, discarding pipelined work`,
512
+ { checkpointNumber: this.checkpointNumber, checkpointedNumber },
513
+ );
514
+ this.emitPipelinedCheckpointDiscarded('unexpected-parent-appeared');
515
+ return false;
516
+ }
517
+
518
+ return true;
519
+ }
520
+ }
521
+
522
+ /** Emits the pipelined-checkpoint-discarded event and records the metric. */
523
+ private emitPipelinedCheckpointDiscarded(reason: string): void {
524
+ this.metrics.recordPipelineParentCheckpointMismatch(reason);
525
+ this.eventEmitter.emit('pipelined-checkpoint-discarded', {
526
+ slot: this.targetSlot,
527
+ checkpointNumber: this.checkpointNumber,
528
+ reason,
256
529
  });
257
530
  }
258
531
 
532
+ /** Simulates and enqueues an invalidation request for the invalid parent checkpoint. */
533
+ private async enqueueInvalidation(validationStatus: ValidateCheckpointResult): Promise<void> {
534
+ if (this.config.skipInvalidateBlockAsProposer) {
535
+ this.log.warn(`Skipping checkpoint invalidation as proposer due to test configuration`);
536
+ return;
537
+ }
538
+ const invalidateRequest = await this.publisher.simulateInvalidateCheckpoint(validationStatus);
539
+ if (invalidateRequest) {
540
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
541
+ const txTimeoutAt = new Date((submissionSlotStart + this.l1Constants.slotDuration) * 1000);
542
+ this.publisher.enqueueInvalidateCheckpoint(invalidateRequest, { txTimeoutAt });
543
+ } else {
544
+ this.log.info(`Invalidation simulation returned undefined, checkpoint may have been removed already`, {
545
+ checkpointNumber: this.checkpointNumber,
546
+ });
547
+ }
548
+ }
549
+
259
550
  @trackSpan('CheckpointProposalJob.proposeCheckpoint', function () {
260
551
  return {
261
552
  // nullish operator needed for tests
@@ -263,19 +554,32 @@ export class CheckpointProposalJob implements Traceable {
263
554
  [Attributes.SLOT_NUMBER]: this.targetSlot,
264
555
  };
265
556
  })
266
- private async proposeCheckpoint(): Promise<CheckpointProposalResult | undefined> {
557
+ private async proposeCheckpoint(): Promise<CheckpointProposalBroadcast | undefined> {
267
558
  try {
559
+ const now = this.dateProvider.now();
560
+ if (this.proposedCheckpointData) {
561
+ // Measure against the wall-clock slot whose build window we are currently using.
562
+ // In pipelining mode `targetSlot` is intentionally one slot ahead, which makes the
563
+ // target-slot boundary a full slot away from the actual build start time.
564
+ const slotBoundaryMs = Number(getTimestampForSlot(this.getBuildSlot(), this.l1Constants)) * 1000;
565
+ this.checkpointMetrics.recordPipelinedCheckpointBuildStartOffsetFromSlotBoundary(now - slotBoundaryMs);
566
+ }
567
+ this.checkpointMetrics.startCheckpointTiming(now);
568
+
268
569
  // Get operator configured coinbase and fee recipient for this attestor
269
570
  const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
270
571
  const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
271
572
 
272
573
  // Start the checkpoint
273
- this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.targetSlot);
274
- this.log.info(`Starting checkpoint proposal`, {
275
- buildSlot: this.slotNow,
574
+ this.setState(SequencerState.INITIALIZING_CHECKPOINT);
575
+ this.logCheckpointEvent('slot-started', `Starting checkpoint proposal for slot ${this.targetSlot}`, {
576
+ buildSlot: this.getBuildSlot(),
276
577
  submissionSlot: this.targetSlot,
277
- pipelining: this.epochCache.isProposerPipeliningEnabled(),
578
+ slot: this.targetSlot,
579
+ checkpointNumber: this.checkpointNumber,
278
580
  proposer: this.proposer?.toString(),
581
+ attestorAddress: this.attestorAddress.toString(),
582
+ publisherAddress: this.publisher.getSenderAddress().toString(),
279
583
  coinbase: coinbase.toString(),
280
584
  });
281
585
  this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
@@ -285,38 +589,51 @@ export class CheckpointProposalJob implements Traceable {
285
589
  this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
286
590
  }
287
591
 
288
- // Create checkpoint builder for the slot.
289
- // When pipelining, force the proposed checkpoint number and fee header to our parent so the
290
- // fee computation sees the same chain tip that L1 will see once the previous pipelined checkpoint lands.
291
- const isPipelining = this.epochCache.isProposerPipeliningEnabled();
292
- const parentCheckpointNumber = isPipelining ? CheckpointNumber(this.checkpointNumber - 1) : undefined;
293
-
294
- // Compute the parent's fee header override when pipelining
295
- if (isPipelining && this.proposedCheckpointData) {
296
- this.computedForceProposedFeeHeader = await this.computeForceProposedFeeHeader(parentCheckpointNumber!);
297
- }
592
+ // Build the simulation plan for this slot. When pipelining, this overrides L1's view of
593
+ // pending/archive/fee-header to "as if the proposed parent had landed", so both the
594
+ // mana-min-fee simulation (in the globals builder) and the pre-broadcast
595
+ // validateCheckpointHeader see the chain tip the eventual L1 send will see.
596
+ this.checkpointSimulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
597
+ checkpointNumber: this.checkpointNumber,
598
+ proposedCheckpointData: this.proposedCheckpointData,
599
+ invalidateToPendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
600
+ checkpointedCheckpointNumber: this.checkpointedCheckpointNumber,
601
+ rollup: this.publisher.rollupContract,
602
+ signatureContext: this.signatureContext,
603
+ log: this.log,
604
+ });
298
605
 
299
606
  const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(
300
607
  coinbase,
301
608
  feeRecipient,
302
609
  this.targetSlot,
303
- {
304
- forcePendingCheckpointNumber: parentCheckpointNumber,
305
- forceProposedFeeHeader: this.computedForceProposedFeeHeader,
306
- },
610
+ this.checkpointSimulationOverridesPlan,
307
611
  );
308
612
 
309
613
  // Collect L1 to L2 messages for the checkpoint and compute their hash
310
614
  const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
311
615
  const inHash = computeInHashFromL1ToL2Messages(l1ToL2Messages);
312
616
 
313
- // Collect the out hashes of all the checkpoints before this one in the same epoch
314
- const previousCheckpointOutHashes = (await this.l2BlockSource.getCheckpointsDataForEpoch(this.targetEpoch))
315
- .filter(c => c.checkpointNumber < this.checkpointNumber)
316
- .map(c => c.checkpointOutHash);
617
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
618
+ // Under pipelining the parent checkpoint may not be on L1 yet at build time, so the helper
619
+ // splices in the parent's checkpointOutHash from the locally-known proposed checkpoint so
620
+ // the resulting `epochOutHash` matches what validators (and L1) compute once the parent
621
+ // lands on L1.
622
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
623
+ blockSource: this.l2BlockSource,
624
+ epoch: this.targetEpoch,
625
+ checkpointNumber: this.checkpointNumber,
626
+ l1Constants: this.epochCache.getL1Constants(),
627
+ pipeliningEnabled: true,
628
+ proposedCheckpointData: this.proposedCheckpointData,
629
+ log: this.log,
630
+ });
317
631
 
318
- // Get the fee asset price modifier from the oracle
319
- const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier();
632
+ // Anchor the modifier to the predicted parent fee header: L1 will apply it against
633
+ // that, not against the latest published checkpoint (which lags by one under pipelining).
634
+ const predictedParentEthPerFeeAssetE12 =
635
+ this.checkpointSimulationOverridesPlan?.pendingCheckpointState?.feeHeader?.ethPerFeeAsset;
636
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12);
320
637
 
321
638
  // Create a long-lived forked world state for the checkpoint builder
322
639
  await using fork = await this.worldState.fork(this.syncedToBlockNumber, { closeDelayMs: 12_000 });
@@ -340,11 +657,12 @@ export class CheckpointProposalJob implements Traceable {
340
657
 
341
658
  const checkpointProposalOptions: CheckpointProposalOptions = {
342
659
  publishFullTxs: !!this.config.publishTxsWithProposals,
343
- broadcastInvalidCheckpointProposal: this.config.broadcastInvalidBlockProposal,
660
+ broadcastInvalidCheckpointProposal:
661
+ this.config.broadcastInvalidCheckpointProposalOnly || this.config.broadcastInvalidBlockProposal,
344
662
  };
345
663
 
346
664
  let blocksInCheckpoint: L2Block[] = [];
347
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
665
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
348
666
  const checkpointBuildTimer = new Timer();
349
667
 
350
668
  try {
@@ -368,23 +686,45 @@ export class CheckpointProposalJob implements Traceable {
368
686
  }
369
687
 
370
688
  if (blocksInCheckpoint.length === 0) {
371
- this.log.warn(`No blocks were built for slot ${this.targetSlot}`, { slot: this.targetSlot });
689
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
690
+ slot: this.targetSlot,
691
+ checkpointNumber: this.checkpointNumber,
692
+ reason: 'no_blocks_built',
693
+ });
694
+ this.log.warn(`No blocks were built for slot ${this.targetSlot}`, {
695
+ slot: this.targetSlot,
696
+ checkpointNumber: this.checkpointNumber,
697
+ reason: 'no_blocks_built',
698
+ });
372
699
  this.eventEmitter.emit('checkpoint-empty', { slot: this.targetSlot });
373
700
  return undefined;
374
701
  }
375
702
 
376
703
  const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
377
704
  if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
705
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
706
+ slot: this.targetSlot,
707
+ checkpointNumber: this.checkpointNumber,
708
+ blocksBuilt: blocksInCheckpoint.length,
709
+ minBlocksForCheckpoint,
710
+ reason: 'min_blocks_not_met',
711
+ });
378
712
  this.log.warn(
379
713
  `Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`,
380
- { slot: this.targetSlot, blocksBuilt: blocksInCheckpoint.length, minBlocksForCheckpoint },
714
+ {
715
+ slot: this.targetSlot,
716
+ checkpointNumber: this.checkpointNumber,
717
+ blocksBuilt: blocksInCheckpoint.length,
718
+ minBlocksForCheckpoint,
719
+ reason: 'min_blocks_not_met',
720
+ },
381
721
  );
382
722
  return undefined;
383
723
  }
384
724
 
385
725
  // Assemble and broadcast the checkpoint proposal, including the last block that was not
386
726
  // broadcasted yet, and wait to collect the committee attestations.
387
- this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.targetSlot);
727
+ this.setState(SequencerState.ASSEMBLING_CHECKPOINT);
388
728
  const checkpoint = await checkpointBuilder.completeCheckpoint();
389
729
 
390
730
  // Final validation: per-block limits are only checked if the operator set them explicitly.
@@ -398,21 +738,43 @@ export class CheckpointProposalJob implements Traceable {
398
738
  maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint,
399
739
  });
400
740
  } catch (err) {
401
- this.log.error(`Built an invalid checkpoint at slot ${this.slotNow} (skipping proposal)`, err, {
741
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
742
+ slot: this.targetSlot,
743
+ checkpointNumber: this.checkpointNumber,
744
+ blocksBuilt: blocksInCheckpoint.length,
745
+ reason: 'invalid_checkpoint',
746
+ checkpoint: checkpoint.header.toInspect(),
747
+ });
748
+ this.log.error(`Built an invalid checkpoint at slot ${this.targetSlot} (skipping proposal)`, err, {
749
+ slot: this.targetSlot,
750
+ checkpointNumber: this.checkpointNumber,
751
+ blocksBuilt: blocksInCheckpoint.length,
752
+ reason: 'invalid_checkpoint',
402
753
  checkpoint: checkpoint.header.toInspect(),
403
754
  });
404
755
  return undefined;
405
756
  }
406
757
 
407
758
  // Record checkpoint-level build metrics
408
- this.metrics.recordCheckpointBuild(
759
+ this.checkpointMetrics.recordCheckpointBuild(
409
760
  checkpointBuildTimer.ms(),
410
761
  blocksInCheckpoint.length,
411
762
  checkpoint.getStats().txCount,
412
763
  Number(checkpoint.header.totalManaUsed.toBigInt()),
413
764
  );
765
+ this.logCheckpointEvent('built', `Checkpoint built for slot ${this.targetSlot}`, {
766
+ slot: this.targetSlot,
767
+ buildSlot: this.getBuildSlot(),
768
+ checkpointNumber: this.checkpointNumber,
769
+ proposer: this.proposer?.toString(),
770
+ attestorAddress: this.attestorAddress.toString(),
771
+ publisherAddress: this.publisher.getSenderAddress().toString(),
772
+ blocksBuilt: blocksInCheckpoint.length,
773
+ txCount: checkpoint.getStats().txCount,
774
+ totalMana: Number(checkpoint.header.totalManaUsed.toBigInt()),
775
+ });
414
776
 
415
- // Do not collect attestations nor publish to L1 in fisherman mode
777
+ // In fisherman mode, return the checkpoint without broadcasting or collecting attestations
416
778
  if (this.config.fishermanMode) {
417
779
  this.log.info(
418
780
  `Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` +
@@ -424,60 +786,63 @@ export class CheckpointProposalJob implements Traceable {
424
786
  },
425
787
  );
426
788
  this.metrics.recordCheckpointSuccess();
427
- return {
428
- checkpoint,
429
- attestations: CommitteeAttestationsAndSigners.empty(),
430
- attestationsSignature: Signature.empty(),
431
- };
789
+ // Return a broadcast result with a dummy proposal — fisherman mode skips attestation collection
790
+ return { checkpoint, proposal: undefined!, blockProposedAt: this.dateProvider.now() };
432
791
  }
433
792
 
434
- // Include the block pending broadcast in the checkpoint proposal if any
435
- const lastBlock = blockPendingBroadcast && {
436
- blockHeader: blockPendingBroadcast.block.header,
437
- indexWithinCheckpoint: blockPendingBroadcast.block.indexWithinCheckpoint,
438
- txs: blockPendingBroadcast.txs,
439
- };
793
+ // Validate the header against L1 state before broadcasting.
794
+ // If this fails the slot is aborted before any gossip work; state drift between here
795
+ // and the eventual L1 send is caught by the bundle simulate at send time.
796
+ try {
797
+ await this.publisher.validateCheckpointHeader(checkpoint.header, this.checkpointSimulationOverridesPlan);
798
+ } catch (err) {
799
+ this.log.error(`Pre-broadcast header validation failed for slot ${this.targetSlot}; aborting`, err, {
800
+ slot: this.targetSlot,
801
+ checkpointNumber: this.checkpointNumber,
802
+ });
803
+ this.metrics.recordCheckpointProposalFailed('header_validation_failed');
804
+ this.eventEmitter.emit('header-validation-failed', {
805
+ slot: this.targetSlot,
806
+ checkpointNumber: this.checkpointNumber,
807
+ reason: err instanceof Error ? err.message : String(err),
808
+ });
809
+ return undefined;
810
+ }
440
811
 
441
812
  // Create the checkpoint proposal and broadcast it
442
813
  const proposal = await this.validatorClient.createCheckpointProposal(
443
814
  checkpoint.header,
444
815
  checkpoint.archive.root,
816
+ this.checkpointNumber,
445
817
  feeAssetPriceModifier,
446
- lastBlock,
818
+ blockPendingBroadcast,
447
819
  this.proposer,
448
820
  checkpointProposalOptions,
449
821
  );
450
822
 
451
- const blockProposedAt = this.dateProvider.now();
452
- await this.p2pClient.broadcastCheckpointProposal(proposal);
453
-
454
- this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.targetSlot);
455
- const attestations = await this.waitForAttestations(proposal);
456
- const blockAttestedAt = this.dateProvider.now();
457
-
458
- this.metrics.recordCheckpointAttestationDelay(blockAttestedAt - blockProposedAt);
823
+ // Advance our own optimistic proposed-checkpoint tip locally before gossiping. Gossipsub
824
+ // doesn't echo our own messages back, so this is how the proposer makes its own proposed
825
+ // checkpoint visible for pipelining the next slot. Built from local checkpoint data — never
826
+ // from the broadcast proposal archive, which may be deliberately corrupted under test flags.
827
+ // Fail closed: if this throws, the outer catch aborts the slot before gossiping.
828
+ await this.syncProposedCheckpointToArchiver(checkpoint, blocksInCheckpoint.length, feeAssetPriceModifier);
459
829
 
460
- // Proposer must sign over the attestations before pushing them to L1
461
- const signer = this.proposer ?? this.publisher.getSenderAddress();
462
- let attestationsSignature: Signature;
463
- try {
464
- attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
465
- attestations,
466
- signer,
467
- this.targetSlot,
468
- this.checkpointNumber,
469
- );
470
- } catch (err) {
471
- // We shouldn't really get here since we yield to another HA node
472
- // as soon as we see these errors when creating block or checkpoint proposals.
473
- if (this.handleHASigningError(err, 'Attestations signature')) {
474
- return undefined;
830
+ const blockProposedAt = this.dateProvider.now();
831
+ if (this.config.skipBroadcastCheckpointProposal) {
832
+ // Test-only: suppress the CheckpointProposal so peers never see a proposed checkpoint for
833
+ // this slot, but still broadcast the held last block standalone so peers' archivers ingest
834
+ // it as a proposed-but-uncheckpointed tip — the exact orphan-block state that
835
+ // pruneOrphanProposedBlocks / checkSync must handle.
836
+ if (blockPendingBroadcast && !this.config.skipBroadcastProposals) {
837
+ await this.p2pClient.broadcastProposal(blockPendingBroadcast);
475
838
  }
476
- throw err;
839
+ } else if (!this.config.skipBroadcastProposals) {
840
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
841
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
477
842
  }
478
843
 
479
- // Return the result for the caller to enqueue after the pipeline sleep
480
- return { checkpoint, attestations, attestationsSignature };
844
+ // Return immediately after broadcast attestation collection happens in the background
845
+ return { checkpoint, proposal, blockProposedAt };
481
846
  } catch (err) {
482
847
  if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
483
848
  // swallow this error. It's already been logged by a function deeper in the stack
@@ -500,28 +865,37 @@ export class CheckpointProposalJob implements Traceable {
500
865
  blockProposalOptions: BlockProposalOptions,
501
866
  ): Promise<{
502
867
  blocksInCheckpoint: L2Block[];
503
- blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined;
868
+ blockPendingBroadcast: BlockProposal | undefined;
504
869
  }> {
505
870
  const blocksInCheckpoint: L2Block[] = [];
506
871
  const txHashesAlreadyIncluded = new Set<string>();
507
872
  const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
508
873
 
509
874
  // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
510
- let blockPendingBroadcast: { block: L2Block; txs: Tx[] } | undefined = undefined;
875
+ let blockPendingBroadcast: BlockProposal | undefined = undefined;
511
876
 
512
877
  while (true) {
513
878
  const blocksBuilt = blocksInCheckpoint.length;
514
879
  const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
515
880
  const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
516
881
 
517
- const secondsIntoSlot = this.getSecondsIntoSlot();
518
- const timingInfo = this.timetable.canStartNextBlock(secondsIntoSlot);
882
+ if (blocksBuilt >= this.config.maxBlocksPerCheckpoint) {
883
+ this.log.debug(`Reached max blocks per checkpoint`, {
884
+ slot: this.targetSlot,
885
+ blocksBuilt,
886
+ maxBlocksPerCheckpoint: this.config.maxBlocksPerCheckpoint,
887
+ });
888
+ break;
889
+ }
890
+
891
+ const nowSeconds = this.dateProvider.now() / 1000;
892
+ const timingInfo = this.timetable.selectNextSubslot(this.targetSlot, nowSeconds);
519
893
 
520
894
  if (!timingInfo.canStart) {
521
895
  this.log.debug(`Not enough time left in slot to start another block`, {
522
896
  slot: this.targetSlot,
523
897
  blocksBuilt,
524
- secondsIntoSlot,
898
+ nowSeconds,
525
899
  });
526
900
  break;
527
901
  }
@@ -531,28 +905,26 @@ export class CheckpointProposalJob implements Traceable {
531
905
  blockTimestamp: timestamp,
532
906
  // Create an empty block if we haven't already and this is the last one
533
907
  forceCreate: timingInfo.isLastBlock && blocksBuilt === 0 && this.config.buildCheckpointIfEmpty,
534
- // Build deadline is only set if we are enforcing the timetable
535
- buildDeadline: timingInfo.deadline
536
- ? new Date((this.getSlotStartBuildTimestamp() + timingInfo.deadline) * 1000)
537
- : undefined,
908
+ buildDeadline: new Date(timingInfo.deadline * 1000),
538
909
  blockNumber,
539
910
  indexWithinCheckpoint,
540
911
  txHashesAlreadyIncluded,
541
912
  });
542
913
 
543
- // TODO(palla/mbps): Review these conditions. We may want to keep trying in some scenarios.
544
- if (!buildResult && timingInfo.isLastBlock) {
545
- // If no block was produced due to not enough txs and this was the last subslot, exit
546
- break;
547
- } else if (!buildResult && timingInfo.deadline !== undefined) {
548
- // But if there is still time for more blocks, wait until the next subslot and try again
914
+ // If we failed to build the block due to insufficient txs, we try again if there is still time left in the slot
915
+ if ('failure' in buildResult) {
916
+ // If this was the last subslot, we're done.
917
+ if (timingInfo.isLastBlock) {
918
+ break;
919
+ }
920
+ // Otherwise, if there is still time for more blocks, we wait until the next subslot and try again
549
921
  await this.waitUntilNextSubslot(timingInfo.deadline);
550
922
  continue;
551
- } else if (!buildResult) {
552
- // Exit if there is no possibility of building more blocks
553
- break;
554
- } else if ('error' in buildResult) {
555
- // If there was an error building the block, just exit the loop and give up the rest of the slot
923
+ }
924
+
925
+ // If there was an error building the block, we just exit the loop and give up the rest of the slot.
926
+ // We don't want to risk building more blocks if something went wrong.
927
+ if ('error' in buildResult) {
556
928
  if (!(buildResult.error instanceof SequencerInterruptedError)) {
557
929
  this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
558
930
  slot: this.targetSlot,
@@ -564,35 +936,44 @@ export class CheckpointProposalJob implements Traceable {
564
936
  }
565
937
 
566
938
  const { block, usedTxs } = buildResult;
939
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
940
+ isFirstBlock: blocksBuilt === 0,
941
+ isLastBlock: timingInfo.isLastBlock,
942
+ });
943
+
567
944
  blocksInCheckpoint.push(block);
568
945
  usedTxs.forEach(tx => txHashesAlreadyIncluded.add(tx.txHash.toString()));
569
946
 
570
- // If this is the last block, sync it to the archiver and exit the loop
571
- // so we can build the checkpoint and start collecting attestations.
947
+ // Sign the block proposal. This will throw if HA signing fails.
948
+ const proposal = await this.createBlockProposal(block, inHash, usedTxs, {
949
+ ...blockProposalOptions,
950
+ broadcastInvalidBlockProposal:
951
+ blockProposalOptions.broadcastInvalidBlockProposal ||
952
+ block.indexWithinCheckpoint === this.config.invalidBlockProposalIndexWithinCheckpoint,
953
+ });
954
+
955
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
956
+ // so we avoid polluting our archive with a block that would fail.
957
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
958
+ // If this throws, we abort the entire checkpoint.
959
+ await this.syncProposedBlockToArchiver(block);
960
+
961
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
572
962
  if (timingInfo.isLastBlock) {
573
- await this.syncProposedBlockToArchiver(block);
574
963
  this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
575
964
  slot: this.targetSlot,
576
965
  blockNumber,
577
966
  blocksBuilt,
578
967
  });
579
- blockPendingBroadcast = { block, txs: usedTxs };
968
+
969
+ blockPendingBroadcast = proposal;
580
970
  break;
581
971
  }
582
972
 
583
- // Broadcast the block proposal (unless we're in fisherman mode) unless the block is the last one,
584
- // in which case we'll broadcast it along with the checkpoint at the end of the loop.
585
- // Note that we only send the block to the archiver if we manage to create the proposal, so if there's
586
- // a HA error we don't pollute our archiver with a block that won't make it to the chain.
587
- const proposal = await this.createBlockProposal(block, inHash, usedTxs, blockProposalOptions);
588
-
589
- // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal.
590
- // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
591
- // If this throws, we abort the entire checkpoint.
592
- await this.syncProposedBlockToArchiver(block);
593
-
594
973
  // Once we have a signed proposal and the archiver agreed with our proposed block, then we broadcast it.
595
- proposal && (await this.p2pClient.broadcastProposal(proposal));
974
+ if (proposal && !this.config.skipBroadcastProposals) {
975
+ await this.p2pClient.broadcastProposal(proposal);
976
+ }
596
977
 
597
978
  // Wait until the next block's start time
598
979
  await this.waitUntilNextSubslot(timingInfo.deadline);
@@ -619,6 +1000,7 @@ export class CheckpointProposalJob implements Traceable {
619
1000
  }
620
1001
  return this.validatorClient.createBlockProposal(
621
1002
  block.header,
1003
+ this.checkpointNumber,
622
1004
  block.indexWithinCheckpoint,
623
1005
  inHash,
624
1006
  block.archive.root,
@@ -628,14 +1010,17 @@ export class CheckpointProposalJob implements Traceable {
628
1010
  );
629
1011
  }
630
1012
 
631
- /** Sleeps until it is time to produce the next block in the slot */
1013
+ /**
1014
+ * Sleeps until it is time to produce the next block in the slot.
1015
+ * @param nextSubslotStart - Absolute wall-clock timestamp in seconds of the previous sub-slot deadline.
1016
+ */
632
1017
  @trackSpan('CheckpointProposalJob.waitUntilNextSubslot')
633
- private async waitUntilNextSubslot(nextSubslotStart: number) {
634
- this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.targetSlot);
635
- this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, {
1018
+ protected async waitUntilNextSubslot(nextSubslotStart: number) {
1019
+ this.setState(SequencerState.WAITING_UNTIL_NEXT_BLOCK);
1020
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s`, {
636
1021
  slot: this.targetSlot,
637
1022
  });
638
- await this.waitUntilTimeInSlot(nextSubslotStart);
1023
+ await this.awaitInterruptibleSleep(Math.max(0, nextSubslotStart * 1000 - this.dateProvider.now()));
639
1024
  }
640
1025
 
641
1026
  /** Builds a single block. Called from the main block building loop. */
@@ -650,7 +1035,9 @@ export class CheckpointProposalJob implements Traceable {
650
1035
  buildDeadline: Date | undefined;
651
1036
  txHashesAlreadyIncluded: Set<string>;
652
1037
  },
653
- ): Promise<{ block: L2Block; usedTxs: Tx[] } | { error: Error } | undefined> {
1038
+ ): Promise<
1039
+ { block: L2Block; usedTxs: Tx[] } | { failure: 'insufficient-txs' | 'insufficient-valid-txs' } | { error: Error }
1040
+ > {
654
1041
  const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } =
655
1042
  opts;
656
1043
 
@@ -661,34 +1048,56 @@ export class CheckpointProposalJob implements Traceable {
661
1048
 
662
1049
  try {
663
1050
  // Wait until we have enough txs to build the block
664
- const { availableTxs, canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
1051
+ const { canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
665
1052
  if (!canStartBuilding) {
666
- this.log.warn(
667
- `Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (got ${availableTxs} txs but needs ${minTxs})`,
668
- { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
1053
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1054
+ reason: 'insufficient_txs',
1055
+ blockNumber,
1056
+ slot: this.targetSlot,
1057
+ checkpointNumber: this.checkpointNumber,
1058
+ indexWithinCheckpoint,
1059
+ minTxs,
1060
+ });
1061
+ this.log.verbose(
1062
+ `Not enough age-eligible txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (needs ${minTxs} eligible)`,
1063
+ {
1064
+ reason: 'insufficient_txs',
1065
+ blockNumber,
1066
+ slot: this.targetSlot,
1067
+ checkpointNumber: this.checkpointNumber,
1068
+ indexWithinCheckpoint,
1069
+ minTxs,
1070
+ },
669
1071
  );
670
- this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, availableTxs, slot: this.targetSlot });
1072
+ this.eventEmitter.emit('block-tx-count-check-failed', { minTxs, slot: this.targetSlot });
671
1073
  this.metrics.recordBlockProposalFailed('insufficient_txs');
672
- return undefined;
1074
+ return { failure: 'insufficient-txs' };
673
1075
  }
674
1076
 
675
1077
  // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
676
1078
  // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
1079
+ // Block building only executes txs, so we skip loading their proofs unless these same tx objects get attached
1080
+ // to the broadcasted proposals via publishTxsWithProposals.
677
1081
  const pendingTxs = filter(
678
- this.p2pClient.iterateEligiblePendingTxs(),
1082
+ this.p2pClient.iterateEligiblePendingTxs({ includeProof: !!this.config.publishTxsWithProposals }),
679
1083
  tx => !txHashesAlreadyIncluded.has(tx.txHash.toString()),
680
1084
  );
681
1085
 
682
- this.log.debug(
683
- `Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot} with ${availableTxs} available txs`,
684
- { slot: this.targetSlot, blockNumber, indexWithinCheckpoint },
685
- );
686
- this.setStateFn(SequencerState.CREATING_BLOCK, this.targetSlot);
1086
+ this.log.debug(`Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot}`, {
1087
+ slot: this.targetSlot,
1088
+ blockNumber,
1089
+ indexWithinCheckpoint,
1090
+ });
1091
+ this.setState(SequencerState.CREATING_BLOCK);
687
1092
 
688
1093
  // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
689
1094
  // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
690
1095
  // minValidTxs is passed into the builder so it can reject the block *before* updating state.
691
- const minValidTxs = forceCreate ? 0 : (this.config.minValidTxsPerBlock ?? minTxs);
1096
+ // Only the first block of a checkpoint may be empty, since this allows a checkpoint to be created
1097
+ // even if there are no transactions. If an empty block appears after the first, it can't be proven
1098
+ // (there is no rollup circuit shaped to allow this), so the floor for minValidTxs is 1.
1099
+ const configuredMinValidTxs = forceCreate ? 0 : (this.config.minValidTxsPerBlock ?? minTxs);
1100
+ const minValidTxs = indexWithinCheckpoint > 0 ? Math.max(configuredMinValidTxs, 1) : configuredMinValidTxs;
692
1101
  const blockBuilderOptions: BlockBuilderOptions = {
693
1102
  maxTransactions: this.config.maxTxsPerBlock,
694
1103
  maxBlockGas:
@@ -698,8 +1107,9 @@ export class CheckpointProposalJob implements Traceable {
698
1107
  deadline: buildDeadline,
699
1108
  isBuildingProposal: true,
700
1109
  minValidTxs,
701
- maxBlocksPerCheckpoint: this.timetable.maxNumberOfBlocks,
1110
+ maxBlocksPerCheckpoint: this.timetable.getMaxBlocksPerCheckpoint(),
702
1111
  perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
1112
+ perBlockDAAllocationMultiplier: this.config.perBlockDAAllocationMultiplier,
703
1113
  };
704
1114
 
705
1115
  // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
@@ -717,10 +1127,21 @@ export class CheckpointProposalJob implements Traceable {
717
1127
  await this.dropFailedTxsFromP2P(buildResult.failedTxs);
718
1128
 
719
1129
  if (buildResult.status === 'insufficient-valid-txs') {
1130
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1131
+ reason: 'insufficient_valid_txs',
1132
+ slot: this.targetSlot,
1133
+ checkpointNumber: this.checkpointNumber,
1134
+ blockNumber,
1135
+ numTxs: buildResult.processedCount,
1136
+ indexWithinCheckpoint,
1137
+ minValidTxs,
1138
+ });
720
1139
  this.log.warn(
721
1140
  `Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`,
722
1141
  {
1142
+ reason: 'insufficient_valid_txs',
723
1143
  slot: this.targetSlot,
1144
+ checkpointNumber: this.checkpointNumber,
724
1145
  blockNumber,
725
1146
  numTxs: buildResult.processedCount,
726
1147
  indexWithinCheckpoint,
@@ -732,7 +1153,7 @@ export class CheckpointProposalJob implements Traceable {
732
1153
  slot: this.targetSlot,
733
1154
  });
734
1155
  this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
735
- return undefined;
1156
+ return { failure: 'insufficient-valid-txs' };
736
1157
  }
737
1158
 
738
1159
  // Block creation succeeded, emit stats and metrics
@@ -758,10 +1179,13 @@ export class CheckpointProposalJob implements Traceable {
758
1179
  // `buildSlot` is the wall-clock slot during which the block was actually built.
759
1180
  this.eventEmitter.emit('block-proposed', {
760
1181
  blockNumber: block.number,
1182
+ blockHash,
1183
+ checkpointNumber: this.checkpointNumber,
1184
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
761
1185
  slot: this.targetSlot,
762
- buildSlot: this.slotNow,
1186
+ buildSlot: this.getBuildSlot(),
763
1187
  });
764
- this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe());
1188
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
765
1189
 
766
1190
  return { block, usedTxs };
767
1191
  } catch (err: any) {
@@ -769,7 +1193,18 @@ export class CheckpointProposalJob implements Traceable {
769
1193
  reason: err.message,
770
1194
  slot: this.targetSlot,
771
1195
  });
772
- this.log.error(`Error building block`, err, { blockNumber, slot: this.targetSlot });
1196
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1197
+ reason: err instanceof Error ? err.message : String(err),
1198
+ slot: this.targetSlot,
1199
+ checkpointNumber: this.checkpointNumber,
1200
+ blockNumber,
1201
+ });
1202
+ this.log.error(`Error building block`, err, {
1203
+ reason: err instanceof Error ? err.message : String(err),
1204
+ slot: this.targetSlot,
1205
+ checkpointNumber: this.checkpointNumber,
1206
+ blockNumber,
1207
+ });
773
1208
  this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
774
1209
  this.metrics.recordFailedBlock();
775
1210
  return { error: err };
@@ -808,37 +1243,66 @@ export class CheckpointProposalJob implements Traceable {
808
1243
  blockNumber: BlockNumber;
809
1244
  indexWithinCheckpoint: IndexWithinCheckpoint;
810
1245
  buildDeadline: Date | undefined;
811
- }): Promise<{ canStartBuilding: boolean; availableTxs: number; minTxs: number }> {
1246
+ }): Promise<{ canStartBuilding: boolean; minTxs: number }> {
812
1247
  const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
813
1248
 
814
1249
  // We only allow a block with 0 txs in the first block of the checkpoint
815
1250
  const minTxs = indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
816
1251
 
817
- // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
1252
+ // Latest time to keep waiting for txs: wait_for_txs_deadline = block_build_deadline(k) - min_block_duration.
818
1253
  const startBuildingDeadline = buildDeadline
819
- ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000)
1254
+ ? new Date(buildDeadline.getTime() - this.timetable.minBlockDuration * 1000)
820
1255
  : undefined;
821
1256
 
822
- let availableTxs = await this.p2pClient.getPendingTxCount();
823
-
824
- while (!forceCreate && availableTxs < minTxs) {
1257
+ // Gate on age-eligible txs so we don't start building on txs the builder would then filter out for being
1258
+ // too fresh. hasEligiblePendingTxs early-exits once minTxs are eligible instead of counting the whole pool.
1259
+ while (!forceCreate && !(await this.p2pClient.hasEligiblePendingTxs(minTxs))) {
825
1260
  // If we're past deadline, or we have no deadline, give up
826
1261
  const now = this.dateProvider.nowAsDate();
827
1262
  if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
828
- return { canStartBuilding: false, availableTxs, minTxs };
1263
+ return { canStartBuilding: false, minTxs };
829
1264
  }
830
1265
 
831
1266
  // Wait a bit before checking again
832
- this.setStateFn(SequencerState.WAITING_FOR_TXS, this.targetSlot);
1267
+ this.setState(SequencerState.WAITING_FOR_TXS);
833
1268
  this.log.verbose(
834
- `Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (have ${availableTxs} but need ${minTxs})`,
835
- { blockNumber, slot: this.targetSlot, indexWithinCheckpoint },
1269
+ `Waiting for ${minTxs} age-eligible txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot}`,
1270
+ { blockNumber, slot: this.targetSlot, indexWithinCheckpoint, minTxs },
836
1271
  );
837
1272
  await this.waitForTxsPollingInterval();
838
- availableTxs = await this.p2pClient.getPendingTxCount();
839
1273
  }
840
1274
 
841
- return { canStartBuilding: true, availableTxs, minTxs };
1275
+ return { canStartBuilding: true, minTxs };
1276
+ }
1277
+
1278
+ private async getSignedCommitteeAttestations(
1279
+ broadcast: CheckpointProposalBroadcast,
1280
+ ): Promise<{ attestations: CommitteeAttestationsAndSigners; attestationsSignature: Signature } | undefined> {
1281
+ const { proposal, blockProposedAt } = broadcast;
1282
+ this.setState(SequencerState.COLLECTING_ATTESTATIONS);
1283
+ const attestations = await this.waitForAttestations(proposal);
1284
+ if (!attestations) {
1285
+ return undefined;
1286
+ }
1287
+ this.checkpointMetrics.recordCheckpointAttestationDelay(this.dateProvider.now() - blockProposedAt);
1288
+
1289
+ // Proposer must sign over the attestations before pushing them to L1
1290
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
1291
+ try {
1292
+ const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(
1293
+ attestations,
1294
+ signer,
1295
+ this.targetSlot,
1296
+ this.checkpointNumber,
1297
+ );
1298
+ return { attestations, attestationsSignature };
1299
+ } catch (err) {
1300
+ if (this.handleHASigningError(err, 'Attestations signature')) {
1301
+ return;
1302
+ }
1303
+ this.log.error(`Error signing attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
1304
+ return undefined;
1305
+ }
842
1306
  }
843
1307
 
844
1308
  /**
@@ -846,10 +1310,12 @@ export class CheckpointProposalJob implements Traceable {
846
1310
  * This is run after all blocks for the checkpoint have been built.
847
1311
  */
848
1312
  @trackSpan('CheckpointProposalJob.waitForAttestations')
849
- private async waitForAttestations(proposal: CheckpointProposal): Promise<CommitteeAttestationsAndSigners> {
1313
+ private async waitForAttestations(
1314
+ proposal: CheckpointProposal,
1315
+ ): Promise<CommitteeAttestationsAndSigners | undefined> {
850
1316
  if (this.config.fishermanMode) {
851
1317
  this.log.debug('Skipping attestation collection in fisherman mode');
852
- return CommitteeAttestationsAndSigners.empty();
1318
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
853
1319
  }
854
1320
 
855
1321
  const slotNumber = proposal.slotNumber;
@@ -859,7 +1325,7 @@ export class CheckpointProposalJob implements Traceable {
859
1325
  throw new Error('No committee when collecting attestations');
860
1326
  } else if (committee.length === 0) {
861
1327
  this.log.verbose(`Attesting committee is empty`);
862
- return CommitteeAttestationsAndSigners.empty();
1328
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
863
1329
  } else {
864
1330
  this.log.debug(`Attesting committee length is ${committee.length}`, { committee });
865
1331
  }
@@ -868,16 +1334,24 @@ export class CheckpointProposalJob implements Traceable {
868
1334
 
869
1335
  if (this.config.skipCollectingAttestations) {
870
1336
  this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
871
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
872
- return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
1337
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
1338
+ this.logCheckpointAttestations('collected', committee, attestations ?? [], numberOfRequiredAttestations, {
1339
+ reason: 'collect_own_only',
1340
+ });
1341
+ return new CommitteeAttestationsAndSigners(
1342
+ orderAttestations(attestations ?? [], committee),
1343
+ this.getSignatureContext(),
1344
+ );
873
1345
  }
874
1346
 
875
- const attestationTimeAllowed = this.config.enforceTimeTable
876
- ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT)!
877
- : this.l1Constants.slotDuration;
878
- const attestationDeadline = new Date((this.getSlotStartBuildTimestamp() + attestationTimeAllowed) * 1000);
1347
+ // Hard attestation-collection cutoff = the single consensus attestation_deadline (target_slot_start + S - 2E).
1348
+ const attestationDeadlineSeconds = this.timetable.getAttestationDeadline(this.targetSlot);
1349
+ const attestationDeadline = new Date(attestationDeadlineSeconds * 1000);
879
1350
 
880
- this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
1351
+ this.metrics.recordRequiredAttestations(
1352
+ numberOfRequiredAttestations,
1353
+ Math.max(0, attestationDeadline.getTime() - this.dateProvider.now()),
1354
+ );
881
1355
 
882
1356
  const collectAttestationsTimer = new Timer();
883
1357
  let collectedAttestationsCount: number = 0;
@@ -886,6 +1360,7 @@ export class CheckpointProposalJob implements Traceable {
886
1360
  proposal,
887
1361
  numberOfRequiredAttestations,
888
1362
  attestationDeadline,
1363
+ this.checkpointNumber,
889
1364
  );
890
1365
 
891
1366
  collectedAttestationsCount = attestations.length;
@@ -904,28 +1379,71 @@ export class CheckpointProposalJob implements Traceable {
904
1379
 
905
1380
  // Rollup contract requires that the signatures are provided in the order of the committee
906
1381
  const sorted = orderAttestations(trimmed, committee);
1382
+ this.logCheckpointAttestations('collected', committee, attestations, numberOfRequiredAttestations, {
1383
+ submittedCount: trimmed.length,
1384
+ });
907
1385
 
908
1386
  // Manipulate the attestations if we've been configured to do so
909
1387
  if (
910
1388
  this.config.injectFakeAttestation ||
911
1389
  this.config.injectHighSValueAttestation ||
912
1390
  this.config.injectUnrecoverableSignatureAttestation ||
1391
+ this.config.injectYParityAttestation ||
913
1392
  this.config.shuffleAttestationOrdering
914
1393
  ) {
915
1394
  return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
916
1395
  }
917
1396
 
918
- return new CommitteeAttestationsAndSigners(sorted);
1397
+ return new CommitteeAttestationsAndSigners(sorted, this.getSignatureContext());
919
1398
  } catch (err) {
920
1399
  if (err && err instanceof AttestationTimeoutError) {
921
1400
  collectedAttestationsCount = err.collectedCount;
1401
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1402
+ collectedCount: collectedAttestationsCount,
1403
+ reason: 'timeout',
1404
+ });
1405
+ this.log.error(
1406
+ `Timeout while waiting for attestations for checkpoint proposal at slot ${proposal.slotNumber} (collected ${collectedAttestationsCount}/${numberOfRequiredAttestations})`,
1407
+ err,
1408
+ );
1409
+ } else {
1410
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1411
+ collectedCount: collectedAttestationsCount,
1412
+ reason: err instanceof Error ? err.message : String(err),
1413
+ });
1414
+ this.log.error(`Error collecting attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
922
1415
  }
923
- throw err;
1416
+ return undefined;
924
1417
  } finally {
925
1418
  this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
926
1419
  }
927
1420
  }
928
1421
 
1422
+ private logCheckpointAttestations(
1423
+ status: 'collected' | 'failed',
1424
+ committee: EthAddress[],
1425
+ attestations: CheckpointAttestation[] | undefined,
1426
+ requiredAttestations: number,
1427
+ opts: { collectedCount?: number; submittedCount?: number; reason?: string } = {},
1428
+ ) {
1429
+ const signedValidators =
1430
+ attestations
1431
+ ?.map(attestation => attestation.getSender()?.toString())
1432
+ .filter((address): address is `0x${string}` => address !== undefined) ?? [];
1433
+ const collectedCount = opts.collectedCount ?? new Set(signedValidators).size;
1434
+ const missingValidatorCount = status === 'failed' ? Math.max(0, requiredAttestations - collectedCount) : undefined;
1435
+ this.logCheckpointEvent(`attestations-${status}`, `Checkpoint attestations ${status} for slot ${this.targetSlot}`, {
1436
+ slot: this.targetSlot,
1437
+ checkpointNumber: this.checkpointNumber,
1438
+ committeeSize: committee.length,
1439
+ requiredAttestations,
1440
+ collectedAttestations: collectedCount,
1441
+ ...(opts.submittedCount !== undefined && { submittedAttestations: opts.submittedCount }),
1442
+ ...(missingValidatorCount !== undefined && { missingValidatorCount }),
1443
+ ...(opts.reason !== undefined && { reason: opts.reason }),
1444
+ });
1445
+ }
1446
+
929
1447
  /** Breaks the attestations before publishing based on attack configs */
930
1448
  private manipulateAttestations(
931
1449
  slotNumber: SlotNumber,
@@ -969,7 +1487,20 @@ export class CheckpointProposalJob implements Traceable {
969
1487
  unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
970
1488
  }
971
1489
  }
972
- return new CommitteeAttestationsAndSigners(attestations);
1490
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1491
+ }
1492
+
1493
+ if (this.config.injectYParityAttestation) {
1494
+ // Force every non-proposer signed slot's recovery byte to yParity (v ∈ {0, 1}) form in the packed L1
1495
+ // tuple, after packAttestations has canonicalized it. The proposer's own slot is left canonical so
1496
+ // propose() still passes verifyProposer. Models a malicious proposer landing a checkpoint L1 accepts
1497
+ // but that can never be proven (ECDSA.recover rejects v ∉ {27, 28}).
1498
+ this.log.warn(`Injecting yParity attestations in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
1499
+ return new MaliciousYParityCommitteeAttestationsAndSigners(
1500
+ attestations,
1501
+ proposerIndex,
1502
+ this.getSignatureContext(),
1503
+ );
973
1504
  }
974
1505
 
975
1506
  if (this.config.shuffleAttestationOrdering) {
@@ -991,11 +1522,11 @@ export class CheckpointProposalJob implements Traceable {
991
1522
  [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
992
1523
  }
993
1524
 
994
- const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
995
- return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
1525
+ const signers = new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext()).getSigners();
1526
+ return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers, this.getSignatureContext());
996
1527
  }
997
1528
 
998
- return new CommitteeAttestationsAndSigners(attestations);
1529
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
999
1530
  }
1000
1531
 
1001
1532
  private async dropFailedTxsFromP2P(failedTxs: FailedTx[]) {
@@ -1004,7 +1535,11 @@ export class CheckpointProposalJob implements Traceable {
1004
1535
  }
1005
1536
  const failedTxData = failedTxs.map(fail => fail.tx);
1006
1537
  const failedTxHashes = failedTxData.map(tx => tx.getTxHash());
1007
- this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
1538
+ const failures = failedTxs.map(fail => ({ txHash: fail.tx.getTxHash().toString(), reason: fail.error.message }));
1539
+ this.log.warn(
1540
+ `Dropping ${failedTxs.length} txs from mempool due to failures during block building for slot ${this.targetSlot}`,
1541
+ { slot: this.targetSlot, checkpointNumber: this.checkpointNumber, failures },
1542
+ );
1008
1543
  await this.p2pClient.handleFailedExecution(failedTxHashes);
1009
1544
  }
1010
1545
 
@@ -1012,9 +1547,13 @@ export class CheckpointProposalJob implements Traceable {
1012
1547
  * Adds the proposed block to the archiver so it's available via P2P.
1013
1548
  * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
1014
1549
  * would never receive its own block without this explicit sync.
1550
+ *
1551
+ * In fisherman mode we skip this push: the fisherman builds blocks locally for validation
1552
+ * and fee analysis only, and pushing them to the archiver causes spurious reorg cascades
1553
+ * whenever the real proposer's block arrives from L1.
1015
1554
  */
1016
1555
  private async syncProposedBlockToArchiver(block: L2Block): Promise<void> {
1017
- if (this.config.skipPushProposedBlocksToArchiver) {
1556
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1018
1557
  this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
1019
1558
  blockNumber: block.number,
1020
1559
  slot: block.header.globalVariables.slotNumber,
@@ -1028,6 +1567,41 @@ export class CheckpointProposalJob implements Traceable {
1028
1567
  await this.blockSink.addBlock(block);
1029
1568
  }
1030
1569
 
1570
+ /**
1571
+ * Adds the proposed checkpoint to the archiver so the proposer's optimistic proposed-checkpoint
1572
+ * tip advances locally. Gossip doesn't echo our own messages back, so without this the proposer
1573
+ * would never see its own proposed checkpoint and couldn't pipeline the next slot.
1574
+ *
1575
+ * Skipped whenever proposed blocks aren't pushed (`skipPushProposedBlocksToArchiver`, fisherman
1576
+ * mode): the archiver derives the checkpoint archive from its stored blocks, so without them the
1577
+ * push would fail. All blocks were already added (and awaited) during block building, so this
1578
+ * needs no retry — they are guaranteed present by the time we get here.
1579
+ */
1580
+ private async syncProposedCheckpointToArchiver(
1581
+ checkpoint: Checkpoint,
1582
+ blockCount: number,
1583
+ feeAssetPriceModifier: bigint,
1584
+ ): Promise<void> {
1585
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1586
+ return;
1587
+ }
1588
+ const startBlock = BlockNumber(this.syncedToBlockNumber + 1);
1589
+ this.log.debug(`Syncing proposed checkpoint ${this.checkpointNumber} to archiver`, {
1590
+ checkpointNumber: this.checkpointNumber,
1591
+ slot: this.targetSlot,
1592
+ startBlock,
1593
+ blockCount,
1594
+ });
1595
+ await this.blockSink.addProposedCheckpoint({
1596
+ header: checkpoint.header,
1597
+ checkpointNumber: this.checkpointNumber,
1598
+ startBlock,
1599
+ blockCount,
1600
+ totalManaUsed: checkpoint.header.totalManaUsed.toBigInt(),
1601
+ feeAssetPriceModifier,
1602
+ });
1603
+ }
1604
+
1031
1605
  /** Runs fee analysis and logs checkpoint outcome as fisherman */
1032
1606
  private async handleCheckpointEndAsFisherman(checkpoint: Checkpoint | undefined) {
1033
1607
  // Perform L1 fee analysis before clearing requests
@@ -1075,76 +1649,9 @@ export class CheckpointProposalJob implements Traceable {
1075
1649
  return false;
1076
1650
  }
1077
1651
 
1078
- /**
1079
- * In times of congestion we need to simulate using the correct fee header override for the previous block
1080
- * We calculate the correct fee header values.
1081
- *
1082
- * If we are in block 1, or the checkpoint we are querying does not exist, we return undefined. However
1083
- * If we are pipelining - where this function is called, the grandparentCheckpointNumber should always exist
1084
- * @param parentCheckpointNumber
1085
- * @returns
1086
- */
1087
- protected async computeForceProposedFeeHeader(parentCheckpointNumber: CheckpointNumber): Promise<
1088
- | {
1089
- checkpointNumber: CheckpointNumber;
1090
- feeHeader: FeeHeader;
1091
- }
1092
- | undefined
1093
- > {
1094
- if (!this.proposedCheckpointData) {
1095
- return undefined;
1096
- }
1097
-
1098
- const rollup = this.publisher.rollupContract;
1099
- const grandparentCheckpointNumber = CheckpointNumber(this.checkpointNumber - 2);
1100
- try {
1101
- const [grandparentCheckpoint, manaTarget] = await Promise.all([
1102
- rollup.getCheckpoint(grandparentCheckpointNumber),
1103
- rollup.getManaTarget(),
1104
- ]);
1105
-
1106
- if (!grandparentCheckpoint || !grandparentCheckpoint.feeHeader) {
1107
- this.log.error(
1108
- `Grandparent checkpoint or its feeHeader is undefined for checkpointNumber=${grandparentCheckpointNumber.toString()}`,
1109
- );
1110
- return undefined;
1111
- } else {
1112
- const parentFeeHeader = RollupContract.computeChildFeeHeader(
1113
- grandparentCheckpoint.feeHeader,
1114
- this.proposedCheckpointData.totalManaUsed,
1115
- this.proposedCheckpointData.feeAssetPriceModifier,
1116
- manaTarget,
1117
- );
1118
- return { checkpointNumber: parentCheckpointNumber, feeHeader: parentFeeHeader };
1119
- }
1120
- } catch (err) {
1121
- this.log.error(
1122
- `Failed to fetch grandparent checkpoint or mana target for checkpointNumber=${grandparentCheckpointNumber.toString()}: ${err}`,
1123
- );
1124
- return undefined;
1125
- }
1126
- }
1127
-
1128
- /** Waits until a specific time within the current slot */
1129
- @trackSpan('CheckpointProposalJob.waitUntilTimeInSlot')
1130
- protected async waitUntilTimeInSlot(targetSecondsIntoSlot: number): Promise<void> {
1131
- const slotStartTimestamp = this.getSlotStartBuildTimestamp();
1132
- const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
1133
- await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
1134
- }
1135
-
1136
1652
  /** Waits the polling interval for transactions. Extracted for test overriding. */
1137
1653
  protected async waitForTxsPollingInterval(): Promise<void> {
1138
- await sleep(TXS_POLLING_MS);
1139
- }
1140
-
1141
- private getSlotStartBuildTimestamp(): number {
1142
- return getSlotStartBuildTimestamp(this.slotNow, this.l1Constants);
1143
- }
1144
-
1145
- private getSecondsIntoSlot(): number {
1146
- const slotStartTimestamp = this.getSlotStartBuildTimestamp();
1147
- return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
1654
+ await this.awaitInterruptibleSleep(TXS_POLLING_MS);
1148
1655
  }
1149
1656
 
1150
1657
  public getPublisher() {