@aztec/prover-node 0.0.0-test.1 → 0.0.1-commit.017a351

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 +13 -0
  8. package/dest/actions/rerun-epoch-proving-job.d.ts.map +1 -0
  9. package/dest/actions/rerun-epoch-proving-job.js +120 -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 +68 -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 +92 -43
  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 +31 -18
  29. package/dest/job/epoch-proving-job.d.ts.map +1 -1
  30. package/dest/job/epoch-proving-job.js +756 -99
  31. package/dest/metrics.d.ts +50 -5
  32. package/dest/metrics.d.ts.map +1 -1
  33. package/dest/metrics.js +157 -72
  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 +24 -17
  37. package/dest/monitors/index.d.ts +1 -1
  38. package/dest/prover-node-publisher.d.ts +38 -19
  39. package/dest/prover-node-publisher.d.ts.map +1 -1
  40. package/dest/prover-node-publisher.js +288 -87
  41. package/dest/prover-node.d.ts +64 -49
  42. package/dest/prover-node.d.ts.map +1 -1
  43. package/dest/prover-node.js +650 -148
  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 +74 -0
  54. package/src/actions/upload-epoch-proof-failure.ts +88 -0
  55. package/src/bin/run-failed-epoch.ts +79 -0
  56. package/src/config.ts +123 -45
  57. package/src/factory.ts +163 -67
  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 +364 -88
  61. package/src/metrics.ts +188 -70
  62. package/src/monitors/epoch-monitor.ts +23 -19
  63. package/src/prover-node-publisher.ts +368 -125
  64. package/src/prover-node.ts +292 -166
  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,28 +1,33 @@
1
- import { compact } from '@aztec/foundation/collection';
1
+ import type { Archiver } from '@aztec/archiver';
2
+ import type { RollupContract } from '@aztec/ethereum/contracts';
3
+ import type { Delayer } from '@aztec/ethereum/l1-tx-utils';
4
+ import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec/foundation/branded-types';
5
+ import { assertRequired, compact, pick, sum } from '@aztec/foundation/collection';
6
+ import type { Fr } from '@aztec/foundation/curves/bn254';
2
7
  import { memoize } from '@aztec/foundation/decorators';
3
8
  import { createLogger } from '@aztec/foundation/log';
4
- import { RunningPromise } from '@aztec/foundation/running-promise';
5
9
  import { DateProvider } from '@aztec/foundation/timer';
6
- import type { Maybe } from '@aztec/foundation/types';
7
- import type { P2P } from '@aztec/p2p';
8
10
  import { PublicProcessorFactory } from '@aztec/simulator/server';
9
- import type { L2Block, L2BlockSource } from '@aztec/stdlib/block';
11
+ import type { L2BlockSource } from '@aztec/stdlib/block';
12
+ import type { Checkpoint } from '@aztec/stdlib/checkpoint';
13
+ import type { ChainConfig } from '@aztec/stdlib/config';
10
14
  import type { ContractDataSource } from '@aztec/stdlib/contract';
