@aztec/prover-node 0.0.1-commit.c31f2472 → 0.0.1-commit.c52d6e7

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 (75) hide show
  1. package/README.md +572 -0
  2. package/dest/actions/download-epoch-proving-job.js +1 -1
  3. package/dest/actions/rerun-epoch-proving-job.d.ts +14 -4
  4. package/dest/actions/rerun-epoch-proving-job.d.ts.map +1 -1
  5. package/dest/actions/rerun-epoch-proving-job.js +244 -24
  6. package/dest/actions/upload-epoch-proof-failure.d.ts +2 -2
  7. package/dest/actions/upload-epoch-proof-failure.d.ts.map +1 -1
  8. package/dest/bin/run-failed-epoch.js +6 -5
  9. package/dest/checkpoint-store.d.ts +95 -0
  10. package/dest/checkpoint-store.d.ts.map +1 -0
  11. package/dest/checkpoint-store.js +178 -0
  12. package/dest/config.d.ts +7 -8
  13. package/dest/config.d.ts.map +1 -1
  14. package/dest/config.js +24 -20
  15. package/dest/factory.d.ts +22 -13
  16. package/dest/factory.d.ts.map +1 -1
  17. package/dest/factory.js +41 -65
  18. package/dest/index.d.ts +2 -1
  19. package/dest/index.d.ts.map +1 -1
  20. package/dest/index.js +1 -0
  21. package/dest/job/checkpoint-prover.d.ts +165 -0
  22. package/dest/job/checkpoint-prover.d.ts.map +1 -0
  23. package/dest/job/checkpoint-prover.js +405 -0
  24. package/dest/job/epoch-session.d.ts +160 -0
  25. package/dest/job/epoch-session.d.ts.map +1 -0
  26. package/dest/job/{epoch-proving-job.js → epoch-session.js} +301 -298
  27. package/dest/job/top-tree-job.d.ts +82 -0
  28. package/dest/job/top-tree-job.d.ts.map +1 -0
  29. package/dest/job/top-tree-job.js +152 -0
  30. package/dest/metrics.d.ts +40 -3
  31. package/dest/metrics.d.ts.map +1 -1
  32. package/dest/metrics.js +101 -4
  33. package/dest/monitors/epoch-monitor.d.ts +1 -1
  34. package/dest/monitors/epoch-monitor.d.ts.map +1 -1
  35. package/dest/monitors/epoch-monitor.js +11 -9
  36. package/dest/proof-publishing-service.d.ts +161 -0
  37. package/dest/proof-publishing-service.d.ts.map +1 -0
  38. package/dest/proof-publishing-service.js +335 -0
  39. package/dest/prover-node-publisher.d.ts +25 -15
  40. package/dest/prover-node-publisher.d.ts.map +1 -1
  41. package/dest/prover-node-publisher.js +202 -63
  42. package/dest/prover-node.d.ts +146 -69
  43. package/dest/prover-node.d.ts.map +1 -1
  44. package/dest/prover-node.js +545 -221
  45. package/dest/prover-publisher-factory.d.ts +6 -4
  46. package/dest/prover-publisher-factory.d.ts.map +1 -1
  47. package/dest/prover-publisher-factory.js +4 -3
  48. package/dest/session-manager.d.ts +158 -0
  49. package/dest/session-manager.d.ts.map +1 -0
  50. package/dest/session-manager.js +492 -0
  51. package/dest/test/index.d.ts +7 -6
  52. package/dest/test/index.d.ts.map +1 -1
  53. package/package.json +24 -22
  54. package/src/actions/download-epoch-proving-job.ts +1 -1
  55. package/src/actions/rerun-epoch-proving-job.ts +190 -31
  56. package/src/actions/upload-epoch-proof-failure.ts +1 -1
  57. package/src/bin/run-failed-epoch.ts +5 -3
  58. package/src/checkpoint-store.ts +212 -0
  59. package/src/config.ts +35 -32
  60. package/src/factory.ts +73 -111
  61. package/src/index.ts +1 -0
  62. package/src/job/checkpoint-prover.ts +538 -0
  63. package/src/job/epoch-session.ts +462 -0
  64. package/src/job/top-tree-job.ts +227 -0
  65. package/src/metrics.ts +123 -10
  66. package/src/monitors/epoch-monitor.ts +5 -6
  67. package/src/proof-publishing-service.ts +427 -0
  68. package/src/prover-node-publisher.ts +237 -79
  69. package/src/prover-node.ts +631 -248
  70. package/src/prover-publisher-factory.ts +8 -5
  71. package/src/session-manager.ts +592 -0
  72. package/src/test/index.ts +6 -6
  73. package/dest/job/epoch-proving-job.d.ts +0 -63
  74. package/dest/job/epoch-proving-job.d.ts.map +0 -1
  75. package/src/job/epoch-proving-job.ts +0 -435
