@aztec/prover-node 0.0.0-test.0 → 0.0.1-commit.0208eb9

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 +42 -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 +67 -0
  16. package/dest/config.d.ts +15 -11
  17. package/dest/config.d.ts.map +1 -1
  18. package/dest/config.js +83 -15
  19. package/dest/factory.d.ts +14 -12
  20. package/dest/factory.d.ts.map +1 -1
  21. package/dest/factory.js +106 -37
  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 +583 -97
  31. package/dest/metrics.d.ts +30 -5
  32. package/dest/metrics.d.ts.map +1 -1
  33. package/dest/metrics.js +111 -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 -13
  37. package/dest/monitors/index.d.ts +1 -1
  38. package/dest/prover-node-publisher.d.ts +17 -17
  39. package/dest/prover-node-publisher.d.ts.map +1 -1
  40. package/dest/prover-node-publisher.js +89 -83
  41. package/dest/prover-node.d.ts +49 -44
  42. package/dest/prover-node.d.ts.map +1 -1
  43. package/dest/prover-node.js +582 -130
  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 +39 -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 +77 -0
  56. package/src/config.ts +111 -25
  57. package/src/factory.ts +177 -46
  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 +264 -84
  61. package/src/metrics.ts +119 -72
  62. package/src/monitors/epoch-monitor.ts +20 -15
  63. package/src/prover-node-publisher.ts +137 -117
  64. package/src/prover-node.ts +225 -142
  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,34 @@
1
- import { compact } from '@aztec/foundation/collection';
1
+ import type { Archiver } from '@aztec/archiver';
2
+ import type { RollupContract } from '@aztec/ethereum/contracts';
3
+ import { BlockNumber, CheckpointNumber, EpochNumber } from '@aztec/foundation/branded-types';
4
+ import { assertRequired, compact, pick, sum } from '@aztec/foundation/collection';
5
+ import type { Fr } from '@aztec/foundation/curves/bn254';
2
6
  import { memoize } from '@aztec/foundation/decorators';
3
7
  import { createLogger } from '@aztec/foundation/log';
4
- import { RunningPromise } from '@aztec/foundation/running-promise';
5
8
  import { DateProvider } from '@aztec/foundation/timer';
6
- import type { Maybe } from '@aztec/foundation/types';
7
- import type { P2P } from '@aztec/p2p';
9
+ import type { DataStoreConfig } from '@aztec/kv-store/config';
10
+ import type { P2PClient } from '@aztec/p2p';
8
11
  import { PublicProcessorFactory } from '@aztec/simulator/server';
9
- import type { L2Block, L2BlockSource } from '@aztec/stdlib/block';
12
+ import type { L2BlockSource } from '@aztec/stdlib/block';
13
+ import type { Checkpoint } from '@aztec/stdlib/checkpoint';
14
+ import type { ChainConfig } from '@aztec/stdlib/config';
10
15
  import type { ContractDataSource } from '@aztec/stdlib/contract';
