@aztec/prover-node 0.0.0-test.1 → 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,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 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
18
  EpochProvingJobTerminalState,
15
- type ProverCoordination,
19
+ type ITxProvider,
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';
26
+ import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
21
27
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
22
- 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,72 @@ 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
- private dateProvider = new DateProvider();
56
58
 
57
- private latestEpochWeAreProving: bigint | undefined;
58
59
  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;
60
+ private config: ProverNodeOptions;
61
+ private jobMetrics: ProverNodeJobMetrics;
62
+ private rewardsMetrics: ProverNodeRewardsMetrics;
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,129 @@ 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));
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
+ });
114
130
  const activeJobs = await this.getActiveJobsForEpoch(epochNumber);
115
131
  if (activeJobs.length > 0) {
116
- this.log.info(`Not starting proof for ${epochNumber} since there are active jobs`);
117
- return;
132
+ this.log.warn(`Not starting proof for ${epochNumber} since there are active jobs for the epoch`, {
133
+ activeJobs: activeJobs.map(job => job.uuid),
134
+ });
135
+ return true;
118
136
  }
119
- // TODO: we probably want to skip starting a proof if we are too far into the current epoch
120
137
  await this.startProof(epochNumber);
138
+ return true;
121
139
  } catch (err) {
122
140
  if (err instanceof EmptyEpochError) {
123
141
  this.log.info(`Not starting proof for ${epochNumber} since no blocks were found`);
124
142
  } else {
125
143
  this.log.error(`Error handling epoch completed`, err);
126
144
  }
145
+ return false;
127
146
  }
128
147
  }
129
148
 
130
149
  /**
131
- * Starts the prover node so it periodically checks for unproven epochs in the unfinalised chain from L1 and
150
+ * Starts the prover node so it periodically checks for unproven epochs in the unfinalized chain from L1 and
132
151
  * starts proving jobs for them.
133
152
  */
134
- start() {
135
- this.txFetcher.start();
153
+ async start() {
136
154
  this.epochsMonitor.start(this);
137
- this.log.info('Started ProverNode', this.options);
155
+ await this.publisherFactory.start();
156
+ this.publisher = await this.publisherFactory.create();
157
+ await this.rewardsMetrics.start();
158
+ this.l1Metrics.start();
159
+ this.log.info(`Started Prover Node with prover id ${this.prover.getProverId().toString()}`, this.config);
138
160
  }
139
161
 
140
162
  /**
141
163
  * Stops the prover node and all its dependencies.
164
+ * Resources not owned by this node (shared with the parent aztec-node) are skipped.
142
165
  */
143
166
  async stop() {
144
167
  this.log.info('Stopping ProverNode');
145
- await this.txFetcher.stop();
146
168
  await this.epochsMonitor.stop();
147
169
  await this.prover.stop();
148
- await tryStop(this.l2BlockSource);
149
- this.publisher.interrupt();
170
+ await tryStop(this.publisherFactory);
171
+ this.publisher?.interrupt();
150
172
  await Promise.all(Array.from(this.jobs.values()).map(job => job.stop()));
151
- await this.worldState.stop();
152
- await tryStop(this.coordination);
173
+ this.rewardsMetrics.stop();
174
+ this.l1Metrics.stop();
153
175
  await this.telemetryClient.stop();
154
176
  this.log.info('Stopped ProverNode');
155
177
  }
156
178
 
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();
179
+ /** Returns world state status. */
180
+ public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
181
+ const { syncSummary } = await this.worldState.status();
182
+ return syncSummary;
183
+ }
184
+
185
+ /** Returns archiver status. */
186
+ public getL2Tips() {
187
+ return this.l2BlockSource.getL2Tips();
163
188
  }
164
189
 