11
- import { getTimestampRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
15
+ import { getProofSubmissionDeadlineTimestamp } from '@aztec/stdlib/epoch-helpers';
12
16
  import {
13
17
  type EpochProverManager,
14
- EpochProvingJobTerminalState,
15
- type ProverCoordination,
18
+ type ITxProvider,
16
19
  type ProverNodeApi,
17
20
  type Service,
21
+ type WorldStateSyncStatus,
18
22
  type WorldStateSynchronizer,
19
23
  tryStop,
20
24
  } from '@aztec/stdlib/interfaces/server';
25
+ import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
21
26
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
22
- import type { P2PClientType } from '@aztec/stdlib/p2p';
23
- import type { Tx, TxHash } from '@aztec/stdlib/tx';
27
+ import type { Tx } from '@aztec/stdlib/tx';
24
28
  import {
25
29
  Attributes,
30
+ L1Metrics,
26
31
  type TelemetryClient,
27
32
  type Traceable,
28
33
  type Tracer,
@@ -30,66 +35,73 @@ import {
30
35
  trackSpan,
31
36
  } from '@aztec/telemetry-client';
32
37
 
33
- import { EpochProvingJob, type EpochProvingJobState } from './job/epoch-proving-job.js';
34
- import { ProverNodeMetrics } from './metrics.js';
38
+ import { uploadEpochProofFailure } from './actions/upload-epoch-proof-failure.js';
39
+ import type { SpecificProverNodeConfig } from './config.js';
40
+ import type { EpochProvingJobData } from './job/epoch-proving-job-data.js';
41
+ import { EpochProvingJob, type EpochProvingJobOptions, type EpochProvingJobState } from './job/epoch-proving-job.js';
42
+ import { ProverNodeJobMetrics, ProverNodeRewardsMetrics } from './metrics.js';
35
43
  import type { EpochMonitor, EpochMonitorHandler } from './monitors/epoch-monitor.js';
36
44
  import type { ProverNodePublisher } from './prover-node-publisher.js';
45
+ import type { ProverPublisherFactory } from './prover-publisher-factory.js';
37
46
 
38
- export type ProverNodeOptions = {
39
- pollingIntervalMs: number;
40
- maxPendingJobs: number;
41
- maxParallelBlocksPerEpoch: number;
42
- txGatheringTimeoutMs: number;
43
- txGatheringIntervalMs: number;
44
- txGatheringMaxParallelRequests: number;
45
- };
47
+ type ProverNodeOptions = SpecificProverNodeConfig & Partial<DataStoreOptions>;
48
+ type DataStoreOptions = Pick<DataStoreConfig, 'dataDirectory'> & Pick<ChainConfig, 'l1ChainId' | 'rollupVersion'>;
46
49
 
47
50
  /**
48
- * An Aztec Prover Node is a standalone process that monitors the unfinalised chain on L1 for unproven blocks,
49
- * submits bids for proving them, and monitors if they are accepted. If so, the prover node fetches the txs
50
- * from a tx source in the p2p network or an external node, re-executes their public functions, creates a rollup
51
+ * An Aztec Prover Node is a standalone process that monitors the unfinalized chain on L1 for unproven epochs,
52
+ * fetches their txs from the p2p network or external nodes, re-executes their public functions, creates a rollup
51
53
  * proof for the epoch, and submits it to L1.
52
54
  */
53
55
  export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable {
54
56
  private log = createLogger('prover-node');
55
- private dateProvider = new DateProvider();
56
57
 
57
- private latestEpochWeAreProving: bigint | undefined;
58
58
  private jobs: Map<string, EpochProvingJob> = new Map();
59
- private cachedEpochData: { epochNumber: bigint; blocks: L2Block[]; txs: Tx[] } | undefined = undefined;
60
- private options: ProverNodeOptions;
61
- private metrics: ProverNodeMetrics;
62
-
63
- private txFetcher: RunningPromise;
64
- private lastBlockNumber: number | undefined;
59
+ private config: ProverNodeOptions;
60
+ private jobMetrics: ProverNodeJobMetrics;
61
+ private rewardsMetrics: ProverNodeRewardsMetrics;
62
+ private startingProofEpochs: Set<EpochNumber> = new Set();
65
63
 
66
64
  public readonly tracer: Tracer;
67
65
 
66
+ protected publisher: ProverNodePublisher | undefined;
67
+
68
68
  constructor(
69
69
  protected readonly prover: EpochProverManager,
70
- protected readonly publisher: ProverNodePublisher,
71
- protected readonly l2BlockSource: L2BlockSource & Maybe<Service>,
70
+ protected readonly publisherFactory: ProverPublisherFactory,
71
+ protected readonly l2BlockSource: L2BlockSource & Partial<Service>,
72
72
  protected readonly l1ToL2MessageSource: L1ToL2MessageSource,
73
73
  protected readonly contractDataSource: ContractDataSource,
74
74
  protected readonly worldState: WorldStateSynchronizer,
75
- protected readonly coordination: ProverCoordination & Maybe<Service>,
75
+ protected readonly p2pClient: { getTxProvider(): ITxProvider } & Partial<Service>,
76
76
  protected readonly epochsMonitor: EpochMonitor,
77
- options: Partial<ProverNodeOptions> = {},
77
+ protected readonly rollupContract: RollupContract,
78
+ protected readonly l1Metrics: L1Metrics,
79
+ config: Partial<ProverNodeOptions> = {},
78
80
  protected readonly telemetryClient: TelemetryClient = getTelemetryClient(),
81
+ private delayer?: Delayer,
82
+ private readonly dateProvider: DateProvider = new DateProvider(),
79
83
  ) {
80
- this.options = {
81
- pollingIntervalMs: 1_000,
82
- maxPendingJobs: 100,
83
- maxParallelBlocksPerEpoch: 32,
84
- txGatheringTimeoutMs: 60_000,
84
+ this.config = {
85
+ proverNodePollingIntervalMs: 1_000,
86
+ proverNodeMaxPendingJobs: 100,
87
+ proverNodeMaxParallelBlocksPerEpoch: 0,
85
88
  txGatheringIntervalMs: 1_000,
86
- txGatheringMaxParallelRequests: 100,
87
- ...compact(options),
89
+ txGatheringBatchSize: 10,
90
+ txGatheringMaxParallelRequestsPerNode: 100,
91
+ txGatheringTimeoutMs: 120_000,
92
+ proverNodeFailedEpochStore: undefined,
93
+ proverNodeEpochProvingDelayMs: undefined,
94
+ ...compact(config),
88
95
  };
89
96
 
90
- this.metrics = new ProverNodeMetrics(telemetryClient, 'ProverNode');
97
+ this.validateConfig();
98
+
99
+ const meter = telemetryClient.getMeter('ProverNode');
91
100
  this.tracer = telemetryClient.getTracer('ProverNode');
92
- this.txFetcher = new RunningPromise(() => this.checkForTxs(), this.log, this.options.txGatheringIntervalMs);
101
+
102
+ this.jobMetrics = new ProverNodeJobMetrics(meter, telemetryClient.getTracer('EpochProvingJob'));
103
+
104
+ this.rewardsMetrics = new ProverNodeRewardsMetrics(meter, this.prover.getProverId(), rollupContract);
93
105
  }
94
106
 
95
107
  public getProverId() {
@@ -97,77 +109,152 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
97
109
  }
98
110
 
99
111
  public getP2P() {
100
- const asP2PClient = this.coordination as P2P<P2PClientType.Prover>;
101
- if (typeof asP2PClient.isP2PClient === 'function' && asP2PClient.isP2PClient()) {
102
- return asP2PClient;
103
- }
104
- return undefined;
112
+ return this.p2pClient;
113
+ }
114
+
115
+ /** Returns the shared tx delayer for prover L1 txs, if enabled. Test-only. */
116
+ public getDelayer(): Delayer | undefined {
117
+ return this.delayer;
105
118
  }
106
119
 
107
120
  /**
108
121
  * Handles an epoch being completed by starting a proof for it if there are no active jobs for it.
109
122
  * @param epochNumber - The epoch number that was just completed.
123
+ * @returns false if there is an error, true otherwise
110
124
  */
111
- async handleEpochReadyToProve(epochNumber: bigint): Promise<void> {
125
+ async handleEpochReadyToProve(epochNumber: EpochNumber): Promise<boolean> {
112
126
  try {
113
- this.log.debug('jobs', JSON.stringify(this.jobs, null, 2));
114
- const activeJobs = await this.getActiveJobsForEpoch(epochNumber);
115
- if (activeJobs.length > 0) {
116
- this.log.info(`Not starting proof for ${epochNumber} since there are active jobs`);
117
- return;
118
- }
119
- // TODO: we probably want to skip starting a proof if we are too far into the current epoch
120
- await this.startProof(epochNumber);
127
+ this.log.debug(`Running jobs as ${epochNumber} is ready to prove`, {
128
+ jobs: Array.from(this.jobs.values()).map(job => `${job.getEpochNumber()}:${job.getId()}`),
129
+ });
130
+ return await this.startProofIfNeeded(epochNumber);
121
131
  } catch (err) {
122
132
  if (err instanceof EmptyEpochError) {
123
133
  this.log.info(`Not starting proof for ${epochNumber} since no blocks were found`);
124
134
  } else {
125
135
  this.log.error(`Error handling epoch completed`, err);
126
136
  }
137
+ return false;
127
138
  }
128
139
  }
129
140
 
130
141
  /**
131
- * Starts the prover node so it periodically checks for unproven epochs in the unfinalised chain from L1 and
142
+ * Starts the prover node so it periodically checks for unproven epochs in the unfinalized chain from L1 and
132
143
  * starts proving jobs for them.
133
144
  */
134
- start() {
135
- this.txFetcher.start();
145
+ async start() {
136
146
  this.epochsMonitor.start(this);
137
- this.log.info('Started ProverNode', this.options);
147
+ await this.publisherFactory.start();
148
+ this.publisher = await this.publisherFactory.create();
149
+ await this.rewardsMetrics.start();
150
+ this.l1Metrics.start();
151
+ this.log.info(`Started Prover Node with prover id ${this.prover.getProverId().toString()}`, this.config);
138
152
  }
139
153
 
140
154
  /**
141
155
  * Stops the prover node and all its dependencies.
156
+ * Resources not owned by this node (shared with the parent aztec-node) are skipped.
142
157
  */
143
158
  async stop() {
144
159
  this.log.info('Stopping ProverNode');
145
- await this.txFetcher.stop();
146
160
  await this.epochsMonitor.stop();
147
- await this.prover.stop();
148
- await tryStop(this.l2BlockSource);
149
- this.publisher.interrupt();
161
+ this.publisher?.interrupt();
150
162
  await Promise.all(Array.from(this.jobs.values()).map(job => job.stop()));
151
- await this.worldState.stop();
152
- await tryStop(this.coordination);
163
+ await this.prover.stop();
164
+ await tryStop(this.publisherFactory);
165
+ this.rewardsMetrics.stop();
166
+ this.l1Metrics.stop();
153
167
  await this.telemetryClient.stop();
154
168
  this.log.info('Stopped ProverNode');
155
169
  }
156
170
 
157
- /**
158
- * Creates a proof for a block range. Returns once the proof has been submitted to L1.
159
- */
160
- public async prove(epochNumber: number | bigint) {
161
- const job = await this.createProvingJob(BigInt(epochNumber));
162
- return job.run();
171
+ /** Returns world state status. */
172
+ public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
173
+ const { syncSummary } = await this.worldState.status();
174
+ return syncSummary;
175
+ }
176
+
177
+ /** Returns archiver status. */
178
+ public getL2Tips() {
179
+ return this.l2BlockSource.getL2Tips();
163
180
  }
164
181
 
165
182
  /**
166
183
  * Starts a proving process and returns immediately.
167
184
  */
168
- public async startProof(epochNumber: number | bigint) {
169
- const job = await this.createProvingJob(BigInt(epochNumber));
170
- void job.run().catch(err => this.log.error(`Error proving epoch ${epochNumber}`, err));
185
+ public async startProof(epochNumber: EpochNumber) {
186
+ await this.startProofIfNeeded(epochNumber, { skipEpochCheck: true });
187
+ }
188
+
189
+ private async startProofIfNeeded(epochNumber: EpochNumber, opts: EpochProvingJobOptions = {}): Promise<boolean> {
190
+ if (this.startingProofEpochs.has(epochNumber)) {
191
+ this.log.warn(`Not starting proof for ${epochNumber} since a proof is already being started for the epoch`, {
192
+ epochNumber,
193
+ });
194
+ return false;
195
+ }
196
+
197
+ this.startingProofEpochs.add(epochNumber);
198
+
199
+ try {
200
+ const activeJobs = await this.activeJobsCoverEpoch(epochNumber);
201
+ if (activeJobs.length > 0) {
202
+ this.log.warn(`Not starting proof for ${epochNumber} since an active job already covers the epoch`, {
203
+ epochNumber,
204
+ activeJobs,
205
+ });
206
+ return true;
207
+ }
208
+
209
+ await this.startProofInternal(epochNumber, opts);
210
+ return true;
211
+ } finally {
212
+ this.startingProofEpochs.delete(epochNumber);
213
+ }
214
+ }
215
+
216
+ private async startProofInternal(epochNumber: EpochNumber, opts: EpochProvingJobOptions = {}) {
217
+ const job = await this.createProvingJob(epochNumber, opts);
218
+ void this.runJob(job);
219
+ }
220
+
221
+ private async runJob(job: EpochProvingJob) {
222
+ const epochNumber = job.getEpochNumber();
223
+ const ctx = { id: job.getId(), epochNumber, state: undefined as EpochProvingJobState | undefined };
224
+
225
+ try {
226
+ await job.run();
227
+ const state = job.getState();
228
+ ctx.state = state;
229
+
230
+ if (state === 'reorg') {
231
+ this.log.warn(`Running new job for epoch ${epochNumber} due to reorg`, ctx);
232
+ await this.createProvingJob(epochNumber);
233
+ } else if (state === 'failed') {
234
+ this.log.error(`Job for ${epochNumber} exited with state ${state}`, ctx);
235
+ await this.tryUploadEpochFailure(job);
236
+ } else {
237
+ this.log.verbose(`Job for ${epochNumber} exited with state ${state}`, ctx);
238
+ }
239
+ } catch (err) {
240
+ this.log.error(`Error proving epoch ${epochNumber}`, err, ctx);
241
+ } finally {
242
+ this.jobs.delete(job.getId());
243
+ }
244
+ }
245
+
246
+ protected async tryUploadEpochFailure(job: EpochProvingJob) {
247
+ if (this.config.proverNodeFailedEpochStore) {
248
+ return await uploadEpochProofFailure(
249
+ this.config.proverNodeFailedEpochStore,
250
+ job.getId(),
251
+ job.getProvingData(),
252
+ this.l2BlockSource as Archiver,
253
+ this.worldState,
254
+ assertRequired(pick(this.config, 'l1ChainId', 'rollupVersion', 'dataDirectory')),
255
+ this.log,
256
+ );
257
+ }
171
258
  }
172
259
 
173
260
  /**
@@ -180,62 +267,85 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
180
267
  /**
181
268
  * Returns an array of jobs being processed.
182
269
  */
183
- public getJobs(): Promise<{ uuid: string; status: EpochProvingJobState; epochNumber: number }[]> {
184
- return Promise.resolve(
185
- Array.from(this.jobs.entries()).map(([uuid, job]) => ({
186
- uuid,
187
- status: job.getState(),
188
- epochNumber: Number(job.getEpochNumber()),
189
- })),
190
- );
270
+ public getJobs(): Promise<{ uuid: string; status: EpochProvingJobState; epochNumber: EpochNumber }[]> {
271
+ return Promise.resolve(this.getJobsInternal());
191
272
  }
192
273
 
193
- protected async getActiveJobsForEpoch(
194
- epochBigInt: bigint,
195
- ): Promise<{ uuid: string; status: EpochProvingJobState }[]> {
196
- const jobs = await this.getJobs();
197
- const epochNumber = Number(epochBigInt);
198
- return jobs.filter(job => job.epochNumber === epochNumber && !EpochProvingJobTerminalState.includes(job.status));
274
+ private getJobsInternal(): { uuid: string; status: EpochProvingJobState; epochNumber: EpochNumber }[] {
275
+ return Array.from(this.jobs.entries()).map(([uuid, job]) => ({
276
+ uuid,
277
+ status: job.getState(),
278
+ epochNumber: job.getEpochNumber(),
279
+ }));
199
280
  }
200
281
 
201
- private checkMaximumPendingJobs() {
202
- const { maxPendingJobs } = this.options;
203
- return maxPendingJobs === 0 || this.jobs.size < maxPendingJobs;
204
- }
282
+ private async activeJobsCoverEpoch(epochNumber: EpochNumber): Promise<string[]> {
283
+ const checkpoints = await this.l2BlockSource.getCheckpointsData({ epoch: epochNumber });
284
+ if (checkpoints.length === 0) {
285
+ return [];
286
+ }
287
+
288
+ const firstCheckpoint = checkpoints.at(0)!.checkpointNumber;
289
+ const latestCheckpoint = checkpoints.at(-1)!.checkpointNumber;
290
+
291
+ const jobs: string[] = [];
292
+ for (const job of this.jobs.values()) {
293
+ if (job.getEpochNumber() !== epochNumber) {
294
+ continue;
295
+ }
296
+
297
+ const jobCheckpoints = job.getProvingData().checkpoints;
298
+ const checkpointOverlap =
299
+ jobCheckpoints.at(0)!.number <= firstCheckpoint && jobCheckpoints.at(-1)!.number >= latestCheckpoint;
205
300
 
206
- @trackSpan('ProverNode.createProvingJob', epochNumber => ({ [Attributes.EPOCH_NUMBER]: Number(epochNumber) }))
207
- private async createProvingJob(epochNumber: bigint) {
208
- if (!this.checkMaximumPendingJobs()) {
209
- throw new Error(`Maximum pending proving jobs ${this.options.maxPendingJobs} reached. Cannot create new job.`);
301
+ if (checkpointOverlap && !['failed', 'stopped', 'timed-out'].includes(job.getState())) {
302
+ jobs.push(job.getId());
303
+ }
210
304
  }
211
305
 
212
- // Gather blocks for this epoch
213
- const cachedEpochData = this.cachedEpochData?.epochNumber === epochNumber ? this.cachedEpochData : undefined;
214
- const { blocks, txs } = cachedEpochData ?? (await this.gatherEpochData(epochNumber));
306
+ return jobs;
307
+ }
215
308
 
216
- const fromBlock = blocks[0].number;
217
- const toBlock = blocks.at(-1)!.number;
309
+ private checkMaximumPendingJobs() {
310
+ const { proverNodeMaxPendingJobs: maxPendingJobs } = this.config;
311
+ if (maxPendingJobs > 0 && this.jobs.size >= maxPendingJobs) {
312
+ throw new Error(`Maximum pending proving jobs ${maxPendingJobs} reached. Cannot create new job.`);
313
+ }
314
+ }
315
+
316
+ @trackSpan('ProverNode.createProvingJob', epochNumber => ({ [Attributes.EPOCH_NUMBER]: epochNumber }))
317
+ private async createProvingJob(epochNumber: EpochNumber, opts: { skipEpochCheck?: boolean } = {}) {
318
+ this.checkMaximumPendingJobs();
319
+
320
+ this.publisher = await this.publisherFactory.create();
321
+
322
+ // Gather all data for this epoch
323
+ const epochData = await this.gatherEpochData(epochNumber);
324
+ const fromCheckpoint = epochData.checkpoints[0].number;
325
+ const toCheckpoint = epochData.checkpoints.at(-1)!.number;
326
+ const fromBlock = epochData.checkpoints[0].blocks[0].number;
327
+ const lastBlock = epochData.checkpoints.at(-1)!.blocks.at(-1)!;
328
+ const toBlock = lastBlock.number;
329
+ this.log.verbose(
330
+ `Creating proving job for epoch ${epochNumber} for checkpoint range ${fromCheckpoint} to ${toCheckpoint} and block range ${fromBlock} to ${toBlock}`,
331
+ );
218
332
 
219
333
  // Fast forward world state to right before the target block and get a fork
220
- this.log.verbose(`Creating proving job for epoch ${epochNumber} for block range ${fromBlock} to ${toBlock}`);
221
- await this.worldState.syncImmediate(toBlock);
334
+ const lastBlockHash = await lastBlock.header.hash();
335
+ await this.worldState.syncImmediate(toBlock, lastBlockHash);
222
336
 
223
- // Create a processor using the forked world state
337
+ // Create a processor factory
224
338
  const publicProcessorFactory = new PublicProcessorFactory(
225
339
  this.contractDataSource,
226
340
  this.dateProvider,
227
341
  this.telemetryClient,
342
+ this.log.getBindings(),
228
343
  );
229
344
 
230
- const cleanUp = () => {
231
- this.jobs.delete(job.getId());
232
- return Promise.resolve();
233
- };
234
-
235
- const [_, endTimestamp] = getTimestampRangeForEpoch(epochNumber + 1n, await this.getL1Constants());
236
- const deadline = new Date(Number(endTimestamp) * 1000);
237
-
238
- const job = this.doCreateEpochProvingJob(epochNumber, deadline, blocks, txs, publicProcessorFactory, cleanUp);
345
+ // Set deadline for this job to run. It will abort if it takes too long.
346
+ const deadlineTs = getProofSubmissionDeadlineTimestamp(epochNumber, await this.getL1Constants());
347
+ const deadline = new Date(Number(deadlineTs) * 1000);
348
+ const job = this.doCreateEpochProvingJob(epochData, deadline, publicProcessorFactory, this.publisher, opts);
239
349
  this.jobs.set(job.getId(), job);
240
350
  return job;
241
351
  }
@@ -245,79 +355,80 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
245
355
  return this.l2BlockSource.getL1Constants();
246
356
  }
247
357
 
248
- /** Monitors for new blocks and requests their txs from the p2p layer to ensure they are available for proving. */
249
- @trackSpan('ProverNode.checkForTxs')
250
- private async checkForTxs() {
251
- const blockNumber = await this.l2BlockSource.getBlockNumber();
252
- if (this.lastBlockNumber === undefined || blockNumber > this.lastBlockNumber) {
253
- const block = await this.l2BlockSource.getBlock(blockNumber);
254
- if (!block) {
255
- return;
256
- }
257
- const txHashes = block.body.txEffects.map(tx => tx.txHash);
258
- this.log.verbose(`Fetching ${txHashes.length} tx hashes for block number ${blockNumber} from coordination`);
259
- await this.coordination.getTxsByHash(txHashes); // This stores the txs in the tx pool, no need to persist them here
260
- this.lastBlockNumber = blockNumber;
358
+ @trackSpan('ProverNode.gatherEpochData', epochNumber => ({ [Attributes.EPOCH_NUMBER]: epochNumber }))
359
+ private async gatherEpochData(epochNumber: EpochNumber): Promise<EpochProvingJobData> {
360
+ const publishedCheckpoints = await this.l2BlockSource.getCheckpoints({ epoch: epochNumber });
361
+ if (publishedCheckpoints.length === 0) {
362
+ throw new EmptyEpochError(epochNumber);
261
363
  }
364
+ const checkpoints = publishedCheckpoints.map(p => p.checkpoint);
365
+ const attestations = publishedCheckpoints.at(-1)?.attestations ?? [];
366
+ const txArray = await this.gatherTxs(epochNumber, checkpoints);
367
+ const txs = new Map<string, Tx>(txArray.map(tx => [tx.getTxHash().toString(), tx]));
368
+ const l1ToL2Messages = await this.gatherMessages(epochNumber, checkpoints);
369
+ const [firstBlock] = checkpoints[0].blocks;
370
+ const previousBlockHeader = await this.gatherPreviousBlockHeader(epochNumber, firstBlock.number - 1);
371
+
372
+ return { checkpoints, txs, l1ToL2Messages, epochNumber, previousBlockHeader, attestations };
262
373
  }
263
374
 
264
- @trackSpan('ProverNode.gatherEpochData', epochNumber => ({ [Attributes.EPOCH_NUMBER]: Number(epochNumber) }))
265
- private async gatherEpochData(epochNumber: bigint) {
266
- // Gather blocks for this epoch and their txs
267
- const blocks = await this.gatherBlocks(epochNumber);
268
- const txs = await this.gatherTxs(epochNumber, blocks);
375
+ private async gatherTxs(epochNumber: EpochNumber, checkpoints: Checkpoint[]) {
376
+ const deadline = new Date(this.dateProvider.now() + this.config.txGatheringTimeoutMs);
377
+ const txProvider = this.p2pClient.getTxProvider();
378
+ const blocks = checkpoints.flatMap(checkpoint => checkpoint.blocks);
379
+ const txsByBlock = await Promise.all(blocks.map(block => txProvider.getTxsForBlock(block, { deadline })));
380
+ const txs = txsByBlock.map(({ txs }) => txs).flat();
381
+ const missingTxs = txsByBlock.map(({ missingTxs }) => missingTxs).flat();
382
+
383
+ if (missingTxs.length === 0) {
384
+ this.log.verbose(`Gathered all ${txs.length} txs for epoch ${epochNumber}`, { epochNumber });
385
+ return txs;
386
+ }
269
387
 
270
- return { blocks, txs };
388
+ throw new Error(`Txs not found for epoch ${epochNumber}: ${missingTxs.map(hash => hash.toString()).join(', ')}`);
271
389
  }
272
390
 
273
- private async gatherBlocks(epochNumber: bigint) {
274
- const blocks = await this.l2BlockSource.getBlocksForEpoch(epochNumber);
275
- if (blocks.length === 0) {
276
- throw new EmptyEpochError(epochNumber);
391
+ private async gatherMessages(epochNumber: EpochNumber, checkpoints: Checkpoint[]) {
392
+ const messages = await Promise.all(checkpoints.map(c => this.l1ToL2MessageSource.getL1ToL2Messages(c.number)));
393
+ const messageCount = sum(messages.map(m => m.length));
394
+ this.log.verbose(`Gathered all ${messageCount} messages for epoch ${epochNumber}`, { epochNumber });
395
+ const messagesByCheckpoint: Record<CheckpointNumber, Fr[]> = {};
396
+ for (let i = 0; i < checkpoints.length; i++) {
397
+ messagesByCheckpoint[checkpoints[i].number] = messages[i];
277
398
  }
278
- return blocks;
399
+ return messagesByCheckpoint;
279
400
  }
280
401
 
281
- private async gatherTxs(epochNumber: bigint, blocks: L2Block[]) {
282
- const txsToFind: TxHash[] = blocks.flatMap(block => block.body.txEffects.map(tx => tx.txHash));
283
- const txs = await this.coordination.getTxsByHash(txsToFind);
284
-
285
- if (txs.length === txsToFind.length) {
286
- this.log.verbose(`Gathered all ${txs.length} txs for epoch ${epochNumber}`, { epochNumber });
287
- return txs;
402
+ private async gatherPreviousBlockHeader(epochNumber: EpochNumber, previousBlockNumber: number) {
403
+ const data = await this.l2BlockSource.getBlockData({ number: BlockNumber(previousBlockNumber) });
404
+ if (!data?.header) {
405
+ throw new Error(`Previous block header ${previousBlockNumber} not found for proving epoch ${epochNumber}`);
288
406
  }
289
407
 
290
- const txHashesFound = await Promise.all(txs.map(tx => tx.getTxHash()));
291
- const missingTxHashes = txsToFind
292
- .filter(txHashToFind => !txHashesFound.some(txHashFound => txHashToFind.equals(txHashFound)))
293
- .join(', ');
294
-
295
- throw new Error(`Txs not found for epoch ${epochNumber}: ${missingTxHashes}`);
408
+ this.log.verbose(`Gathered previous block header ${data.header.getBlockNumber()} for epoch ${epochNumber}`);
409
+ return data.header;
296
410
  }
297
411
 
298
412
  /** Extracted for testing purposes. */
299
413
  protected doCreateEpochProvingJob(
300
- epochNumber: bigint,
414
+ data: EpochProvingJobData,
301
415
  deadline: Date | undefined,
302
- blocks: L2Block[],
303
- txs: Tx[],
304
416
  publicProcessorFactory: PublicProcessorFactory,
305
- cleanUp: () => Promise<void>,
417
+ publisher: ProverNodePublisher,
418
+ opts: { skipEpochCheck?: boolean } = {},
306
419
  ) {
420
+ const { proverNodeMaxParallelBlocksPerEpoch: parallelBlockLimit, proverNodeDisableProofPublish } = this.config;
307
421
  return new EpochProvingJob(
422
+ data,
308
423
  this.worldState,
309
- epochNumber,
310
- blocks,
311
- txs,
312
424
  this.prover.createEpochProver(),
313
425
  publicProcessorFactory,
314
- this.publisher,
426
+ publisher,
315
427
  this.l2BlockSource,
316
- this.l1ToL2MessageSource,
317
- this.metrics,
428
+ this.jobMetrics,
318
429
  deadline,
319
- { parallelBlockLimit: this.options.maxParallelBlocksPerEpoch },
320
- cleanUp,
430
+ { parallelBlockLimit, skipSubmitProof: proverNodeDisableProofPublish, ...opts },
431
+ this.log.getBindings(),
321
432
  );
322
433
  }
323
434
 
@@ -325,10 +436,25 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
325
436
  protected async triggerMonitors() {
326
437
  await this.epochsMonitor.work();
327
438
  }
439
+
440
+ private validateConfig() {
441
+ if (
442
+ this.config.proverNodeFailedEpochStore &&
443
+ (!this.config.dataDirectory || !this.config.l1ChainId || this.config.rollupVersion === undefined)
444
+ ) {
445
+ this.log.warn(
446
+ `Invalid prover-node config (missing dataDirectory, l1ChainId, or rollupVersion)`,
447
+ pick(this.config, 'proverNodeFailedEpochStore', 'dataDirectory', 'l1ChainId', 'rollupVersion'),
448
+ );
449
+ throw new Error(
450
+ 'All of dataDirectory, l1ChainId, and rollupVersion are required if proverNodeFailedEpochStore is set.',
451
+ );
452
+ }
453
+ }
328
454
  }
329
455
 
330
456
  class EmptyEpochError extends Error {
331
- constructor(epochNumber: bigint) {
457
+ constructor(epochNumber: EpochNumber) {
332
458
  super(`No blocks found for epoch ${epochNumber}`);
333
459
  this.name = 'EmptyEpochError';
334
460
  }
@@ -0,0 +1,45 @@
1
+ import type { RollupContract } from '@aztec/ethereum/contracts';
2
+ import type { L1TxUtils } from '@aztec/ethereum/l1-tx-utils';
3
+ import type { PublisherManager } from '@aztec/ethereum/publisher-manager';
4
+ import type { LoggerBindings } from '@aztec/foundation/log';
5
+ import type { ProverPublisherConfig, ProverTxSenderConfig } from '@aztec/sequencer-client';
6
+ import type { TelemetryClient } from '@aztec/telemetry-client';
7
+
8
+ import { ProverNodePublisher } from './prover-node-publisher.js';
9
+
10
+ export class ProverPublisherFactory {
11
+ constructor(
12
+ private config: ProverTxSenderConfig & ProverPublisherConfig,
13
+ private deps: {
14
+ rollupContract: RollupContract;
15
+ publisherManager: PublisherManager<L1TxUtils>;
16
+ telemetry?: TelemetryClient;
17
+ },
18
+ private bindings?: LoggerBindings,
19
+ ) {}
20
+
21
+ public async start() {
22
+ await this.deps.publisherManager.start();
23
+ }
24
+
25
+ public async stop() {
26
+ await this.deps.publisherManager.stop();
27
+ }
28
+
29
+ /**
30
+ * Creates a new Prover Publisher instance.
31
+ * @returns A new ProverNodePublisher instance.
32
+ */
33
+ public async create(): Promise<ProverNodePublisher> {
34
+ const l1Publisher = await this.deps.publisherManager.getAvailablePublisher();
35
+ return new ProverNodePublisher(
36
+ this.config,
37
+ {
38
+ rollupContract: this.deps.rollupContract,
39
+ l1TxUtils: l1Publisher,
40
+ telemetry: this.deps.telemetry,
41
+ },
42
+ this.bindings,
43
+ );
44
+ }
45
+ }