@aztec/prover-node 0.0.0-test.0 → 0.0.1-commit.001888fc

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 (82) hide show
  1. package/dest/actions/download-epoch-proving-job.d.ts +18 -0
  2. package/dest/actions/download-epoch-proving-job.d.ts.map +1 -0
  3. package/dest/actions/download-epoch-proving-job.js +37 -0
  4. package/dest/actions/index.d.ts +3 -0
  5. package/dest/actions/index.d.ts.map +1 -0
  6. package/dest/actions/index.js +2 -0
  7. package/dest/actions/rerun-epoch-proving-job.d.ts +12 -0
  8. package/dest/actions/rerun-epoch-proving-job.d.ts.map +1 -0
  9. package/dest/actions/rerun-epoch-proving-job.js +40 -0
  10. package/dest/actions/upload-epoch-proof-failure.d.ts +15 -0
  11. package/dest/actions/upload-epoch-proof-failure.d.ts.map +1 -0
  12. package/dest/actions/upload-epoch-proof-failure.js +78 -0
  13. package/dest/bin/run-failed-epoch.d.ts +2 -0
  14. package/dest/bin/run-failed-epoch.d.ts.map +1 -0
  15. package/dest/bin/run-failed-epoch.js +70 -0
  16. package/dest/config.d.ts +17 -16
  17. package/dest/config.d.ts.map +1 -1
  18. package/dest/config.js +93 -28
  19. package/dest/factory.d.ts +26 -18
  20. package/dest/factory.d.ts.map +1 -1
  21. package/dest/factory.js +72 -42
  22. package/dest/index.d.ts +3 -2
  23. package/dest/index.d.ts.map +1 -1
  24. package/dest/index.js +2 -1
  25. package/dest/job/epoch-proving-job-data.d.ts +18 -0
  26. package/dest/job/epoch-proving-job-data.d.ts.map +1 -0
  27. package/dest/job/epoch-proving-job-data.js +59 -0
  28. package/dest/job/epoch-proving-job.d.ts +27 -18
  29. package/dest/job/epoch-proving-job.d.ts.map +1 -1
  30. package/dest/job/epoch-proving-job.js +604 -97
  31. package/dest/metrics.d.ts +40 -5
  32. package/dest/metrics.d.ts.map +1 -1
  33. package/dest/metrics.js +136 -73
  34. package/dest/monitors/epoch-monitor.d.ts +5 -2
  35. package/dest/monitors/epoch-monitor.d.ts.map +1 -1
  36. package/dest/monitors/epoch-monitor.js +18 -15
  37. package/dest/monitors/index.d.ts +1 -1
  38. package/dest/prover-node-publisher.d.ts +19 -19
  39. package/dest/prover-node-publisher.d.ts.map +1 -1
  40. package/dest/prover-node-publisher.js +90 -84
  41. package/dest/prover-node.d.ts +61 -46
  42. package/dest/prover-node.d.ts.map +1 -1
  43. package/dest/prover-node.js +592 -135
  44. package/dest/prover-publisher-factory.d.ts +25 -0
  45. package/dest/prover-publisher-factory.d.ts.map +1 -0
  46. package/dest/prover-publisher-factory.js +28 -0
  47. package/dest/test/index.d.ts +5 -3
  48. package/dest/test/index.d.ts.map +1 -1
  49. package/dest/test/index.js +1 -3
  50. package/package.json +40 -33
  51. package/src/actions/download-epoch-proving-job.ts +44 -0
  52. package/src/actions/index.ts +2 -0
  53. package/src/actions/rerun-epoch-proving-job.ts +63 -0
  54. package/src/actions/upload-epoch-proof-failure.ts +88 -0
  55. package/src/bin/run-failed-epoch.ts +80 -0
  56. package/src/config.ts +123 -45
  57. package/src/factory.ts +146 -66
  58. package/src/index.ts +2 -1
  59. package/src/job/epoch-proving-job-data.ts +82 -0
  60. package/src/job/epoch-proving-job.ts +295 -85
  61. package/src/metrics.ts +153 -72
  62. package/src/monitors/epoch-monitor.ts +21 -17
  63. package/src/prover-node-publisher.ts +139 -119
  64. package/src/prover-node.ts +238 -149
  65. package/src/prover-publisher-factory.ts +45 -0
  66. package/src/test/index.ts +7 -4
  67. package/dest/http.d.ts +0 -8
  68. package/dest/http.d.ts.map +0 -1
  69. package/dest/http.js +0 -9
  70. package/dest/prover-coordination/config.d.ts +0 -7
  71. package/dest/prover-coordination/config.d.ts.map +0 -1
  72. package/dest/prover-coordination/config.js +0 -11
  73. package/dest/prover-coordination/factory.d.ts +0 -22
  74. package/dest/prover-coordination/factory.d.ts.map +0 -1
  75. package/dest/prover-coordination/factory.js +0 -42
  76. package/dest/prover-coordination/index.d.ts +0 -3
  77. package/dest/prover-coordination/index.d.ts.map +0 -1
  78. package/dest/prover-coordination/index.js +0 -2
  79. package/src/http.ts +0 -13
  80. package/src/prover-coordination/config.ts +0 -17
  81. package/src/prover-coordination/factory.ts +0 -72
  82. package/src/prover-coordination/index.ts +0 -2