11
- import { getTimestampRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
16
+ import { getProofSubmissionDeadlineTimestamp } from '@aztec/stdlib/epoch-helpers';
12
17
  import {
13
18
  type EpochProverManager,
14
19
  EpochProvingJobTerminalState,
15
- type ProverCoordination,
16
20
  type ProverNodeApi,
17
21
  type Service,
22
+ type WorldStateSyncStatus,
18
23
  type WorldStateSynchronizer,
19
24
  tryStop,
20
25
  } from '@aztec/stdlib/interfaces/server';
21
26
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
22
27
  import type { P2PClientType } from '@aztec/stdlib/p2p';
23
- import type { Tx, TxHash } from '@aztec/stdlib/tx';
28
+ import type { Tx } from '@aztec/stdlib/tx';
24
29
  import {
25
30
  Attributes,
31
+ L1Metrics,
26
32
  type TelemetryClient,
27
33
  type Traceable,
28
34
  type Tracer,
@@ -30,66 +36,71 @@ import {
30
36
  trackSpan,
31
37
  } from '@aztec/telemetry-client';
32
38
 
39
+ import { uploadEpochProofFailure } from './actions/upload-epoch-proof-failure.js';
40
+ import type { SpecificProverNodeConfig } from './config.js';
41
+ import type { EpochProvingJobData } from './job/epoch-proving-job-data.js';
33
42
  import { EpochProvingJob, type EpochProvingJobState } from './job/epoch-proving-job.js';
34
- import { ProverNodeMetrics } from './metrics.js';
43
+ import { ProverNodeJobMetrics, ProverNodeRewardsMetrics } from './metrics.js';
35
44
  import type { EpochMonitor, EpochMonitorHandler } from './monitors/epoch-monitor.js';
36
45
  import type { ProverNodePublisher } from './prover-node-publisher.js';
46
+ import type { ProverPublisherFactory } from './prover-publisher-factory.js';
37
47
 
38
- export type ProverNodeOptions = {
39
- pollingIntervalMs: number;
40
- maxPendingJobs: number;
41
- maxParallelBlocksPerEpoch: number;
42
- txGatheringTimeoutMs: number;
43
- txGatheringIntervalMs: number;
44
- txGatheringMaxParallelRequests: number;
45
- };
48
+ type ProverNodeOptions = SpecificProverNodeConfig & Partial<DataStoreOptions>;
49
+ type DataStoreOptions = Pick<DataStoreConfig, 'dataDirectory'> & Pick<ChainConfig, 'l1ChainId' | 'rollupVersion'>;
46
50
 
47
51
  /**
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
52
+ * An Aztec Prover Node is a standalone process that monitors the unfinalized chain on L1 for unproven epochs,
53
+ * fetches their txs from the p2p network or external nodes, re-executes their public functions, creates a rollup
51
54
  * proof for the epoch, and submits it to L1.
52
55
  */
53
56
  export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable {
54
57
  private log = createLogger('prover-node');
55
58
  private dateProvider = new DateProvider();
56
59
 
57
- private latestEpochWeAreProving: bigint | undefined;
58
60
  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;
61
+ private config: ProverNodeOptions;
62
+ private jobMetrics: ProverNodeJobMetrics;
63
+ private rewardsMetrics: ProverNodeRewardsMetrics;
65
64
 
66
65
  public readonly tracer: Tracer;
67
66
 
67
+ protected publisher: ProverNodePublisher | undefined;
68
+
68
69
  constructor(
69
70
  protected readonly prover: EpochProverManager,
70
- protected readonly publisher: ProverNodePublisher,
71
- protected readonly l2BlockSource: L2BlockSource & Maybe<Service>,
71
+ protected readonly publisherFactory: ProverPublisherFactory,
72
+ protected readonly l2BlockSource: L2BlockSource & Partial<Service>,
72
73
  protected readonly l1ToL2MessageSource: L1ToL2MessageSource,
73
74
  protected readonly contractDataSource: ContractDataSource,
74
75
  protected readonly worldState: WorldStateSynchronizer,
75
- protected readonly coordination: ProverCoordination & Maybe<Service>,
76
+ protected readonly p2pClient: Pick<P2PClient<P2PClientType.Prover>, 'getTxProvider'> & Partial<Service>,
76
77
  protected readonly epochsMonitor: EpochMonitor,
77
- options: Partial<ProverNodeOptions> = {},
78
+ protected readonly rollupContract: RollupContract,
79
+ protected readonly l1Metrics: L1Metrics,
80
+ config: Partial<ProverNodeOptions> = {},
78
81
  protected readonly telemetryClient: TelemetryClient = getTelemetryClient(),
79
82
  ) {
80
- this.options = {
81
- pollingIntervalMs: 1_000,
82
- maxPendingJobs: 100,
83
- maxParallelBlocksPerEpoch: 32,
84
- txGatheringTimeoutMs: 60_000,
83
+ this.config = {
84
+ proverNodePollingIntervalMs: 1_000,
85
+ proverNodeMaxPendingJobs: 100,
86
+ proverNodeMaxParallelBlocksPerEpoch: 32,
85
87
  txGatheringIntervalMs: 1_000,
86
- txGatheringMaxParallelRequests: 100,
87
- ...compact(options),
88
+ txGatheringBatchSize: 10,
89
+ txGatheringMaxParallelRequestsPerNode: 100,
90
+ txGatheringTimeoutMs: 120_000,
91
+ proverNodeFailedEpochStore: undefined,
92
+ proverNodeEpochProvingDelayMs: undefined,
93
+ ...compact(config),
88
94
  };
89
95
 
90
- this.metrics = new ProverNodeMetrics(telemetryClient, 'ProverNode');
96
+ this.validateConfig();
97
+
98
+ const meter = telemetryClient.getMeter('ProverNode');
91
99
  this.tracer = telemetryClient.getTracer('ProverNode');
92
- this.txFetcher = new RunningPromise(() => this.checkForTxs(), this.log, this.options.txGatheringIntervalMs);
100
+
101
+ this.jobMetrics = new ProverNodeJobMetrics(meter, telemetryClient.getTracer('EpochProvingJob'));
102
+
103
+ this.rewardsMetrics = new ProverNodeRewardsMetrics(meter, this.prover.getProverId(), rollupContract);
93
104
  }
94
105
 
95
106
  public getProverId() {
@@ -97,44 +108,49 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
97
108
  }
98
109
 
99
110
  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;
111
+ return this.p2pClient;
105
112
  }
106
113
 
107
114
  /**
108
115
  * Handles an epoch being completed by starting a proof for it if there are no active jobs for it.
109
116
  * @param epochNumber - The epoch number that was just completed.
117
+ * @returns false if there is an error, true otherwise
110
118
  */
111
- async handleEpochReadyToProve(epochNumber: bigint): Promise<void> {
119
+ async handleEpochReadyToProve(epochNumber: EpochNumber): Promise<boolean> {
112
120
  try {
113
- this.log.debug('jobs', JSON.stringify(this.jobs, null, 2));
121
+ this.log.debug(`Running jobs as ${epochNumber} is ready to prove`, {
122
+ jobs: Array.from(this.jobs.values()).map(job => `${job.getEpochNumber()}:${job.getId()}`),
123
+ });
114
124
  const activeJobs = await this.getActiveJobsForEpoch(epochNumber);
115
125
  if (activeJobs.length > 0) {
116
- this.log.info(`Not starting proof for ${epochNumber} since there are active jobs`);
117
- return;
126
+ this.log.warn(`Not starting proof for ${epochNumber} since there are active jobs for the epoch`, {
127
+ activeJobs: activeJobs.map(job => job.uuid),
128
+ });
129
+ return true;
118
130
  }
119
- // TODO: we probably want to skip starting a proof if we are too far into the current epoch
120
131
  await this.startProof(epochNumber);
132
+ return true;
121
133
  } catch (err) {
122
134
  if (err instanceof EmptyEpochError) {
123
135
  this.log.info(`Not starting proof for ${epochNumber} since no blocks were found`);
124
136
  } else {
125
137
  this.log.error(`Error handling epoch completed`, err);
126
138
  }
139
+ return false;
127
140
  }
128
141
  }
129
142
 
130
143
  /**
131
- * Starts the prover node so it periodically checks for unproven epochs in the unfinalised chain from L1 and
144
+ * Starts the prover node so it periodically checks for unproven epochs in the unfinalized chain from L1 and
132
145
  * starts proving jobs for them.
133
146
  */
134
- start() {
135
- this.txFetcher.start();
147
+ async start() {
136
148
  this.epochsMonitor.start(this);
137
- this.log.info('Started ProverNode', this.options);
149
+ await this.publisherFactory.start();
150
+ this.publisher = await this.publisherFactory.create();
151
+ await this.rewardsMetrics.start();
152
+ this.l1Metrics.start();
153
+ this.log.info(`Started Prover Node with prover id ${this.prover.getProverId().toString()}`, this.config);
138
154
  }
139
155
 
140
156
  /**
@@ -142,32 +158,76 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
142
158
  */
143
159
  async stop() {
144
160
  this.log.info('Stopping ProverNode');
145
- await this.txFetcher.stop();
146
161
  await this.epochsMonitor.stop();
147
162
  await this.prover.stop();
163
+ await tryStop(this.p2pClient);
148
164
  await tryStop(this.l2BlockSource);
149
- this.publisher.interrupt();
165
+ await tryStop(this.publisherFactory);
166
+ this.publisher?.interrupt();
150
167
  await Promise.all(Array.from(this.jobs.values()).map(job => job.stop()));
151
168
  await this.worldState.stop();
152
- await tryStop(this.coordination);
169
+ this.rewardsMetrics.stop();
170
+ this.l1Metrics.stop();
153
171
  await this.telemetryClient.stop();
154
172
  this.log.info('Stopped ProverNode');
155
173
  }
156
174
 
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();
175
+ /** Returns world state status. */
176
+ public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
177
+ const { syncSummary } = await this.worldState.status();
178
+ return syncSummary;
179
+ }
180
+
181
+ /** Returns archiver status. */
182
+ public getL2Tips() {
183
+ return this.l2BlockSource.getL2Tips();
163
184
  }
164
185
 
165
186
  /**
166
187
  * Starts a proving process and returns immediately.
167
188
  */
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));
189
+ public async startProof(epochNumber: EpochNumber) {
190
+ const job = await this.createProvingJob(epochNumber, { skipEpochCheck: true });
191
+ void this.runJob(job);
192
+ }
193
+
194
+ private async runJob(job: EpochProvingJob) {
195
+ const epochNumber = job.getEpochNumber();
196
+ const ctx = { id: job.getId(), epochNumber, state: undefined as EpochProvingJobState | undefined };
197
+
198
+ try {
199
+ await job.run();
200
+ const state = job.getState();
201
+ ctx.state = state;
202
+
203
+ if (state === 'reorg') {
204
+ this.log.warn(`Running new job for epoch ${epochNumber} due to reorg`, ctx);
205
+ await this.createProvingJob(epochNumber);
206
+ } else if (state === 'failed') {
207
+ this.log.error(`Job for ${epochNumber} exited with state ${state}`, ctx);
208
+ await this.tryUploadEpochFailure(job);
209
+ } else {
210
+ this.log.verbose(`Job for ${epochNumber} exited with state ${state}`, ctx);
211
+ }
212
+ } catch (err) {
213
+ this.log.error(`Error proving epoch ${epochNumber}`, err, ctx);
214
+ } finally {
215
+ this.jobs.delete(job.getId());
216
+ }
217
+ }
218
+
219
+ protected async tryUploadEpochFailure(job: EpochProvingJob) {
220
+ if (this.config.proverNodeFailedEpochStore) {
221
+ return await uploadEpochProofFailure(
222
+ this.config.proverNodeFailedEpochStore,
223
+ job.getId(),
224
+ job.getProvingData(),
225
+ this.l2BlockSource as Archiver,
226
+ this.worldState,
227
+ assertRequired(pick(this.config, 'l1ChainId', 'rollupVersion', 'dataDirectory')),
228
+ this.log,
229
+ );
230
+ }
171
231
  }
172
232
 
173
233
  /**
@@ -180,62 +240,61 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
180
240
  /**
181
241
  * Returns an array of jobs being processed.
182
242
  */
183
- public getJobs(): Promise<{ uuid: string; status: EpochProvingJobState; epochNumber: number }[]> {
243
+ public getJobs(): Promise<{ uuid: string; status: EpochProvingJobState; epochNumber: EpochNumber }[]> {
184
244
  return Promise.resolve(
185
245
  Array.from(this.jobs.entries()).map(([uuid, job]) => ({
186
246
  uuid,
187
247
  status: job.getState(),
188
- epochNumber: Number(job.getEpochNumber()),
248
+ epochNumber: job.getEpochNumber(),
189
249
  })),
190
250
  );
191
251
  }
192
252
 
193
253
  protected async getActiveJobsForEpoch(
194
- epochBigInt: bigint,
254
+ epochNumber: EpochNumber,
195
255
  ): Promise<{ uuid: string; status: EpochProvingJobState }[]> {
196
256
  const jobs = await this.getJobs();
197
- const epochNumber = Number(epochBigInt);
198
257
  return jobs.filter(job => job.epochNumber === epochNumber && !EpochProvingJobTerminalState.includes(job.status));
199
258
  }
200
259
 
201
260
  private checkMaximumPendingJobs() {
202
- const { maxPendingJobs } = this.options;
203
- return maxPendingJobs === 0 || this.jobs.size < maxPendingJobs;
261
+ const { proverNodeMaxPendingJobs: maxPendingJobs } = this.config;
262
+ if (maxPendingJobs > 0 && this.jobs.size >= maxPendingJobs) {
263
+ throw new Error(`Maximum pending proving jobs ${maxPendingJobs} reached. Cannot create new job.`);
264
+ }
204
265
  }
205
266
 
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.`);
210
- }
267
+ @trackSpan('ProverNode.createProvingJob', epochNumber => ({ [Attributes.EPOCH_NUMBER]: epochNumber }))
268
+ private async createProvingJob(epochNumber: EpochNumber, opts: { skipEpochCheck?: boolean } = {}) {
269
+ this.checkMaximumPendingJobs();
211
270
 
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));
271
+ this.publisher = await this.publisherFactory.create();
215
272
 
216
- const fromBlock = blocks[0].number;
217
- const toBlock = blocks.at(-1)!.number;
273
+ // Gather all data for this epoch
274
+ const epochData = await this.gatherEpochData(epochNumber);
275
+ const fromCheckpoint = epochData.checkpoints[0].number;
276
+ const toCheckpoint = epochData.checkpoints.at(-1)!.number;
277
+ const fromBlock = epochData.checkpoints[0].blocks[0].number;
278
+ const toBlock = epochData.checkpoints.at(-1)!.blocks.at(-1)!.number;
279
+ this.log.verbose(
280
+ `Creating proving job for epoch ${epochNumber} for checkpoint range ${fromCheckpoint} to ${toCheckpoint} and block range ${fromBlock} to ${toBlock}`,
281
+ );
218
282
 
219
283
  // 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
284
  await this.worldState.syncImmediate(toBlock);
222
285
 
223
- // Create a processor using the forked world state
286
+ // Create a processor factory
224
287
  const publicProcessorFactory = new PublicProcessorFactory(
225
288
  this.contractDataSource,
226
289
  this.dateProvider,
227
290
  this.telemetryClient,
291
+ this.log.getBindings(),
228
292
  );
229
293
 
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);
294
+ // Set deadline for this job to run. It will abort if it takes too long.
295
+ const deadlineTs = getProofSubmissionDeadlineTimestamp(epochNumber, await this.getL1Constants());
296
+ const deadline = new Date(Number(deadlineTs) * 1000);
297
+ const job = this.doCreateEpochProvingJob(epochData, deadline, publicProcessorFactory, this.publisher, opts);
239
298
  this.jobs.set(job.getId(), job);
240
299
  return job;
241
300
  }
@@ -245,79 +304,88 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
245
304
  return this.l2BlockSource.getL1Constants();
246
305
  }
247
306
 
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;
261
- }
262
- }
263
-
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);
269
-
270
- return { blocks, txs };
307
+ @trackSpan('ProverNode.gatherEpochData', epochNumber => ({ [Attributes.EPOCH_NUMBER]: epochNumber }))
308
+ private async gatherEpochData(epochNumber: EpochNumber): Promise<EpochProvingJobData> {
309
+ const checkpoints = await this.gatherCheckpoints(epochNumber);
310
+ const txArray = await this.gatherTxs(epochNumber, checkpoints);
311
+ const txs = new Map<string, Tx>(txArray.map(tx => [tx.getTxHash().toString(), tx]));
312
+ const l1ToL2Messages = await this.gatherMessages(epochNumber, checkpoints);
313
+ const [firstBlock] = checkpoints[0].blocks;
314
+ const previousBlockHeader = await this.gatherPreviousBlockHeader(epochNumber, firstBlock.number - 1);
315
+ const [lastPublishedCheckpoint] = await this.l2BlockSource.getCheckpoints(checkpoints.at(-1)!.number, 1);
316
+ const attestations = lastPublishedCheckpoint?.attestations ?? [];
317
+
318
+ return { checkpoints, txs, l1ToL2Messages, epochNumber, previousBlockHeader, attestations };
271
319
  }
272
320
 
273
- private async gatherBlocks(epochNumber: bigint) {
274
- const blocks = await this.l2BlockSource.getBlocksForEpoch(epochNumber);
275
- if (blocks.length === 0) {
321
+ private async gatherCheckpoints(epochNumber: EpochNumber) {
322
+ const checkpoints = await this.l2BlockSource.getCheckpointsForEpoch(epochNumber);
323
+ if (checkpoints.length === 0) {
276
324
  throw new EmptyEpochError(epochNumber);
277
325
  }
278
- return blocks;
326
+ return checkpoints;
279
327
  }
280
328
 
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);
329
+ private async gatherTxs(epochNumber: EpochNumber, checkpoints: Checkpoint[]) {
330
+ const deadline = new Date(this.dateProvider.now() + this.config.txGatheringTimeoutMs);
331
+ const txProvider = this.p2pClient.getTxProvider();
332
+ const blocks = checkpoints.flatMap(checkpoint => checkpoint.blocks);
333
+ const txsByBlock = await Promise.all(blocks.map(block => txProvider.getTxsForBlock(block, { deadline })));
334
+ const txs = txsByBlock.map(({ txs }) => txs).flat();
335
+ const missingTxs = txsByBlock.map(({ missingTxs }) => missingTxs).flat();
284
336
 
285
- if (txs.length === txsToFind.length) {
337
+ if (missingTxs.length === 0) {
286
338
  this.log.verbose(`Gathered all ${txs.length} txs for epoch ${epochNumber}`, { epochNumber });
287
339
  return txs;
288
340
  }
289
341
 
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(', ');
342
+ throw new Error(`Txs not found for epoch ${epochNumber}: ${missingTxs.map(hash => hash.toString()).join(', ')}`);
343
+ }
294
344
 
295
- throw new Error(`Txs not found for epoch ${epochNumber}: ${missingTxHashes}`);
345
+ private async gatherMessages(epochNumber: EpochNumber, checkpoints: Checkpoint[]) {
346
+ const messages = await Promise.all(checkpoints.map(c => this.l1ToL2MessageSource.getL1ToL2Messages(c.number)));
347
+ const messageCount = sum(messages.map(m => m.length));
348
+ this.log.verbose(`Gathered all ${messageCount} messages for epoch ${epochNumber}`, { epochNumber });
349
+ const messagesByCheckpoint: Record<CheckpointNumber, Fr[]> = {};
350
+ for (let i = 0; i < checkpoints.length; i++) {
351
+ messagesByCheckpoint[checkpoints[i].number] = messages[i];
352
+ }
353
+ return messagesByCheckpoint;
354
+ }
355
+
356
+ private async gatherPreviousBlockHeader(epochNumber: EpochNumber, previousBlockNumber: number) {
357
+ const header = await (previousBlockNumber === 0
358
+ ? this.worldState.getCommitted().getInitialHeader()
359
+ : this.l2BlockSource.getBlockHeader(BlockNumber(previousBlockNumber)));
360
+
361
+ if (!header) {
362
+ throw new Error(`Previous block header ${previousBlockNumber} not found for proving epoch ${epochNumber}`);
363
+ }
364
+
365
+ this.log.verbose(`Gathered previous block header ${header.getBlockNumber()} for epoch ${epochNumber}`);
366
+ return header;
296
367
  }
297
368
 
298
369
  /** Extracted for testing purposes. */
299
370
  protected doCreateEpochProvingJob(
300
- epochNumber: bigint,
371
+ data: EpochProvingJobData,
301
372
  deadline: Date | undefined,
302
- blocks: L2Block[],
303
- txs: Tx[],
304
373
  publicProcessorFactory: PublicProcessorFactory,
305
- cleanUp: () => Promise<void>,
374
+ publisher: ProverNodePublisher,
375
+ opts: { skipEpochCheck?: boolean } = {},
306
376
  ) {
377
+ const { proverNodeMaxParallelBlocksPerEpoch: parallelBlockLimit, proverNodeDisableProofPublish } = this.config;
307
378
  return new EpochProvingJob(
379
+ data,
308
380
  this.worldState,
309
- epochNumber,
310
- blocks,
311
- txs,
312
381
  this.prover.createEpochProver(),
313
382
  publicProcessorFactory,
314
- this.publisher,
383
+ publisher,
315
384
  this.l2BlockSource,
316
- this.l1ToL2MessageSource,
317
- this.metrics,
385
+ this.jobMetrics,
318
386
  deadline,
319
- { parallelBlockLimit: this.options.maxParallelBlocksPerEpoch },
320
- cleanUp,
387
+ { parallelBlockLimit, skipSubmitProof: proverNodeDisableProofPublish, ...opts },
388
+ this.log.getBindings(),
321
389
  );
322
390
  }
323
391
 
@@ -325,10 +393,25 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
325
393
  protected async triggerMonitors() {
326
394
  await this.epochsMonitor.work();
327
395
  }
396
+
397
+ private validateConfig() {
398
+ if (
399
+ this.config.proverNodeFailedEpochStore &&
400
+ (!this.config.dataDirectory || !this.config.l1ChainId || this.config.rollupVersion === undefined)
401
+ ) {
402
+ this.log.warn(
403
+ `Invalid prover-node config (missing dataDirectory, l1ChainId, or rollupVersion)`,
404
+ pick(this.config, 'proverNodeFailedEpochStore', 'dataDirectory', 'l1ChainId', 'rollupVersion'),
405
+ );
406
+ throw new Error(
407
+ 'All of dataDirectory, l1ChainId, and rollupVersion are required if proverNodeFailedEpochStore is set.',
408
+ );
409
+ }
410
+ }
328
411
  }
329
412
 
330
413
  class EmptyEpochError extends Error {
331
- constructor(epochNumber: bigint) {
414
+ constructor(epochNumber: EpochNumber) {
332
415
  super(`No blocks found for epoch ${epochNumber}`);
333
416
  this.name = 'EmptyEpochError';
334
417
  }
@@ -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 { PublisherConfig, TxSenderConfig } 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: TxSenderConfig & PublisherConfig,
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.loadState();
23
+ }
24
+
25
+ public stop() {
26
+ this.deps.publisherManager.interrupt();
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
+ }
package/src/test/index.ts CHANGED
@@ -1,11 +1,14 @@
1
1
  import type { EpochProverManager } from '@aztec/stdlib/interfaces/server';
2
2
 
3
+ import type { EpochProvingJob } from '../job/epoch-proving-job.js';
3
4
  import type { ProverNodePublisher } from '../prover-node-publisher.js';
4
5
  import { ProverNode } from '../prover-node.js';
5
6
 
6
- class TestProverNode_ extends ProverNode {
7
- public override prover!: EpochProverManager;
8
- public override publisher!: ProverNodePublisher;
7
+ abstract class TestProverNodeClass extends ProverNode {
8
+ declare public prover: EpochProverManager;
9
+ declare public publisher: ProverNodePublisher;
10
+
11
+ public abstract override tryUploadEpochFailure(job: EpochProvingJob): Promise<string | undefined>;
9
12
  }
10
13
 
11
- export type TestProverNode = TestProverNode_;
14
+ export type TestProverNode = TestProverNodeClass;
package/dest/http.d.ts DELETED
@@ -1,8 +0,0 @@
1
- import type { ProverNode } from './prover-node.js';
2
- /**
3
- * Wrap a ProverNode instance with a JSON RPC HTTP server.
4
- * @param node - The ProverNode
5
- * @returns An JSON-RPC HTTP server
6
- */
7
- export declare function createProverNodeRpcServer(node: ProverNode): import("@aztec/foundation/json-rpc/server").SafeJsonRpcServer;
8
- //# sourceMappingURL=http.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"http.d.ts","sourceRoot":"","sources":["../src/http.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAEnD;;;;GAIG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,UAAU,iEAEzD"}
package/dest/http.js DELETED
@@ -1,9 +0,0 @@
1
- import { ProverNodeApiSchema } from '@aztec/stdlib/interfaces/server';
2
- import { createTracedJsonRpcServer } from '@aztec/telemetry-client';
3
- /**
4
- * Wrap a ProverNode instance with a JSON RPC HTTP server.
5
- * @param node - The ProverNode
6
- * @returns An JSON-RPC HTTP server
7
- */ export function createProverNodeRpcServer(node) {
8
- return createTracedJsonRpcServer(node, ProverNodeApiSchema);
9
- }
@@ -1,7 +0,0 @@
1
- import { type ConfigMappingsType } from '@aztec/foundation/config';
2
- export type ProverCoordinationConfig = {
3
- proverCoordinationNodeUrl: string | undefined;
4
- };
5
- export declare const proverCoordinationConfigMappings: ConfigMappingsType<ProverCoordinationConfig>;
6
- export declare function getTxProviderConfigFromEnv(): ProverCoordinationConfig;
7
- //# sourceMappingURL=config.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/prover-coordination/config.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,kBAAkB,EAAyB,MAAM,0BAA0B,CAAC;AAE1F,MAAM,MAAM,wBAAwB,GAAG;IACrC,yBAAyB,EAAE,MAAM,GAAG,SAAS,CAAC;CAC/C,CAAC;AAEF,eAAO,MAAM,gCAAgC,EAAE,kBAAkB,CAAC,wBAAwB,CAMzF,CAAC;AAEF,wBAAgB,0BAA0B,IAAI,wBAAwB,CAErE"}