165
190
  /**
166
191
  * Starts a proving process and returns immediately.
167
192
  */
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));
193
+ public async startProof(epochNumber: EpochNumber) {
194
+ const job = await this.createProvingJob(epochNumber, { skipEpochCheck: true });
195
+ void this.runJob(job);
196
+ }
197
+
198
+ private async runJob(job: EpochProvingJob) {
199
+ const epochNumber = job.getEpochNumber();
200
+ const ctx = { id: job.getId(), epochNumber, state: undefined as EpochProvingJobState | undefined };
201
+
202
+ try {
203
+ await job.run();
204
+ const state = job.getState();
205
+ ctx.state = state;
206
+
207
+ if (state === 'reorg') {
208
+ this.log.warn(`Running new job for epoch ${epochNumber} due to reorg`, ctx);
209
+ await this.createProvingJob(epochNumber);
210
+ } else if (state === 'failed') {
211
+ this.log.error(`Job for ${epochNumber} exited with state ${state}`, ctx);
212
+ await this.tryUploadEpochFailure(job);
213
+ } else {
214
+ this.log.verbose(`Job for ${epochNumber} exited with state ${state}`, ctx);
215
+ }
216
+ } catch (err) {
217
+ this.log.error(`Error proving epoch ${epochNumber}`, err, ctx);
218
+ } finally {
219
+ this.jobs.delete(job.getId());
220
+ }
221
+ }
222
+
223
+ protected async tryUploadEpochFailure(job: EpochProvingJob) {
224
+ if (this.config.proverNodeFailedEpochStore) {
225
+ return await uploadEpochProofFailure(
226
+ this.config.proverNodeFailedEpochStore,
227
+ job.getId(),
228
+ job.getProvingData(),
229
+ this.l2BlockSource as Archiver,
230
+ this.worldState,
231
+ assertRequired(pick(this.config, 'l1ChainId', 'rollupVersion', 'dataDirectory')),
232
+ this.log,
233
+ );
234
+ }
171
235
  }
172
236
 
173
237
  /**
@@ -180,62 +244,63 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
180
244
  /**
181
245
  * Returns an array of jobs being processed.
182
246
  */