@@ -1,56 +1,77 @@
1
+ import { NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP } from '@aztec/constants';
1
2
  import { asyncPool } from '@aztec/foundation/async-pool';
2
- import { createLogger } from '@aztec/foundation/log';
3
- import { promiseWithResolvers } from '@aztec/foundation/promise';
3
+ import { BlockNumber, EpochNumber } from '@aztec/foundation/branded-types';
4
+ import { padArrayEnd } from '@aztec/foundation/collection';
5
+ import { Fr } from '@aztec/foundation/curves/bn254';
6
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
7
+ import { RunningPromise, promiseWithResolvers } from '@aztec/foundation/promise';
4
8
  import { Timer } from '@aztec/foundation/timer';
9
+ import { AVM_MAX_CONCURRENT_SIMULATIONS } from '@aztec/native';
10
+ import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
11
+ import { protocolContractsHash } from '@aztec/protocol-contracts';
12
+ import { buildFinalBlobChallenges } from '@aztec/prover-client/helpers';
5
13
  import type { PublicProcessor, PublicProcessorFactory } from '@aztec/simulator/server';
14
+ import { PublicSimulatorConfig } from '@aztec/stdlib/avm';
6
15
  import type { L2Block, L2BlockSource } from '@aztec/stdlib/block';
16
+ import type { Checkpoint } from '@aztec/stdlib/checkpoint';
7
17
  import {
8
18
  type EpochProver,
9
19
  type EpochProvingJobState,
10
20
  EpochProvingJobTerminalState,
11
21
  type ForkMerkleTreeOperations,
12
22
  } from '@aztec/stdlib/interfaces/server';
13
- import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
23
+ import { CheckpointConstantData } from '@aztec/stdlib/rollup';
24
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
14
25
  import type { ProcessedTx, Tx } from '@aztec/stdlib/tx';
15
26
  import { Attributes, type Traceable, type Tracer, trackSpan } from '@aztec/telemetry-client';
16
27
 
17
28
  import * as crypto from 'node:crypto';
18
29
 
19
- import type { ProverNodeMetrics } from '../metrics.js';
30
+ import type { ProverNodeJobMetrics } from '../metrics.js';
20
31
  import type { ProverNodePublisher } from '../prover-node-publisher.js';
32
+ import { type EpochProvingJobData, validateEpochProvingJobData } from './epoch-proving-job-data.js';
33
+
34
+ export type EpochProvingJobOptions = {
35
+ parallelBlockLimit?: number;
36
+ skipEpochCheck?: boolean;
37
+ skipSubmitProof?: boolean;
38
+ };
21
39
 