@@ -1,42 +1,262 @@
1
- import { createArchiverStore } from '@aztec/archiver';
1
+ function _ts_add_disposable_resource(env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() {
16
+ try {
17
+ inner.call(this);
18
+ } catch (e) {
19
+ return Promise.reject(e);
20
+ }
21
+ };
22
+ env.stack.push({
23
+ value: value,
24
+ dispose: dispose,
25
+ async: async
26
+ });
27
+ } else if (async) {
28
+ env.stack.push({
29
+ async: true
30
+ });
31
+ }
32
+ return value;
33
+ }
34
+ function _ts_dispose_resources(env) {
35
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
36
+ var e = new Error(message);
37
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
38
+ };
39
+ return (_ts_dispose_resources = function _ts_dispose_resources(env) {
40
+ function fail(e) {
41
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
42
+ env.hasError = true;
43
+ }
44
+ var r, s = 0;
45
+ function next() {
46
+ while(r = env.stack.pop()){
47
+ try {
48
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
49
+ if (r.dispose) {
50
+ var result = r.dispose.call(r.value);
51
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
52
+ fail(e);
53
+ return next();
54
+ });
55
+ } else s |= 1;
56
+ } catch (e) {
57
+ fail(e);
58
+ }
59
+ }
60
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
61
+ if (env.hasError) throw env.error;
62
+ }
63
+ return next();
64
+ })(env);
65
+ }
66
+ import { createArchiverStore, createContractDataSource } from '@aztec/archiver';
67
+ import { BlockNumber } from '@aztec/foundation/branded-types';
68
+ import { DateProvider } from '@aztec/foundation/timer';
2
69
  import { createProverClient } from '@aztec/prover-client';
3
70
  import { createAndStartProvingBroker } from '@aztec/prover-client/broker';