183
- public getJobs(): Promise<{ uuid: string; status: EpochProvingJobState; epochNumber: number }[]> {
247
+ public getJobs(): Promise<{ uuid: string; status: EpochProvingJobState; epochNumber: EpochNumber }[]> {
184
248
  return Promise.resolve(
185
249
  Array.from(this.jobs.entries()).map(([uuid, job]) => ({
186
250
  uuid,
187
251
  status: job.getState(),
188
- epochNumber: Number(job.getEpochNumber()),
252
+ epochNumber: job.getEpochNumber(),
189
253
  })),
190
254
  );
191
255
  }
192
256
 
193
257
  protected async getActiveJobsForEpoch(
194
- epochBigInt: bigint,
258
+ epochNumber: EpochNumber,
195
259
  ): Promise<{ uuid: string; status: EpochProvingJobState }[]> {
196
260
  const jobs = await this.getJobs();
197
- const epochNumber = Number(epochBigInt);
198
261
  return jobs.filter(job => job.epochNumber === epochNumber && !EpochProvingJobTerminalState.includes(job.status));
199
262
  }
200
263
 
201
264
  private checkMaximumPendingJobs() {
202
- const { maxPendingJobs } = this.options;
203
- return maxPendingJobs === 0 || this.jobs.size < maxPendingJobs;
204
- }
205
-
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.`);
265
+ const { proverNodeMaxPendingJobs: maxPendingJobs } = this.config;
266
+ if (maxPendingJobs > 0 && this.jobs.size >= maxPendingJobs) {
267
+ throw new Error(`Maximum pending proving jobs ${maxPendingJobs} reached. Cannot create new job.`);
210
268
  }
269
+ }
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));
215
-
216
- const fromBlock = blocks[0].number;
217
- const toBlock = blocks.at(-1)!.number;
271
+ @trackSpan('ProverNode.createProvingJob', epochNumber => ({ [Attributes.EPOCH_NUMBER]: epochNumber }))
272
+ private async createProvingJob(epochNumber: EpochNumber, opts: { skipEpochCheck?: boolean } = {}) {
273
+ this.checkMaximumPendingJobs();
274
+
275
+ this.publisher = await this.publisherFactory.create();
276
+
277
+ // Gather all data for this epoch
278
+ const epochData = await this.gatherEpochData(epochNumber);
279
+ const fromCheckpoint = epochData.checkpoints[0].number;
280
+ const toCheckpoint = epochData.checkpoints.at(-1)!.number;
281
+ const fromBlock = epochData.checkpoints[0].blocks[0].number;
282
+ const lastBlock = epochData.checkpoints.at(-1)!.blocks.at(-1)!;
283
+ const toBlock = lastBlock.number;
284
+ this.log.verbose(
285
+ `Creating proving job for epoch ${epochNumber} for checkpoint range ${fromCheckpoint} to ${toCheckpoint} and block range ${fromBlock} to ${toBlock}`,
286
+ );
218
287
 
219
288
  // 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);
289
+ const lastBlockHash = await lastBlock.header.hash();
290
+ await this.worldState.syncImmediate(toBlock, lastBlockHash);
222
291
 
223
- // Create a processor using the forked world state
292
+ // Create a processor factory
224
293
  const publicProcessorFactory = new PublicProcessorFactory(
225
294
  this.contractDataSource,
226
295
  this.dateProvider,
227
296
  this.telemetryClient,
297
+ this.log.getBindings(),
228
298
  );
229
299
 
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);
300
+ // Set deadline for this job to run. It will abort if it takes too long.
301
+ const deadlineTs = getProofSubmissionDeadlineTimestamp(epochNumber, await this.getL1Constants());
302
+ const deadline = new Date(Number(deadlineTs) * 1000);
303
+ const job = this.doCreateEpochProvingJob(epochData, deadline, publicProcessorFactory, this.publisher, opts);
239
304
  this.jobs.set(job.getId(), job);
240
305
  return job;
241
306
  }
@@ -245,79 +310,88 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
245
310
  return this.l2BlockSource.getL1Constants();
246
311
  }
247
312
 
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 };
313
+ @trackSpan('ProverNode.gatherEpochData', epochNumber => ({ [Attributes.EPOCH_NUMBER]: epochNumber }))
314
+ private async gatherEpochData(epochNumber: EpochNumber): Promise<EpochProvingJobData> {
315
+ const checkpoints = await this.gatherCheckpoints(epochNumber);
316
+ const txArray = await this.gatherTxs(epochNumber, checkpoints);
317
+ const txs = new Map<string, Tx>(txArray.map(tx => [tx.getTxHash().toString(), tx]));
318
+ const l1ToL2Messages = await this.gatherMessages(epochNumber, checkpoints);
319
+ const [firstBlock] = checkpoints[0].blocks;
320
+ const previousBlockHeader = await this.gatherPreviousBlockHeader(epochNumber, firstBlock.number - 1);
321
+ const [lastPublishedCheckpoint] = await this.l2BlockSource.getCheckpoints(checkpoints.at(-1)!.number, 1);
322
+ const attestations = lastPublishedCheckpoint?.attestations ?? [];
323
+
324
+ return { checkpoints, txs, l1ToL2Messages, epochNumber, previousBlockHeader, attestations };
271
325
  }
272
326
 
273
- private async gatherBlocks(epochNumber: bigint) {
274
- const blocks = await this.l2BlockSource.getBlocksForEpoch(epochNumber);
275
- if (blocks.length === 0) {
327
+ private async gatherCheckpoints(epochNumber: EpochNumber) {
328
+ const checkpoints = await this.l2BlockSource.getCheckpointsForEpoch(epochNumber);
329
+ if (checkpoints.length === 0) {
276
330
  throw new EmptyEpochError(epochNumber);
277
331
  }
278
- return blocks;
332
+ return checkpoints;
279
333
  }
280
334
 
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);
335
+ private async gatherTxs(epochNumber: EpochNumber, checkpoints: Checkpoint[]) {
336
+ const deadline = new Date(this.dateProvider.now() + this.config.txGatheringTimeoutMs);
337
+ const txProvider = this.p2pClient.getTxProvider();
338
+ const blocks = checkpoints.flatMap(checkpoint => checkpoint.blocks);
339
+ const txsByBlock = await Promise.all(blocks.map(block => txProvider.getTxsForBlock(block, { deadline })));
340
+ const txs = txsByBlock.map(({ txs }) => txs).flat();
341
+ const missingTxs = txsByBlock.map(({ missingTxs }) => missingTxs).flat();
284
342
 
285
- if (txs.length === txsToFind.length) {
343
+ if (missingTxs.length === 0) {
286
344
  this.log.verbose(`Gathered all ${txs.length} txs for epoch ${epochNumber}`, { epochNumber });
287
345
  return txs;
288
346
  }
289
347
 
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(', ');
348
+ throw new Error(`Txs not found for epoch ${epochNumber}: ${missingTxs.map(hash => hash.toString()).join(', ')}`);
349
+ }
350
+
351
+ private async gatherMessages(epochNumber: EpochNumber, checkpoints: Checkpoint[]) {
352
+ const messages = await Promise.all(checkpoints.map(c => this.l1ToL2MessageSource.getL1ToL2Messages(c.number)));
353
+ const messageCount = sum(messages.map(m => m.length));
354
+ this.log.verbose(`Gathered all ${messageCount} messages for epoch ${epochNumber}`, { epochNumber });
355
+ const messagesByCheckpoint: Record<CheckpointNumber, Fr[]> = {};
356
+ for (let i = 0; i < checkpoints.length; i++) {
357
+ messagesByCheckpoint[checkpoints[i].number] = messages[i];
358
+ }
359
+ return messagesByCheckpoint;
360
+ }
361
+
362
+ private async gatherPreviousBlockHeader(epochNumber: EpochNumber, previousBlockNumber: number) {
363
+ const header = await (previousBlockNumber === 0
364
+ ? this.worldState.getCommitted().getInitialHeader()
365
+ : this.l2BlockSource.getBlockHeader(BlockNumber(previousBlockNumber)));
366
+
367
+ if (!header) {
368
+ throw new Error(`Previous block header ${previousBlockNumber} not found for proving epoch ${epochNumber}`);
369
+ }
294
370
 
295
- throw new Error(`Txs not found for epoch ${epochNumber}: ${missingTxHashes}`);
371
+ this.log.verbose(`Gathered previous block header ${header.getBlockNumber()} for epoch ${epochNumber}`);
372
+ return header;
296
373
  }
297
374
 
298
375
  /** Extracted for testing purposes. */
299
376
  protected doCreateEpochProvingJob(
300
- epochNumber: bigint,
377
+ data: EpochProvingJobData,
301
378
  deadline: Date | undefined,
302
- blocks: L2Block[],
303
- txs: Tx[],
304
379
  publicProcessorFactory: PublicProcessorFactory,
305
- cleanUp: () => Promise<void>,
380
+ publisher: ProverNodePublisher,
381
+ opts: { skipEpochCheck?: boolean } = {},
306
382
  ) {
383
+ const { proverNodeMaxParallelBlocksPerEpoch: parallelBlockLimit, proverNodeDisableProofPublish } = this.config;
307
384
  return new EpochProvingJob(
385
+ data,
308
386
  this.worldState,
309
- epochNumber,
310
- blocks,
311
- txs,
312
387
  this.prover.createEpochProver(),
313
388
  publicProcessorFactory,
314
- this.publisher,
389
+ publisher,
315
390
  this.l2BlockSource,
316
- this.l1ToL2MessageSource,
317
- this.metrics,
391
+ this.jobMetrics,
318
392
  deadline,
319
- { parallelBlockLimit: this.options.maxParallelBlocksPerEpoch },
320
- cleanUp,
393
+ { parallelBlockLimit, skipSubmitProof: proverNodeDisableProofPublish, ...opts },
394
+ this.log.getBindings(),
321
395
  );
322
396
  }
323
397
 
@@ -325,10 +399,25 @@ export class ProverNode implements EpochMonitorHandler, ProverNodeApi, Traceable
325
399
  protected async triggerMonitors() {
326
400
  await this.epochsMonitor.work();
327
401
  }
402
+
403
+ private validateConfig() {
404
+ if (
405
+ this.config.proverNodeFailedEpochStore &&
406
+ (!this.config.dataDirectory || !this.config.l1ChainId || this.config.rollupVersion === undefined)
407
+ ) {
408
+ this.log.warn(
409
+ `Invalid prover-node config (missing dataDirectory, l1ChainId, or rollupVersion)`,
410
+ pick(this.config, 'proverNodeFailedEpochStore', 'dataDirectory', 'l1ChainId', 'rollupVersion'),
411
+ );
412
+ throw new Error(
413
+ 'All of dataDirectory, l1ChainId, and rollupVersion are required if proverNodeFailedEpochStore is set.',
414
+ );
415
+ }
416
+ }
328
417
  }
329
418
 
330
419
  class EmptyEpochError extends Error {
331
- constructor(epochNumber: bigint) {
420
+ constructor(epochNumber: EpochNumber) {
332
421
  super(`No blocks found for epoch ${epochNumber}`);
333
422
  this.name = 'EmptyEpochError';
334
423
  }
@@ -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.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
- }