22
40
  /**
23
- * Job that grabs a range of blocks from the unfinalised chain from L1, gets their txs given their hashes,
41
+ * Job that grabs a range of blocks from the unfinalized chain from L1, gets their txs given their hashes,
24
42
  * re-executes their public calls, generates a rollup proof, and submits it to L1. This job will update the
25
43
  * world state as part of public call execution via the public processor.
26
44
  */
27
45
  export class EpochProvingJob implements Traceable {
28
46
  private state: EpochProvingJobState = 'initialized';
29
- private log = createLogger('prover-node:epoch-proving-job');
47
+ private log: Logger;
30
48
  private uuid: string;
31
49
 
32
50
  private runPromise: Promise<void> | undefined;
51
+ private epochCheckPromise: RunningPromise | undefined;
33
52
  private deadlineTimeoutHandler: NodeJS.Timeout | undefined;
34
53
 
35
54
  public readonly tracer: Tracer;
36
55
 
37
56
  constructor(
38
- private dbProvider: ForkMerkleTreeOperations,
39
- private epochNumber: bigint,
40
- private blocks: L2Block[],
41
- private txs: Tx[],
57
+ private data: EpochProvingJobData,
58
+ private dbProvider: Pick<ForkMerkleTreeOperations, 'fork'>,
42
59
  private prover: EpochProver,
43
60
  private publicProcessorFactory: PublicProcessorFactory,
44
- private publisher: ProverNodePublisher,
45
- private l2BlockSource: L2BlockSource,
46
- private l1ToL2MessageSource: L1ToL2MessageSource,
47
- private metrics: ProverNodeMetrics,
61
+ private publisher: Pick<ProverNodePublisher, 'submitEpochProof'>,
62
+ private l2BlockSource: L2BlockSource | undefined,
63
+ private metrics: ProverNodeJobMetrics,
48
64
  private deadline: Date | undefined,
49
- private config: { parallelBlockLimit: number } = { parallelBlockLimit: 32 },
50
- private cleanUp: (job: EpochProvingJob) => Promise<void> = () => Promise.resolve(),
65
+ private config: EpochProvingJobOptions,
66
+ bindings?: LoggerBindings,
51
67
  ) {
68
+ validateEpochProvingJobData(data);
52
69
  this.uuid = crypto.randomUUID();
53
- this.tracer = metrics.client.getTracer('EpochProvingJob');
70
+ this.log = createLogger('prover-node:epoch-proving-job', {
71
+ ...bindings,
72
+ instanceId: `epoch-${data.epochNumber}`,
73
+ });
74
+ this.tracer = metrics.tracer;
54
75
  }
55
76
 
56
77
  public getId(): string {
@@ -61,27 +82,63 @@ export class EpochProvingJob implements Traceable {
61
82
  return this.state;
62
83
  }
63
84
 
64
- public getEpochNumber(): bigint {
65
- return this.epochNumber;
85
+ public getEpochNumber(): EpochNumber {
86
+ return this.data.epochNumber;
87
+ }
88
+
89
+ public getDeadline(): Date | undefined {
90
+ return this.deadline;
91
+ }
92
+
93
+ public getProvingData(): EpochProvingJobData {
94
+ return this.data;
95
+ }
96
+
97
+ private get epochNumber() {
98
+ return this.data.epochNumber;
99
+ }
100
+
101
+ private get checkpoints() {
102
+ return this.data.checkpoints;
103
+ }
104
+
105
+ private get txs() {
106
+ return this.data.txs;
107
+ }
108
+
109
+ private get attestations() {
110
+ return this.data.attestations;
66
111
  }
67
112
 
68
113
  /**
69
114
  * Proves the given epoch and submits the proof to L1.
70
115
  */
71
116
  @trackSpan('EpochProvingJob.run', function () {
72
- return { [Attributes.EPOCH_NUMBER]: Number(this.epochNumber) };
117
+ return { [Attributes.EPOCH_NUMBER]: this.data.epochNumber };
73
118
  })
74
119
  public async run() {
75
120
  this.scheduleDeadlineStop();
121
+ if (!this.config.skipEpochCheck) {
122
+ await this.scheduleEpochCheck();
123
+ }
76
124
 
77
- const epochNumber = Number(this.epochNumber);
78
- const epochSizeBlocks = this.blocks.length;
79
- const epochSizeTxs = this.blocks.reduce((total, current) => total + current.body.txEffects.length, 0);
80
- const [fromBlock, toBlock] = [this.blocks[0].number, this.blocks.at(-1)!.number];
81
- this.log.info(`Starting epoch ${epochNumber} proving job with blocks ${fromBlock} to ${toBlock}`, {
125
+ const attestations = this.attestations.map(attestation => attestation.toViem());
126
+ const epochNumber = this.epochNumber;
127
+ const epochSizeCheckpoints = this.checkpoints.length;
128
+ const epochSizeBlocks = this.checkpoints.reduce((accum, checkpoint) => accum + checkpoint.blocks.length, 0);
129
+ const epochSizeTxs = this.checkpoints.reduce(
130
+ (accum, checkpoint) =>
131
+ accum + checkpoint.blocks.reduce((accumC, block) => accumC + block.body.txEffects.length, 0),
132
+ 0,
133
+ );
134
+ const fromCheckpoint = this.checkpoints[0].number;
135
+ const toCheckpoint = this.checkpoints.at(-1)!.number;
136
+ const fromBlock = this.checkpoints[0].blocks[0].number;
137
+ const toBlock = this.checkpoints.at(-1)!.blocks.at(-1)!.number;
138
+ this.log.info(`Starting epoch ${epochNumber} proving job with checkpoints ${fromCheckpoint} to ${toCheckpoint}`, {
82
139
  fromBlock,
83
140
  toBlock,
84
- epochSizeBlocks,
141
+ epochSizeTxs,
85
142
  epochNumber,
86
143
  uuid: this.uuid,
87
144
  });
@@ -92,96 +149,215 @@ export class EpochProvingJob implements Traceable {
92
149
  this.runPromise = promise;
93
150
 
94
151
  try {
95
- this.prover.startNewEpoch(epochNumber, fromBlock, epochSizeBlocks);
96
- await this.prover.startTubeCircuits(this.txs);
152
+ const blobTimer = new Timer();
153
+ const blobFieldsPerCheckpoint = this.checkpoints.map(checkpoint => checkpoint.toBlobFields());
154
+ const finalBlobBatchingChallenges = await buildFinalBlobChallenges(blobFieldsPerCheckpoint);
155
+ this.metrics.recordBlobProcessing(blobTimer.ms());
97
156
 
98
- await asyncPool(this.config.parallelBlockLimit, this.blocks, async block => {
99
- this.checkState();
157
+ this.prover.startNewEpoch(epochNumber, epochSizeCheckpoints, finalBlobBatchingChallenges);
158
+ const chonkTimer = new Timer();
159
+ await this.prover.startChonkVerifierCircuits(Array.from(this.txs.values()));
160
+ this.metrics.recordChonkVerifier(chonkTimer.ms());
100
161
 
101
- const globalVariables = block.header.globalVariables;
102
- const txs = await this.getTxs(block);
103
- const l1ToL2Messages = await this.getL1ToL2Messages(block);
104
- const previousHeader = (await this.getBlockHeader(block.number - 1))!;
105
-
106
- this.log.verbose(`Starting processing block ${block.number}`, {
107
- number: block.number,
108
- blockHash: (await block.hash()).toString(),
109
- lastArchive: block.header.lastArchive.root,
110
- noteHashTreeRoot: block.header.state.partial.noteHashTree.root,
111
- nullifierTreeRoot: block.header.state.partial.nullifierTree.root,
112
- publicDataTreeRoot: block.header.state.partial.publicDataTree.root,
113
- previousHeader: previousHeader.hash(),
114
- uuid: this.uuid,
115
- ...globalVariables,
162
+ // Everything in the epoch should have the same chainId and version.
163
+ const { chainId, version } = this.checkpoints[0].blocks[0].header.globalVariables;
164
+
165
+ const previousBlockHeaders = this.gatherPreviousBlockHeaders();
166
+
167
+ const allCheckpointsTimer = new Timer();
168
+
169
+ const parallelism = this.config.parallelBlockLimit
170
+ ? this.config.parallelBlockLimit
171
+ : AVM_MAX_CONCURRENT_SIMULATIONS > 0
172
+ ? AVM_MAX_CONCURRENT_SIMULATIONS
173
+ : this.checkpoints.length;
174
+
175
+ await asyncPool(parallelism, this.checkpoints, async checkpoint => {
176
+ this.checkState();
177
+ const checkpointTimer = new Timer();
178
+
179
+ const checkpointIndex = checkpoint.number - fromCheckpoint;
180
+ const checkpointConstants = CheckpointConstantData.from({
181
+ chainId,
182
+ version,
183
+ vkTreeRoot: getVKTreeRoot(),
184
+ protocolContractsHash: protocolContractsHash,
185
+ proverId: this.prover.getProverId().toField(),
186
+ slotNumber: checkpoint.header.slotNumber,
187
+ coinbase: checkpoint.header.coinbase,
188
+ feeRecipient: checkpoint.header.feeRecipient,
189
+ gasFees: checkpoint.header.gasFees,
116
190
  });
191
+ const previousHeader = previousBlockHeaders[checkpointIndex];
192
+ const l1ToL2Messages = this.getL1ToL2Messages(checkpoint);
117
193
 
118
- // Start block proving
119
- await this.prover.startNewBlock(globalVariables, l1ToL2Messages, previousHeader);
120
-
121
- // Process public fns
122
- const db = await this.dbProvider.fork(block.number - 1);
123
- const publicProcessor = this.publicProcessorFactory.create(db, globalVariables, true);
124
- const processed = await this.processTxs(publicProcessor, txs);
125
- await this.prover.addTxs(processed);
126
- await db.close();
127
- this.log.verbose(`Processed all ${txs.length} txs for block ${block.number}`, {
128
- blockNumber: block.number,
129
- blockHash: (await block.hash()).toString(),
194
+ this.log.verbose(`Starting processing checkpoint ${checkpoint.number}`, {
195
+ number: checkpoint.number,
196
+ checkpointHash: checkpoint.hash().toString(),
197
+ lastArchive: checkpoint.header.lastArchiveRoot,
198
+ previousHeader: previousHeader.hash(),
130
199
  uuid: this.uuid,
131
200
  });
132
201
 
133
- // Mark block as completed to pad it
134
- await this.prover.setBlockCompleted(block.number, block.header);
202
+ await this.prover.startNewCheckpoint(
203
+ checkpointIndex,
204
+ checkpointConstants,
205
+ l1ToL2Messages,
206
+ checkpoint.blocks.length,
207
+ previousHeader,
208
+ );
209
+
210
+ for (let blockIndex = 0; blockIndex < checkpoint.blocks.length; blockIndex++) {
211
+ const blockTimer = new Timer();
212
+ const block = checkpoint.blocks[blockIndex];
213
+ const globalVariables = block.header.globalVariables;
214
+ const txs = this.getTxs(block);
215
+
216
+ this.log.verbose(`Starting processing block ${block.number}`, {
217
+ number: block.number,
218
+ blockHash: (await block.hash()).toString(),
219
+ lastArchive: block.header.lastArchive.root,
220
+ noteHashTreeRoot: block.header.state.partial.noteHashTree.root,
221
+ nullifierTreeRoot: block.header.state.partial.nullifierTree.root,
222
+ publicDataTreeRoot: block.header.state.partial.publicDataTree.root,
223
+ ...globalVariables,
224
+ numTxs: txs.length,
225
+ });
226
+
227
+ // Start block proving
228
+ await this.prover.startNewBlock(block.number, globalVariables.timestamp, txs.length);
229
+
230
+ // Process public fns. L1 to L2 messages are only inserted for the first block of a checkpoint,
231
+ // as the fork for subsequent blocks already includes them from the previous block's synced state.
232
+ const db = await this.createFork(
233
+ BlockNumber(block.number - 1),
234
+ blockIndex === 0 ? l1ToL2Messages : undefined,
235
+ );
236
+ const config = PublicSimulatorConfig.from({
237
+ proverId: this.prover.getProverId().toField(),
238
+ skipFeeEnforcement: false,
239
+ collectDebugLogs: false,
240
+ collectHints: true,
241
+ collectPublicInputs: true,
242
+ collectStatistics: false,
243
+ });
244
+ const publicProcessor = this.publicProcessorFactory.create(db, globalVariables, config);
245
+ const processed = await this.processTxs(publicProcessor, txs);
246
+ await this.prover.addTxs(processed);
247
+ await db.close();
248
+ this.log.verbose(`Processed all ${txs.length} txs for block ${block.number}`, {
249
+ blockNumber: block.number,
250
+ blockHash: (await block.hash()).toString(),
251
+ uuid: this.uuid,
252
+ });
253
+
254
+ // Mark block as completed to pad it
255
+ const expectedBlockHeader = block.header;
256
+ await this.prover.setBlockCompleted(block.number, expectedBlockHeader);
257
+ this.metrics.recordBlockProcessing(blockTimer.ms());
258
+ }
259
+ this.metrics.recordCheckpointProcessing(checkpointTimer.ms());
135
260
  });
261
+ this.metrics.recordAllCheckpointsProcessing(allCheckpointsTimer.ms());
136
262
 
137
263
  const executionTime = timer.ms();
138
264
 
139
265
  this.progressState('awaiting-prover');
140
- const { publicInputs, proof } = await this.prover.finaliseEpoch();
141
- this.log.info(`Finalised proof for epoch ${epochNumber}`, { epochNumber, uuid: this.uuid, duration: timer.ms() });
266
+ const { publicInputs, proof, batchedBlobInputs } = await this.prover.finalizeEpoch();
267
+ this.log.info(`Finalized proof for epoch ${epochNumber}`, { epochNumber, uuid: this.uuid, duration: timer.ms() });
142
268
 
143
269
  this.progressState('publishing-proof');
144
- const success = await this.publisher.submitEpochProof({ fromBlock, toBlock, epochNumber, publicInputs, proof });
270
+
271
+ if (this.config.skipSubmitProof) {
272
+ this.log.info(
273
+ `Proof publishing is disabled. Dropping valid proof for epoch ${epochNumber} (checkpoints ${fromCheckpoint} to ${toCheckpoint})`,
274
+ );
275
+ this.state = 'completed';
276
+ this.metrics.recordProvingJob(executionTime, timer.ms(), epochSizeCheckpoints, epochSizeBlocks, epochSizeTxs);
277
+ return;
278
+ }
279
+
280
+ const success = await this.publisher.submitEpochProof({
281
+ fromCheckpoint,
282
+ toCheckpoint,
283
+ epochNumber,
284
+ publicInputs,
285
+ proof,
286
+ batchedBlobInputs,
287
+ attestations,
288
+ });
145
289
  if (!success) {
146
290
  throw new Error('Failed to submit epoch proof to L1');
147
291
  }
148
292
 
149
- this.log.info(`Submitted proof for epoch ${epochNumber} (blocks ${fromBlock} to ${toBlock})`, {
293
+ this.log.info(`Submitted proof for epoch ${epochNumber} (checkpoints ${fromCheckpoint} to ${toCheckpoint})`, {
150
294
  epochNumber,
151
295
  uuid: this.uuid,
152
296
  });
153
297
  this.state = 'completed';
154
- this.metrics.recordProvingJob(executionTime, timer.ms(), epochSizeBlocks, epochSizeTxs);
298
+ this.metrics.recordProvingJob(executionTime, timer.ms(), epochSizeCheckpoints, epochSizeBlocks, epochSizeTxs);
155
299
  } catch (err: any) {
156
300
  if (err && err.name === 'HaltExecutionError') {
157
- this.log.warn(`Halted execution of epoch ${epochNumber} prover job`, { uuid: this.uuid, epochNumber });
301
+ this.log.warn(`Halted execution of epoch ${epochNumber} prover job`, {
302
+ uuid: this.uuid,
303
+ epochNumber,
304
+ details: err.message,
305
+ });
158
306
  return;
159
307
  }
160
308
  this.log.error(`Error running epoch ${epochNumber} prover job`, err, { uuid: this.uuid, epochNumber });
161
- this.state = 'failed';
309
+ if (this.state === 'processing' || this.state === 'awaiting-prover' || this.state === 'publishing-proof') {
310
+ this.state = 'failed';
311
+ }
162
312
  } finally {
163
313
  clearTimeout(this.deadlineTimeoutHandler);
164
- await this.cleanUp(this);
314
+ await this.epochCheckPromise?.stop();
165
315
  await this.prover.stop();
166
316
  resolve();
167
317
  }
168
318
  }
169
319
 
320
+ /**
321
+ * Create a new db fork for tx processing, optionally inserting L1 to L2 messages.
322
+ * L1 to L2 messages should only be inserted for the first block in a checkpoint,
323
+ * as subsequent blocks' synced state already includes them.
324
+ * REFACTOR: The prover already spawns a db fork of its own for each block, so we may be able to do away with just one fork.
325
+ */
326
+ private async createFork(blockNumber: BlockNumber, l1ToL2Messages: Fr[] | undefined) {
327
+ this.log.verbose(`Creating fork at ${blockNumber}`, { blockNumber });
328
+ const db = await this.dbProvider.fork(blockNumber);
329
+
330
+ if (l1ToL2Messages !== undefined) {
331
+ this.log.verbose(`Inserting ${l1ToL2Messages.length} L1 to L2 messages in fork`, {
332
+ blockNumber,
333
+ l1ToL2Messages: l1ToL2Messages.map(m => m.toString()),
334
+ });
335
+ const l1ToL2MessagesPadded = padArrayEnd<Fr, number>(
336
+ l1ToL2Messages,
337
+ Fr.ZERO,
338
+ NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP,
339
+ 'Too many L1 to L2 messages',
340
+ );
341
+ await db.appendLeaves(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, l1ToL2MessagesPadded);
342
+ }
343
+
344
+ return db;
345
+ }
346
+
170
347
  private progressState(state: EpochProvingJobState) {
171
348
  this.checkState();
172
349
  this.state = state;
173
350
  }
174
351
 
175
352
  private checkState() {
176
- if (this.state === 'timed-out' || this.state === 'stopped' || this.state === 'failed') {
353
+ if (this.state === 'timed-out' || this.state === 'stopped' || this.state === 'failed' || this.state === 'reorg') {
177
354
  throw new HaltExecutionError(this.state);
178
355
  }
179
356
  }
180
357
 
181
- public async stop(state: EpochProvingJobState = 'stopped') {
358
+ public async stop(state: EpochProvingJobTerminalState = 'stopped') {
182
359
  this.state = state;
183
360
  this.prover.cancel();
184
- // TODO(palla/prover): Stop the publisher as well
185
361
  if (this.runPromise) {
186
362
  await this.runPromise;
187
363
  }
@@ -207,24 +383,55 @@ export class EpochProvingJob implements Traceable {
207
383
  }
208
384
  }
209
385
 
210
- /* Returns the header for the given block number, or the genesis block for block zero. */
211
- private async getBlockHeader(blockNumber: number) {
212
- if (blockNumber === 0) {
213
- return (await this.dbProvider.fork()).getInitialHeader();
386
+ /**
387
+ * Kicks off a running promise that queries the archiver for the set of L2 blocks of the current epoch.
388
+ * If those change, stops the proving job with a `rerun` state, so the node re-enqueues it.
389
+ */
390
+ private async scheduleEpochCheck() {
391
+ const l2BlockSource = this.l2BlockSource;
392
+ if (!l2BlockSource) {
393
+ this.log.warn(`No L2 block source available, skipping epoch check`);
394
+ return;
214
395
  }
215
- return this.l2BlockSource.getBlockHeader(blockNumber);
396
+
397
+ const intervalMs = Math.ceil((await l2BlockSource.getL1Constants()).ethereumSlotDuration / 2) * 1000;
398
+ this.epochCheckPromise = new RunningPromise(
399
+ async () => {
400
+ const blockHeaders = await l2BlockSource.getCheckpointedBlockHeadersForEpoch(this.epochNumber);
401
+ const blockHashes = await Promise.all(blockHeaders.map(header => header.hash()));
402
+ const thisBlocks = this.checkpoints.flatMap(checkpoint => checkpoint.blocks);
403
+ const thisBlockHashes = await Promise.all(thisBlocks.map(block => block.hash()));
404
+ if (
405
+ blockHeaders.length !== thisBlocks.length ||
406
+ !blockHashes.every((block, i) => block.equals(thisBlockHashes[i]))
407
+ ) {
408
+ this.log.warn('Epoch blocks changed underfoot', {
409
+ uuid: this.uuid,
410
+ epochNumber: this.epochNumber,
411
+ oldBlockHashes: thisBlockHashes,
412
+ newBlockHashes: blockHashes,
413
+ });
414
+ void this.stop('reorg');
415
+ }
416
+ },
417
+ this.log,
418
+ intervalMs,
419
+ ).start();
420
+ this.log.verbose(`Scheduled epoch check for epoch ${this.epochNumber} every ${intervalMs}ms`);
421
+ }
422
+
423
+ /* Returns the last block header in the previous checkpoint for all checkpoints in the epoch */
424
+ private gatherPreviousBlockHeaders() {
425
+ const lastBlocks = this.checkpoints.map(checkpoint => checkpoint.blocks.at(-1)!);
426
+ return [this.data.previousBlockHeader, ...lastBlocks.map(block => block.header).slice(0, -1)];
216
427
  }
217
428
 
218
- private async getTxs(block: L2Block): Promise<Tx[]> {
219
- const txHashes = block.body.txEffects.map(tx => tx.txHash.toBigInt());
220
- const txsAndHashes = await Promise.all(this.txs.map(async tx => ({ tx, hash: await tx.getTxHash() })));
221
- return txsAndHashes
222
- .filter(txAndHash => txHashes.includes(txAndHash.hash.toBigInt()))
223
- .map(txAndHash => txAndHash.tx);
429
+ private getTxs(block: L2Block): Tx[] {
430
+ return block.body.txEffects.map(txEffect => this.txs.get(txEffect.txHash.toString())!);
224
431
  }
225
432
 
226
- private getL1ToL2Messages(block: L2Block) {
227
- return this.l1ToL2MessageSource.getL1ToL2Messages(BigInt(block.number));
433
+ private getL1ToL2Messages(checkpoint: Checkpoint) {
434
+ return this.data.l1ToL2Messages[checkpoint.number];
228
435
  }
229
436
 
230
437
  private async processTxs(publicProcessor: PublicProcessor, txs: Tx[]): Promise<ProcessedTx[]> {
@@ -232,8 +439,11 @@ export class EpochProvingJob implements Traceable {
232
439
  const [processedTxs, failedTxs] = await publicProcessor.process(txs, { deadline });
233
440
 
234
441
  if (failedTxs.length) {
442
+ const failedTxHashes = await Promise.all(failedTxs.map(({ tx }) => tx.getTxHash()));
235
443
  throw new Error(
236
- `Txs failed processing: ${failedTxs.map(({ tx, error }) => `${tx.getTxHash()} (${error})`).join(', ')}`,
444
+ `Txs failed processing: ${failedTxs
445
+ .map(({ error }, index) => `${failedTxHashes[index]} (${error})`)
446
+ .join(', ')}`,
237
447
  );
238
448
  }
239
449
 
@@ -246,7 +456,7 @@ export class EpochProvingJob implements Traceable {
246
456
  }
247
457
 
248
458
  class HaltExecutionError extends Error {
249
- constructor(state: EpochProvingJobState) {
459
+ constructor(public readonly state: EpochProvingJobState) {
250
460
  super(`Halted execution due to state ${state}`);
251
461
  this.name = 'HaltExecutionError';
252
462
  }