4
- import { PublicProcessorFactory } from '@aztec/simulator/server';
71
+ import { getLastSiblingPath } from '@aztec/prover-client/helpers';
72
+ import { ChonkCache } from '@aztec/prover-client/orchestrator';
73
+ import { AvmSimulatorPool, PublicProcessorFactory } from '@aztec/simulator/server';
74
+ import { getEpochAtSlot, getSlotRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
75
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
5
76
  import { getTelemetryClient } from '@aztec/telemetry-client';
6
77
  import { createWorldState } from '@aztec/world-state';
7
78
  import { readFileSync } from 'fs';
79
+ import { CheckpointProver } from '../job/checkpoint-prover.js';
8
80
  import { deserializeEpochProvingJobData } from '../job/epoch-proving-job-data.js';
9
- import { EpochProvingJob } from '../job/epoch-proving-job.js';
81
+ import { EpochSession } from '../job/epoch-session.js';
10
82
  import { ProverNodeJobMetrics } from '../metrics.js';
11
83
  /**
12
84
  * Given a local folder where `downloadEpochProvingJob` was called, creates a new archiver and world state
13
- * using the state snapshots, and creates a new epoch proving job to prove the downloaded proving job.
85
+ * using the state snapshots, and creates a new epoch proving session to prove the downloaded proving job.
14
86
  * Proving is done with a local proving broker and agents as specified by the config.
15
- */ export async function rerunEpochProvingJob(localPath, log, config) {
87
+ */ export async function rerunEpochProvingJob(localPath, log, config, genesis) {
88
+ const env = {
89
+ stack: [],
90
+ error: void 0,
91
+ hasError: false
92
+ };
93
+ try {
94
+ const ctx = _ts_add_disposable_resource(env, await createRerunContext(localPath, log, config, genesis), true);
95
+ const { jobData, prover, metrics } = ctx;
96
+ log.info(`Rerunning epoch proving for epoch ${jobData.epochNumber}`);
97
+ const provers = [];
98
+ for(let i = 0; i < jobData.checkpoints.length; i++){
99
+ provers.push(await buildCheckpointProver(ctx, i, log));
100
+ }
101
+ // Local rerun never publishes — stub the service so submit() always resolves 'published'
102
+ // and withdraw is a no-op.
103
+ const publishingService = {
104
+ submit: ()=>Promise.resolve('published'),
105
+ withdraw: ()=>{}
106
+ };
107
+ const l1Constants = {
108
+ epochDuration: config.aztecEpochDuration
109
+ };
110
+ const [fromSlot, toSlot] = getSlotRangeForEpoch(jobData.epochNumber, l1Constants);
111
+ const spec = {
112
+ kind: 'full',
113
+ epochNumber: jobData.epochNumber,
114
+ fromSlot,
115
+ toSlot
116
+ };
117
+ const session = new EpochSession(spec, provers, {
118
+ proverFactory: prover,
119
+ proverId: prover.getProverId(),
120
+ publishingService,
121
+ metrics,
122
+ dateProvider: new DateProvider(),
123
+ deadline: undefined,
124
+ config: {},
125
+ bindings: log.getBindings()
126
+ });
127
+ const finalState = await session.start();
128
+ log.info(`Completed proving for epoch ${jobData.epochNumber} with status ${finalState}`, {
129
+ derivedEpoch: getEpochAtSlot(provers[0].slotNumber, l1Constants)
130
+ });
131
+ return finalState;
132
+ } catch (e) {
133
+ env.error = e;
134
+ env.hasError = true;
135
+ } finally{
136
+ const result = _ts_dispose_resources(env);
137
+ if (result) await result;
138
+ }
139
+ }
140
+ /**
141
+ * Re-proves a single downloaded checkpoint proving job (as uploaded by a `CheckpointProver` failure).
142
+ * Reconstructs just that checkpoint's sub-tree prover from the snapshot and awaits its block proofs — no
143
+ * epoch top-tree, no L1 submission — so a checkpoint-level failure can be reproduced offline in isolation.
144
+ * Returns the block-rollup proof outputs on success; throws if the checkpoint fails to prove again.
145
+ */ export async function rerunCheckpointProvingJob(localPath, log, config, genesis) {
146
+ const env = {
147
+ stack: [],
148
+ error: void 0,
149
+ hasError: false
150
+ };
151
+ try {
152
+ const ctx = _ts_add_disposable_resource(env, await createRerunContext(localPath, log, config, genesis), true);
153
+ const { jobData } = ctx;
154
+ const checkpointNumber = jobData.checkpoints[0].number;
155
+ log.info(`Rerunning checkpoint proving for checkpoint ${checkpointNumber} (epoch ${jobData.epochNumber})`);
156
+ const prover = await buildCheckpointProver(ctx, 0, log);
157
+ try {
158
+ const blockProofs = await prover.whenBlockProofsReady();
159
+ log.info(`Completed proving for checkpoint ${checkpointNumber} with ${blockProofs.length} block proof(s)`);
160
+ return blockProofs;
161
+ } finally{
162
+ prover.cancel({
163
+ routine: true
164
+ });
165
+ await prover.whenDone();
166
+ }
167
+ } catch (e) {
168
+ env.error = e;
169
+ env.hasError = true;
170
+ } finally{
171
+ const result = _ts_dispose_resources(env);
172
+ if (result) await result;
173
+ }
174
+ }
175
+ /**
176
+ * Rebuilds the offline proving environment from a downloaded job: world state + archiver from the
177
+ * snapshots, a local proving broker + client, a chonk cache, and a tx provider that replays the job's txs.
178
+ */ async function createRerunContext(localPath, log, config, genesis) {
16
179
  const jobData = deserializeEpochProvingJobData(readFileSync(localPath));
17
180
  log.info(`Loaded proving job data for epoch ${jobData.epochNumber}`);
18
181
  const telemetry = getTelemetryClient();
19
182
  const metrics = new ProverNodeJobMetrics(telemetry.getMeter('prover-job'), telemetry.getTracer('prover-job'));
20
- const worldState = await createWorldState(config);
21
- const archiver = await createArchiverStore(config, {
22
- epochDuration: config.aztecEpochDuration
183
+ const worldState = await createWorldState(config, genesis);
184
+ const initialBlockHash = await worldState.getInitialHeader().hash();
185
+ const archiver = await createArchiverStore(config, initialBlockHash);
186
+ const avmSimulator = await AvmSimulatorPool.spawn({
187
+ wsdbIpcPath: worldState.getIpcPath()
23
188
  });
24
- const publicProcessorFactory = new PublicProcessorFactory(archiver, undefined, undefined, log.getBindings());
25
- const publisher = {
26
- submitEpochProof: ()=>Promise.resolve(true)
27
- };
28
- const l2BlockSourceForReorgDetection = undefined;
29
- const deadline = undefined;
30
- // This starts a local proving broker that does not get exposed as a service. This should be good enough for
31
- // smallish epochs to be proven if we run on a large machine, but as epochs grow larger, we may want to switch
32
- // this out for a live proving broker with multiple agents that we can connect to.
189
+ const publicProcessorFactory = new PublicProcessorFactory(createContractDataSource(archiver), avmSimulator, undefined, undefined, log.getBindings());
33
190
  const broker = await createAndStartProvingBroker(config, telemetry);
34
191
  const prover = await createProverClient(config, worldState, broker, telemetry);
35
- const provingJob = new EpochProvingJob(jobData, worldState, prover.createEpochProver(), publicProcessorFactory, publisher, l2BlockSourceForReorgDetection, metrics, deadline, {
36
- skipEpochCheck: true
37
- }, log.getBindings());
38
- log.info(`Rerunning epoch proving job for epoch ${jobData.epochNumber}`);
39
- await provingJob.run();
40
- log.info(`Completed job for epoch ${jobData.epochNumber} with status ${provingJob.getState()}`);
41
- return provingJob.getState();
192
+ const chonkCache = new ChonkCache(log.getBindings());
193
+ const txProvider = makeReplayingTxProvider(jobData.txs);
194
+ return {
195
+ jobData,
196
+ metrics,
197
+ worldState,
198
+ publicProcessorFactory,
199
+ prover,
200
+ chonkCache,
201
+ txProvider,
202
+ async [Symbol.asyncDispose] () {
203
+ await avmSimulator[Symbol.asyncDispose]();
204
+ await worldState[Symbol.asyncDispose]();
205
+ }
206
+ };
207
+ }
208
+ /** Reconstructs the `CheckpointProver` for the checkpoint at `index` in the job, ready to prove. */ async function buildCheckpointProver(ctx, index, log) {
209
+ const { jobData, worldState, prover, chonkCache, publicProcessorFactory, txProvider, metrics } = ctx;
210
+ const checkpoint = jobData.checkpoints[index];
211
+ const previousBlockHeader = index === 0 ? jobData.previousBlockHeader : jobData.checkpoints[index - 1].blocks.at(-1).header;
212
+ const l1ToL2Messages = jobData.l1ToL2Messages[checkpoint.number] ?? [];
213
+ const previousArchiveSiblingPath = await getLastSiblingPath(MerkleTreeId.ARCHIVE, worldState.getSnapshot(BlockNumber(checkpoint.blocks[0].number - 1)));
214
+ const attestations = checkpoint.number === jobData.checkpoints.at(-1).number ? jobData.attestations : [];
215
+ return new CheckpointProver({
216
+ checkpoint,
217
+ epochNumber: jobData.epochNumber,
218
+ attestations,
219
+ previousBlockHeader,
220
+ l1ToL2Messages,
221
+ previousArchiveSiblingPath
222
+ }, {
223
+ proverFactory: prover,
224
+ chonkCache,
225
+ publicProcessorFactory,
226
+ dbProvider: worldState,
227
+ txProvider,
228
+ dateProvider: new DateProvider(),
229
+ proverId: prover.getProverId(),
230
+ metrics,
231
+ txGatheringTimeoutMs: 120_000,
232
+ deadline: undefined,
233
+ log
234
+ });
235
+ }
236
+ /** Build a synthetic ITxProvider that returns the supplied txs map by lookup. */ function makeReplayingTxProvider(txs) {
237
+ const lookup = (hashes)=>{
238
+ const found = [];
239
+ const missing = [];
240
+ for (const hash of hashes){
241
+ const tx = txs.get(hash.toString());
242
+ if (tx) {
243
+ found.push(tx);
244
+ } else {
245
+ missing.push(hash);
246
+ }
247
+ }
248
+ return {
249
+ txs: found,
250
+ missingTxs: missing
251
+ };
252
+ };
253
+ return {
254
+ getAvailableTxs: (hashes)=>Promise.resolve(lookup(hashes)),
255
+ hasTxs: (hashes)=>Promise.resolve(hashes.map((h)=>txs.has(h.toString()))),
256
+ getTxsForBlockProposal: ()=>Promise.resolve({
257
+ txs: [],
258
+ missingTxs: []
259
+ }),
260
+ getTxsForBlock: (block)=>Promise.resolve(lookup(block.body.txEffects.map((e)=>e.txHash)))
261
+ };
42
262
  }
@@ -1,8 +1,8 @@
1
1
  import { type Archiver } from '@aztec/archiver';
2
2
  import type { Logger } from '@aztec/foundation/log';
3
- import type { DataStoreConfig } from '@aztec/kv-store/config';
4
3
  import type { ChainConfig } from '@aztec/stdlib/config';
5
4
  import type { WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
5
+ import type { DataStoreConfig } from '@aztec/stdlib/kv-store';
6
6
  import { type EpochProvingJobData } from '../job/epoch-proving-job-data.js';
7
7
  type UploadEpochProofConfig = Pick<ChainConfig, 'l1ChainId' | 'rollupVersion'> & Pick<DataStoreConfig, 'dataDirectory'>;
8
8
  /**
@@ -12,4 +12,4 @@ type UploadEpochProofConfig = Pick<ChainConfig, 'l1ChainId' | 'rollupVersion'> &
12
12
  */
13
13
  export declare function uploadEpochProofFailure(location: string, jobId: string, jobData: EpochProvingJobData, archiver: Archiver, worldState: WorldStateSynchronizer, config: UploadEpochProofConfig, log: Logger): Promise<string>;
14
14
  export {};
15
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidXBsb2FkLWVwb2NoLXByb29mLWZhaWx1cmUuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9hY3Rpb25zL3VwbG9hZC1lcG9jaC1wcm9vZi1mYWlsdXJlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFBdUIsS0FBSyxRQUFRLEVBQUUsTUFBTSxpQkFBaUIsQ0FBQztBQUdyRSxPQUFPLEtBQUssRUFBRSxNQUFNLEVBQUUsTUFBTSx1QkFBdUIsQ0FBQztBQUVwRCxPQUFPLEtBQUssRUFBRSxlQUFlLEVBQUUsTUFBTSx3QkFBd0IsQ0FBQztBQUU5RCxPQUFPLEtBQUssRUFBRSxXQUFXLEVBQUUsTUFBTSxzQkFBc0IsQ0FBQztBQUV4RCxPQUFPLEtBQUssRUFBRSxzQkFBc0IsRUFBRSxNQUFNLGlDQUFpQyxDQUFDO0FBUTlFLE9BQU8sRUFBRSxLQUFLLG1CQUFtQixFQUFnQyxNQUFNLGtDQUFrQyxDQUFDO0FBRTFHLEtBQUssc0JBQXNCLEdBQUcsSUFBSSxDQUFDLFdBQVcsRUFBRSxXQUFXLEdBQUcsZUFBZSxDQUFDLEdBQUcsSUFBSSxDQUFDLGVBQWUsRUFBRSxlQUFlLENBQUMsQ0FBQztBQUt4SDs7OztHQUlHO0FBQ0gsd0JBQXNCLHVCQUF1QixDQUMzQyxRQUFRLEVBQUUsTUFBTSxFQUNoQixLQUFLLEVBQUUsTUFBTSxFQUNiLE9BQU8sRUFBRSxtQkFBbUIsRUFDNUIsUUFBUSxFQUFFLFFBQVEsRUFDbEIsVUFBVSxFQUFFLHNCQUFzQixFQUNsQy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LEVBQzlCLEdBQUcsRUFBRSxNQUFNLG1CQXVDWiJ9
@@ -1 +1 @@
1
- {"version":3,"file":"upload-epoch-proof-failure.d.ts","sourceRoot":"","sources":["../../src/actions/upload-epoch-proof-failure.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAGrE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAEpD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAE9D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAExD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AAQ9E,OAAO,EAAE,KAAK,mBAAmB,EAAgC,MAAM,kCAAkC,CAAC;AAE1G,KAAK,sBAAsB,GAAG,IAAI,CAAC,WAAW,EAAE,WAAW,GAAG,eAAe,CAAC,GAAG,IAAI,CAAC,eAAe,EAAE,eAAe,CAAC,CAAC;AAKxH;;;;GAIG;AACH,wBAAsB,uBAAuB,CAC3C,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,mBAAmB,EAC5B,QAAQ,EAAE,QAAQ,EAClB,UAAU,EAAE,sBAAsB,EAClC,MAAM,EAAE,sBAAsB,EAC9B,GAAG,EAAE,MAAM,mBAuCZ"}
1
+ {"version":3,"file":"upload-epoch-proof-failure.d.ts","sourceRoot":"","sources":["../../src/actions/upload-epoch-proof-failure.ts"],"names":[],"mappings":"AAAA,OAAO,EAAuB,KAAK,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAGrE,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AAGpD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAExD,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,iCAAiC,CAAC;AAC9E,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAQ9D,OAAO,EAAE,KAAK,mBAAmB,EAAgC,MAAM,kCAAkC,CAAC;AAE1G,KAAK,sBAAsB,GAAG,IAAI,CAAC,WAAW,EAAE,WAAW,GAAG,eAAe,CAAC,GAAG,IAAI,CAAC,eAAe,EAAE,eAAe,CAAC,CAAC;AAKxH;;;;GAIG;AACH,wBAAsB,uBAAuB,CAC3C,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,EACb,OAAO,EAAE,mBAAmB,EAC5B,QAAQ,EAAE,QAAQ,EAClB,UAAU,EAAE,sBAAsB,EAClC,MAAM,EAAE,sBAAsB,EAC9B,GAAG,EAAE,MAAM,mBAuCZ"}
@@ -1,4 +1,5 @@
1
- /* eslint-disable no-console */ import { EthAddress } from '@aztec/foundation/eth-address';
1
+ /* eslint-disable no-console */ import { getL1ContractsConfigEnvVars } from '@aztec/ethereum/config';
2
+ import { EthAddress } from '@aztec/foundation/eth-address';
2
3
  import { jsonParseWithSchema, jsonStringify } from '@aztec/foundation/json-rpc';
3
4
  import { createLogger } from '@aztec/foundation/log';
4
5
  import { downloadEpochProvingJob, getProverNodeConfigFromEnv, rerunEpochProvingJob } from '@aztec/prover-node';
@@ -15,8 +16,10 @@ async function rerunFailedEpoch(provingJobUrl, baseLocalDir) {
15
16
  const jobPath = join(localDir, 'data.bin');
16
17
  const dataDir = join(localDir, 'state');
17
18
  const env = getProverNodeConfigFromEnv();
19
+ const l1Config = getL1ContractsConfigEnvVars();
18
20
  const config = {
19
- ...getProverNodeConfigFromEnv(),
21
+ ...env,
22
+ ...l1Config,
20
23
  dataDirectory: dataDir,
21
24
  dataStoreMapSizeKb: env.dataStoreMapSizeKb ?? 1024 * 1024,
22
25
  proverId: env.proverId ?? EthAddress.random()
@@ -38,9 +41,7 @@ async function rerunFailedEpoch(provingJobUrl, baseLocalDir) {
38
41
  logger.info(`Rerunning proving job from ${jobPath} with state from ${dataDir}`, metadata);
39
42
  const result = await rerunEpochProvingJob(jobPath, logger, {
40
43
  ...config,
41
- l1Contracts: {
42
- rollupAddress: metadata.rollupAddress
43
- },
44
+ rollupAddress: metadata.rollupAddress,
44
45
  rollupVersion: metadata.rollupVersion
45
46
  });
46
47
  console.error(`Epoch proving job complete with result ${result}`);
@@ -0,0 +1,95 @@
1
+ import type { BlockNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
2
+ import { type LoggerBindings } from '@aztec/foundation/log';
3
+ import type { L2BlockSource } from '@aztec/stdlib/block';
4
+ import type { Checkpoint } from '@aztec/stdlib/checkpoint';
5
+ import { type L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
6
+ import { CheckpointProver, type CheckpointProverArgs, type CheckpointProverDeps, type CheckpointProverTestHooks } from './job/checkpoint-prover.js';
7
+ /** Register-time data needed to construct a `CheckpointProver` (everything except the checkpoint + epoch). */
8
+ export type RegisterCheckpointData = Omit<CheckpointProverArgs, 'checkpoint' | 'epochNumber'>;
9
+ /** Factory used by the store to construct new provers. Tests can inject a stub. */
10
+ export type CheckpointProverFactory = (args: CheckpointProverArgs, deps: CheckpointProverDeps) => CheckpointProver;
11
+ /**
12
+ * Prover-node-wide registry of `CheckpointProver` instances, content-addressed by
13
+ * `(checkpoint number, slot, checkpoint archive root)`.
14
+ *
15
+ * The store survives every epoch / session boundary. A prover lives from its first
16
+ * `addOrUpdate` call until either:
17
+ * - its checkpoint is pruned by an L1 reorg (`cancelAndRemoveAboveBlock`), or
18
+ * - its epoch's proof-submission window has closed (`reapExpired`), so the proof could no
19
+ * longer be accepted on L1 even if produced.
20
+ *
21
+ * A prover's sub-tree work forks world-state per block and does not survive a prune of a base
22
+ * block, so there is nothing to preserve across a reorg: a pruned prover is cancelled and
23
+ * dropped, and a re-add (even of identical content) constructs a fresh prover.
24
+ */
25
+ export declare class CheckpointStore {
26
+ private readonly l2BlockSource;
27
+ private readonly proverDeps;
28
+ private readonly proverFactoryFn;
29
+ private readonly provers;
30
+ /**
31
+ * Teardowns of provers already removed from `provers` (by prune or reap), awaited on `stop()`.
32
+ * Keyed by a monotonic id rather than the prover's content id: a prune-then-re-add can leave two
33
+ * teardowns for the same content id in flight at once, which a content-id key would clobber.
34
+ */
35
+ private readonly pendingTeardowns;
36
+ private nextTeardownId;
37
+ /** Test-only hooks injected into every prover this store constructs. */
38
+ private testHooks;
39
+ private readonly log;
40
+ constructor(l2BlockSource: Pick<L2BlockSource, 'getL1Constants'>, proverDeps: Omit<CheckpointProverDeps, 'log'>, bindings?: LoggerBindings, proverFactoryFn?: CheckpointProverFactory);
41
+ start(): Promise<void>;
42
+ stop(): Promise<void>;
43
+ /**
44
+ * Tracks the teardown of a prover just removed from the store so `stop()` can await it. The entry
45
+ * removes itself once teardown settles, so the map stays bounded by the number in flight.
46
+ */
47
+ private trackTeardown;
48
+ /**
49
+ * Registers a checkpoint with the store. If a prover already exists for the
50
+ * `(number, slot, archive root)` content key it is reused (an at-least-once re-registration of
51
+ * still-canonical content); otherwise a new prover is constructed.
52
+ */
53
+ addOrUpdate(checkpoint: Checkpoint, data: RegisterCheckpointData): Promise<CheckpointProver>;
54
+ /**
55
+ * Installs test-only hooks applied to every prover constructed from now on. Used by the e2e harness to
56
+ * force a checkpoint sub-tree failure without monkey-patching the prover factory.
57
+ */
58
+ setTestHooks(hooks: CheckpointProverTestHooks): void;
59
+ /**
60
+ * Cancels and removes every prover that holds a block above the prune target. A checkpoint is orphaned by a prune to
61
+ * block `targetBlockNumber` iff its last block sits above the target — including a checkpoint whose range straddles
62
+ * the target (partially orphaned), which block-range marking catches without boundary ambiguity. Keying off the
63
+ * surviving block number (rather than a checkpoint number) is correct even when the source has already
64
+ * re-checkpointed past the divergence: the prune event reports the highest surviving block, which by construction
65
+ * survives on the source, whereas the source's current checkpointed tip can sit above the prune target.
66
+ *
67
+ * The prover's in-flight sub-tree work forks world-state per block and faults once its base block is pruned, so it
68
+ * cannot be reused; it is cancelled (aborting the fork reads) and dropped. A subsequent re-add constructs a fresh
69
+ * prover. Returns the removed provers.
70
+ */
71
+ cancelAndRemoveAboveBlock(targetBlockNumber: BlockNumber): CheckpointProver[];
72
+ /**
73
+ * Drops provers whose epoch is at or below the supplied expired epoch. Once an epoch's
74
+ * proof-submission window has closed, its proof can no longer be accepted on L1, so the
75
+ * prover is no longer needed.
76
+ */
77
+ reapExpired(expiredEpoch: EpochNumber): void;
78
+ /** Returns the prover with the supplied id, or undefined. */
79
+ get(id: string): CheckpointProver | undefined;
80
+ /** Returns the prover for the supplied checkpoint (by its content-addressed id), or undefined. */
81
+ getByCheckpoint(checkpoint: Checkpoint): CheckpointProver | undefined;
82
+ /** Every prover currently in the store, in insertion order. */
83
+ listAll(): CheckpointProver[];
84
+ /** Provers in the store, sorted by checkpoint number. */
85
+ list(): CheckpointProver[];
86
+ /**
87
+ * Provers whose slot is in the supplied epoch's slot range, sorted by checkpoint number.
88
+ */
89
+ listForEpoch(epoch: EpochNumber): Promise<CheckpointProver[]>;
90
+ /** Provers whose slot falls within `[fromSlot, toSlot]`, sorted by checkpoint number. */
91
+ listInSlotRange(fromSlot: SlotNumber, toSlot: SlotNumber): CheckpointProver[];
92
+ }
93
+ /** Sub-set of `L1RollupConstants` actually consumed by the store's slot helpers. */
94
+ export type CheckpointStoreL1Constants = Pick<L1RollupConstants, 'epochDuration'>;
95
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY2hlY2twb2ludC1zdG9yZS5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2NoZWNrcG9pbnQtc3RvcmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxLQUFLLEVBQUUsV0FBVyxFQUFvQixXQUFXLEVBQUUsVUFBVSxFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFDOUcsT0FBTyxFQUFlLEtBQUssY0FBYyxFQUFnQixNQUFNLHVCQUF1QixDQUFDO0FBQ3ZGLE9BQU8sS0FBSyx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B,EAAE,CAEhC;IAED;;OAEG;IACU,YAAY,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,gBAAgB,EAAE,CAAC,CAIzE;IAED,yFAAyF;IAClF,eAAe,CAAC,QAAQ,EAAE,UAAU,EAAE,MAAM,EAAE,UAAU,GAAG,gBAAgB,EAAE,CAEnF;CACF;AAED,oFAAoF;AACpF,MAAM,MAAM,0BAA0B,GAAG,IAAI,CAAC,iBAAiB,EAAE,eAAe,CAAC,CAAC"}
@@ -0,0 +1,178 @@
1
+ import { createLogger } from '@aztec/foundation/log';
2
+ import { getEpochAtSlot, getSlotRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
3
+ import { CheckpointProver } from './job/checkpoint-prover.js';
4
+ /**
5
+ * Prover-node-wide registry of `CheckpointProver` instances, content-addressed by
6
+ * `(checkpoint number, slot, checkpoint archive root)`.
7
+ *
8
+ * The store survives every epoch / session boundary. A prover lives from its first
9
+ * `addOrUpdate` call until either:
10
+ * - its checkpoint is pruned by an L1 reorg (`cancelAndRemoveAboveBlock`), or
11
+ * - its epoch's proof-submission window has closed (`reapExpired`), so the proof could no
12
+ * longer be accepted on L1 even if produced.
13
+ *
14
+ * A prover's sub-tree work forks world-state per block and does not survive a prune of a base
15
+ * block, so there is nothing to preserve across a reorg: a pruned prover is cancelled and
16
+ * dropped, and a re-add (even of identical content) constructs a fresh prover.
17
+ */ export class CheckpointStore {
18
+ l2BlockSource;
19
+ proverDeps;
20
+ proverFactoryFn;
21
+ provers;
22
+ /**
23
+ * Teardowns of provers already removed from `provers` (by prune or reap), awaited on `stop()`.
24
+ * Keyed by a monotonic id rather than the prover's content id: a prune-then-re-add can leave two
25
+ * teardowns for the same content id in flight at once, which a content-id key would clobber.
26
+ */ pendingTeardowns;
27
+ nextTeardownId;
28
+ /** Test-only hooks injected into every prover this store constructs. */ testHooks;
29
+ log;
30
+ constructor(l2BlockSource, proverDeps, bindings, proverFactoryFn = (args, deps)=>new CheckpointProver(args, deps)){
31
+ this.l2BlockSource = l2BlockSource;
32
+ this.proverDeps = proverDeps;
33
+ this.proverFactoryFn = proverFactoryFn;
34
+ this.provers = new Map();
35
+ this.pendingTeardowns = new Map();
36
+ this.nextTeardownId = 0;
37
+ this.testHooks = {};
38
+ this.log = createLogger('prover-node:checkpoint-store', bindings);
39
+ }
40
+ start() {
41
+ return Promise.resolve();
42
+ }
43
+ async stop() {
44
+ // Cancel every live prover, then await both their teardown and any still in flight for provers
45
+ // already removed by a prune or reap.
46
+ const provers = Array.from(this.provers.values());
47
+ this.provers.clear();
48
+ for (const prover of provers){
49
+ prover.cancel();
50
+ }
51
+ await Promise.allSettled([
52
+ ...provers.map((p)=>p.whenDone()),
53
+ ...this.pendingTeardowns.values()
54
+ ]);
55
+ }
56
+ /**
57
+ * Tracks the teardown of a prover just removed from the store so `stop()` can await it. The entry
58
+ * removes itself once teardown settles, so the map stays bounded by the number in flight.
59
+ */ trackTeardown(prover) {
60
+ const id = this.nextTeardownId++;
61
+ const done = prover.whenDone();
62
+ this.pendingTeardowns.set(id, done);
63
+ void done.finally(()=>this.pendingTeardowns.delete(id));
64
+ }
65
+ /**
66
+ * Registers a checkpoint with the store. If a prover already exists for the
67
+ * `(number, slot, archive root)` content key it is reused (an at-least-once re-registration of
68
+ * still-canonical content); otherwise a new prover is constructed.
69
+ */ async addOrUpdate(checkpoint, data) {
70
+ const l1Constants = await this.l2BlockSource.getL1Constants();
71
+ const epochNumber = getEpochAtSlot(checkpoint.header.slotNumber, l1Constants);
72
+ const id = CheckpointProver.idFor(checkpoint);
73
+ const existing = this.provers.get(id);
74
+ if (existing) {
75
+ return existing;
76
+ }
77
+ // At most one canonical checkpoint per slot. A different checkpoint at the same slot means the
78
+ // caller forgot to prune the old chain before adding the replacement — surface it rather than
79
+ // silently creating a parallel canonical chain. A pruned checkpoint has already been removed,
80
+ // so every prover still in the store is canonical.
81
+ for (const prover of this.provers.values()){
82
+ if (prover.slotNumber === checkpoint.header.slotNumber) {
83
+ throw new Error(`Cannot add checkpoint ${checkpoint.number} (archive ${checkpoint.archive.root}) at slot ${checkpoint.header.slotNumber}: ` + `a different checkpoint already occupies this slot. Prune it first.`);
84
+ }
85
+ }
86
+ const prover = this.proverFactoryFn({
87
+ ...data,
88
+ checkpoint,
89
+ epochNumber
90
+ }, {
91
+ ...this.proverDeps,
92
+ checkpointProveOverride: this.testHooks.checkpointProveOverride,
93
+ log: this.log
94
+ });
95
+ this.provers.set(id, prover);
96
+ return prover;
97
+ }
98
+ /**
99
+ * Installs test-only hooks applied to every prover constructed from now on. Used by the e2e harness to
100
+ * force a checkpoint sub-tree failure without monkey-patching the prover factory.
101
+ */ setTestHooks(hooks) {
102
+ this.testHooks = hooks;
103
+ }
104
+ /**
105
+ * Cancels and removes every prover that holds a block above the prune target. A checkpoint is orphaned by a prune to
106
+ * block `targetBlockNumber` iff its last block sits above the target — including a checkpoint whose range straddles
107
+ * the target (partially orphaned), which block-range marking catches without boundary ambiguity. Keying off the
108
+ * surviving block number (rather than a checkpoint number) is correct even when the source has already
109
+ * re-checkpointed past the divergence: the prune event reports the highest surviving block, which by construction
110
+ * survives on the source, whereas the source's current checkpointed tip can sit above the prune target.
111
+ *
112
+ * The prover's in-flight sub-tree work forks world-state per block and faults once its base block is pruned, so it
113
+ * cannot be reused; it is cancelled (aborting the fork reads) and dropped. A subsequent re-add constructs a fresh
114
+ * prover. Returns the removed provers.
115
+ */ cancelAndRemoveAboveBlock(targetBlockNumber) {
116
+ const affected = [];
117
+ for (const [id, prover] of Array.from(this.provers.entries())){
118
+ const lastBlockNumber = prover.checkpoint.blocks.at(-1).number;
119
+ if (lastBlockNumber > targetBlockNumber) {
120
+ prover.cancel();
121
+ this.trackTeardown(prover);
122
+ this.provers.delete(id);
123
+ affected.push(prover);
124
+ }
125
+ }
126
+ return affected;
127
+ }
128
+ /**
129
+ * Drops provers whose epoch is at or below the supplied expired epoch. Once an epoch's
130
+ * proof-submission window has closed, its proof can no longer be accepted on L1, so the
131
+ * prover is no longer needed.
132
+ */ reapExpired(expiredEpoch) {
133
+ const reaped = [];
134
+ for (const [id, prover] of Array.from(this.provers.entries())){
135
+ if (prover.epochNumber <= expiredEpoch) {
136
+ reaped.push({
137
+ id,
138
+ checkpointNumber: prover.checkpoint.number,
139
+ epochNumber: prover.epochNumber
140
+ });
141
+ prover.cancel({
142
+ routine: true
143
+ });
144
+ this.trackTeardown(prover);
145
+ this.provers.delete(id);
146
+ }
147
+ }
148
+ if (reaped.length > 0) {
149
+ this.log.info(`Reaped ${reaped.length} expired CheckpointProver(s) for expiredEpoch ${expiredEpoch}`, {
150
+ expiredEpoch,
151
+ reapedCount: reaped.length,
152
+ reaped
153
+ });
154
+ }
155
+ }
156
+ /** Returns the prover with the supplied id, or undefined. */ get(id) {
157
+ return this.provers.get(id);
158
+ }
159
+ /** Returns the prover for the supplied checkpoint (by its content-addressed id), or undefined. */ getByCheckpoint(checkpoint) {
160
+ return this.provers.get(CheckpointProver.idFor(checkpoint));
161
+ }
162
+ /** Every prover currently in the store, in insertion order. */ listAll() {
163
+ return Array.from(this.provers.values());
164
+ }
165
+ /** Provers in the store, sorted by checkpoint number. */ list() {
166
+ return Array.from(this.provers.values()).sort((a, b)=>a.checkpoint.number - b.checkpoint.number);
167
+ }
168
+ /**
169
+ * Provers whose slot is in the supplied epoch's slot range, sorted by checkpoint number.
170
+ */ async listForEpoch(epoch) {
171
+ const l1Constants = await this.l2BlockSource.getL1Constants();
172
+ const [fromSlot, toSlot] = getSlotRangeForEpoch(epoch, l1Constants);
173
+ return this.listInSlotRange(fromSlot, toSlot);
174
+ }
175
+ /** Provers whose slot falls within `[fromSlot, toSlot]`, sorted by checkpoint number. */ listInSlotRange(fromSlot, toSlot) {
176
+ return this.list().filter((p)=>p.slotNumber >= fromSlot && p.slotNumber <= toSlot);
177
+ }
178
+ }