@aztec-labs/prover-client 6.0.0-nightly.20260829

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 (170) hide show
  1. package/README.md +1 -0
  2. package/dest/config.d.ts +17 -0
  3. package/dest/config.d.ts.map +1 -0
  4. package/dest/config.js +63 -0
  5. package/dest/index.d.ts +4 -0
  6. package/dest/index.d.ts.map +1 -0
  7. package/dest/index.js +2 -0
  8. package/dest/light/index.d.ts +2 -0
  9. package/dest/light/index.d.ts.map +1 -0
  10. package/dest/light/index.js +1 -0
  11. package/dest/light/lightweight_checkpoint_builder.d.ts +58 -0
  12. package/dest/light/lightweight_checkpoint_builder.d.ts.map +1 -0
  13. package/dest/light/lightweight_checkpoint_builder.js +243 -0
  14. package/dest/mocks/fixtures.d.ts +20 -0
  15. package/dest/mocks/fixtures.d.ts.map +1 -0
  16. package/dest/mocks/fixtures.js +96 -0
  17. package/dest/mocks/test_context.d.ts +93 -0
  18. package/dest/mocks/test_context.d.ts.map +1 -0
  19. package/dest/mocks/test_context.js +354 -0
  20. package/dest/orchestrator/block-building-helpers.d.ts +67 -0
  21. package/dest/orchestrator/block-building-helpers.d.ts.map +1 -0
  22. package/dest/orchestrator/block-building-helpers.js +274 -0
  23. package/dest/orchestrator/block-proving-state.d.ts +107 -0
  24. package/dest/orchestrator/block-proving-state.d.ts.map +1 -0
  25. package/dest/orchestrator/block-proving-state.js +339 -0
  26. package/dest/orchestrator/checkpoint-proving-state.d.ts +67 -0
  27. package/dest/orchestrator/checkpoint-proving-state.d.ts.map +1 -0
  28. package/dest/orchestrator/checkpoint-proving-state.js +175 -0
  29. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts +169 -0
  30. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.d.ts.map +1 -0
  31. package/dest/orchestrator/checkpoint-sub-tree-orchestrator.js +1047 -0
  32. package/dest/orchestrator/chonk-cache.d.ts +39 -0
  33. package/dest/orchestrator/chonk-cache.d.ts.map +1 -0
  34. package/dest/orchestrator/chonk-cache.js +80 -0
  35. package/dest/orchestrator/index.d.ts +4 -0
  36. package/dest/orchestrator/index.d.ts.map +1 -0
  37. package/dest/orchestrator/index.js +3 -0
  38. package/dest/orchestrator/orchestrator_metrics.d.ts +8 -0
  39. package/dest/orchestrator/orchestrator_metrics.d.ts.map +1 -0
  40. package/dest/orchestrator/orchestrator_metrics.js +13 -0
  41. package/dest/orchestrator/proving-scheduler.d.ts +81 -0
  42. package/dest/orchestrator/proving-scheduler.d.ts.map +1 -0
  43. package/dest/orchestrator/proving-scheduler.js +120 -0
  44. package/dest/orchestrator/top-tree-orchestrator.d.ts +89 -0
  45. package/dest/orchestrator/top-tree-orchestrator.d.ts.map +1 -0
  46. package/dest/orchestrator/top-tree-orchestrator.js +233 -0
  47. package/dest/orchestrator/top-tree-proving-state.d.ts +61 -0
  48. package/dest/orchestrator/top-tree-proving-state.d.ts.map +1 -0
  49. package/dest/orchestrator/top-tree-proving-state.js +185 -0
  50. package/dest/orchestrator/tx-proving-state.d.ts +37 -0
  51. package/dest/orchestrator/tx-proving-state.d.ts.map +1 -0
  52. package/dest/orchestrator/tx-proving-state.js +77 -0
  53. package/dest/prover-client/factory.d.ts +6 -0
  54. package/dest/prover-client/factory.d.ts.map +1 -0
  55. package/dest/prover-client/factory.js +5 -0
  56. package/dest/prover-client/index.d.ts +3 -0
  57. package/dest/prover-client/index.d.ts.map +1 -0
  58. package/dest/prover-client/index.js +2 -0
  59. package/dest/prover-client/prover-client.d.ts +99 -0
  60. package/dest/prover-client/prover-client.d.ts.map +1 -0
  61. package/dest/prover-client/prover-client.js +163 -0
  62. package/dest/proving_broker/broker_prover_facade.d.ts +52 -0
  63. package/dest/proving_broker/broker_prover_facade.d.ts.map +1 -0
  64. package/dest/proving_broker/broker_prover_facade.js +360 -0
  65. package/dest/proving_broker/config.d.ts +40 -0
  66. package/dest/proving_broker/config.d.ts.map +1 -0
  67. package/dest/proving_broker/config.js +138 -0
  68. package/dest/proving_broker/factory.d.ts +5 -0
  69. package/dest/proving_broker/factory.d.ts.map +1 -0
  70. package/dest/proving_broker/factory.js +13 -0
  71. package/dest/proving_broker/fixtures.d.ts +6 -0
  72. package/dest/proving_broker/fixtures.d.ts.map +1 -0
  73. package/dest/proving_broker/fixtures.js +13 -0
  74. package/dest/proving_broker/index.d.ts +11 -0
  75. package/dest/proving_broker/index.d.ts.map +1 -0
  76. package/dest/proving_broker/index.js +10 -0
  77. package/dest/proving_broker/proof_store/factory.d.ts +3 -0
  78. package/dest/proving_broker/proof_store/factory.d.ts.map +1 -0
  79. package/dest/proving_broker/proof_store/factory.js +13 -0
  80. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts +18 -0
  81. package/dest/proving_broker/proof_store/file_store_proof_store.d.ts.map +1 -0
  82. package/dest/proving_broker/proof_store/file_store_proof_store.js +60 -0
  83. package/dest/proving_broker/proof_store/index.d.ts +5 -0
  84. package/dest/proving_broker/proof_store/index.d.ts.map +1 -0
  85. package/dest/proving_broker/proof_store/index.js +4 -0
  86. package/dest/proving_broker/proof_store/inline_proof_store.d.ts +15 -0
  87. package/dest/proving_broker/proof_store/inline_proof_store.d.ts.map +1 -0
  88. package/dest/proving_broker/proof_store/inline_proof_store.js +41 -0
  89. package/dest/proving_broker/proof_store/proof_store.d.ts +36 -0
  90. package/dest/proving_broker/proof_store/proof_store.d.ts.map +1 -0
  91. package/dest/proving_broker/proof_store/proof_store.js +3 -0
  92. package/dest/proving_broker/proving_agent.d.ts +42 -0
  93. package/dest/proving_broker/proving_agent.d.ts.map +1 -0
  94. package/dest/proving_broker/proving_agent.js +155 -0
  95. package/dest/proving_broker/proving_broker.d.ts +77 -0
  96. package/dest/proving_broker/proving_broker.d.ts.map +1 -0
  97. package/dest/proving_broker/proving_broker.js +780 -0
  98. package/dest/proving_broker/proving_broker_database/memory.d.ts +20 -0
  99. package/dest/proving_broker/proving_broker_database/memory.d.ts.map +1 -0
  100. package/dest/proving_broker/proving_broker_database/memory.js +67 -0
  101. package/dest/proving_broker/proving_broker_database/persisted.d.ts +40 -0
  102. package/dest/proving_broker/proving_broker_database/persisted.d.ts.map +1 -0
  103. package/dest/proving_broker/proving_broker_database/persisted.js +623 -0
  104. package/dest/proving_broker/proving_broker_database.d.ts +66 -0
  105. package/dest/proving_broker/proving_broker_database.d.ts.map +1 -0
  106. package/dest/proving_broker/proving_broker_database.js +3 -0
  107. package/dest/proving_broker/proving_broker_instrumentation.d.ts +31 -0
  108. package/dest/proving_broker/proving_broker_instrumentation.d.ts.map +1 -0
  109. package/dest/proving_broker/proving_broker_instrumentation.js +97 -0
  110. package/dest/proving_broker/proving_job_controller.d.ts +34 -0
  111. package/dest/proving_broker/proving_job_controller.d.ts.map +1 -0
  112. package/dest/proving_broker/proving_job_controller.js +184 -0
  113. package/dest/proving_broker/rpc.d.ts +38 -0
  114. package/dest/proving_broker/rpc.d.ts.map +1 -0
  115. package/dest/proving_broker/rpc.js +138 -0
  116. package/dest/test/epoch_settlement.d.ts +36 -0
  117. package/dest/test/epoch_settlement.d.ts.map +1 -0
  118. package/dest/test/epoch_settlement.js +52 -0
  119. package/dest/test/index.d.ts +2 -0
  120. package/dest/test/index.d.ts.map +1 -0
  121. package/dest/test/index.js +1 -0
  122. package/dest/test/mock_proof_store.d.ts +9 -0
  123. package/dest/test/mock_proof_store.d.ts.map +1 -0
  124. package/dest/test/mock_proof_store.js +10 -0
  125. package/dest/test/mock_prover.d.ts +38 -0
  126. package/dest/test/mock_prover.d.ts.map +1 -0
  127. package/dest/test/mock_prover.js +91 -0
  128. package/package.json +113 -0
  129. package/src/config.ts +87 -0
  130. package/src/index.ts +4 -0
  131. package/src/light/index.ts +1 -0
  132. package/src/light/lightweight_checkpoint_builder.ts +342 -0
  133. package/src/mocks/fixtures.ts +120 -0
  134. package/src/mocks/test_context.ts +477 -0
  135. package/src/orchestrator/block-building-helpers.ts +486 -0
  136. package/src/orchestrator/block-proving-state.ts +457 -0
  137. package/src/orchestrator/checkpoint-proving-state.ts +247 -0
  138. package/src/orchestrator/checkpoint-sub-tree-orchestrator.ts +1010 -0
  139. package/src/orchestrator/chonk-cache.ts +99 -0
  140. package/src/orchestrator/index.ts +12 -0
  141. package/src/orchestrator/orchestrator_metrics.ts +18 -0
  142. package/src/orchestrator/proving-scheduler.ts +160 -0
  143. package/src/orchestrator/top-tree-orchestrator.ts +394 -0
  144. package/src/orchestrator/top-tree-proving-state.ts +219 -0
  145. package/src/orchestrator/tx-proving-state.ts +121 -0
  146. package/src/prover-client/factory.ts +18 -0
  147. package/src/prover-client/index.ts +2 -0
  148. package/src/prover-client/prover-client.ts +286 -0
  149. package/src/proving_broker/broker_prover_facade.ts +626 -0
  150. package/src/proving_broker/config.ts +178 -0
  151. package/src/proving_broker/factory.ts +19 -0
  152. package/src/proving_broker/fixtures.ts +20 -0
  153. package/src/proving_broker/index.ts +10 -0
  154. package/src/proving_broker/proof_store/factory.ts +20 -0
  155. package/src/proving_broker/proof_store/file_store_proof_store.ts +78 -0
  156. package/src/proving_broker/proof_store/index.ts +4 -0
  157. package/src/proving_broker/proof_store/inline_proof_store.ts +63 -0
  158. package/src/proving_broker/proof_store/proof_store.ts +54 -0
  159. package/src/proving_broker/proving_agent.ts +210 -0
  160. package/src/proving_broker/proving_broker.ts +888 -0
  161. package/src/proving_broker/proving_broker_database/memory.ts +78 -0
  162. package/src/proving_broker/proving_broker_database/persisted.ts +296 -0
  163. package/src/proving_broker/proving_broker_database.ts +75 -0
  164. package/src/proving_broker/proving_broker_instrumentation.ts +133 -0
  165. package/src/proving_broker/proving_job_controller.ts +199 -0
  166. package/src/proving_broker/rpc.ts +131 -0
  167. package/src/test/epoch_settlement.ts +82 -0
  168. package/src/test/index.ts +1 -0
  169. package/src/test/mock_proof_store.ts +14 -0
  170. package/src/test/mock_prover.ts +304 -0
@@ -0,0 +1,1047 @@
1
+ function applyDecs2203RFactory() {
2
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
3
+ return function addInitializer(initializer) {
4
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
5
+ assertCallable(initializer, "An initializer");
6
+ initializers.push(initializer);
7
+ };
8
+ }
9
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
10
+ var kindStr;
11
+ switch(kind){
12
+ case 1:
13
+ kindStr = "accessor";
14
+ break;
15
+ case 2:
16
+ kindStr = "method";
17
+ break;
18
+ case 3:
19
+ kindStr = "getter";
20
+ break;
21
+ case 4:
22
+ kindStr = "setter";
23
+ break;
24
+ default:
25
+ kindStr = "field";
26
+ }
27
+ var ctx = {
28
+ kind: kindStr,
29
+ name: isPrivate ? "#" + name : name,
30
+ static: isStatic,
31
+ private: isPrivate,
32
+ metadata: metadata
33
+ };
34
+ var decoratorFinishedRef = {
35
+ v: false
36
+ };
37
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
38
+ var get, set;
39
+ if (kind === 0) {
40
+ if (isPrivate) {
41
+ get = desc.get;
42
+ set = desc.set;
43
+ } else {
44
+ get = function() {
45
+ return this[name];
46
+ };
47
+ set = function(v) {
48
+ this[name] = v;
49
+ };
50
+ }
51
+ } else if (kind === 2) {
52
+ get = function() {
53
+ return desc.value;
54
+ };
55
+ } else {
56
+ if (kind === 1 || kind === 3) {
57
+ get = function() {
58
+ return desc.get.call(this);
59
+ };
60
+ }
61
+ if (kind === 1 || kind === 4) {
62
+ set = function(v) {
63
+ desc.set.call(this, v);
64
+ };
65
+ }
66
+ }
67
+ ctx.access = get && set ? {
68
+ get: get,
69
+ set: set
70
+ } : get ? {
71
+ get: get
72
+ } : {
73
+ set: set
74
+ };
75
+ try {
76
+ return dec(value, ctx);
77
+ } finally{
78
+ decoratorFinishedRef.v = true;
79
+ }
80
+ }
81
+ function assertNotFinished(decoratorFinishedRef, fnName) {
82
+ if (decoratorFinishedRef.v) {
83
+ throw new Error("attempted to call " + fnName + " after decoration was finished");
84
+ }
85
+ }
86
+ function assertCallable(fn, hint) {
87
+ if (typeof fn !== "function") {
88
+ throw new TypeError(hint + " must be a function");
89
+ }
90
+ }
91
+ function assertValidReturnValue(kind, value) {
92
+ var type = typeof value;
93
+ if (kind === 1) {
94
+ if (type !== "object" || value === null) {
95
+ throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
96
+ }
97
+ if (value.get !== undefined) {
98
+ assertCallable(value.get, "accessor.get");
99
+ }
100
+ if (value.set !== undefined) {
101
+ assertCallable(value.set, "accessor.set");
102
+ }
103
+ if (value.init !== undefined) {
104
+ assertCallable(value.init, "accessor.init");
105
+ }
106
+ } else if (type !== "function") {
107
+ var hint;
108
+ if (kind === 0) {
109
+ hint = "field";
110
+ } else if (kind === 10) {
111
+ hint = "class";
112
+ } else {
113
+ hint = "method";
114
+ }
115
+ throw new TypeError(hint + " decorators must return a function or void 0");
116
+ }
117
+ }
118
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
119
+ var decs = decInfo[0];
120
+ var desc, init, value;
121
+ if (isPrivate) {
122
+ if (kind === 0 || kind === 1) {
123
+ desc = {
124
+ get: decInfo[3],
125
+ set: decInfo[4]
126
+ };
127
+ } else if (kind === 3) {
128
+ desc = {
129
+ get: decInfo[3]
130
+ };
131
+ } else if (kind === 4) {
132
+ desc = {
133
+ set: decInfo[3]
134
+ };
135
+ } else {
136
+ desc = {
137
+ value: decInfo[3]
138
+ };
139
+ }
140
+ } else if (kind !== 0) {
141
+ desc = Object.getOwnPropertyDescriptor(base, name);
142
+ }
143
+ if (kind === 1) {
144
+ value = {
145
+ get: desc.get,
146
+ set: desc.set
147
+ };
148
+ } else if (kind === 2) {
149
+ value = desc.value;
150
+ } else if (kind === 3) {
151
+ value = desc.get;
152
+ } else if (kind === 4) {
153
+ value = desc.set;
154
+ }
155
+ var newValue, get, set;
156
+ if (typeof decs === "function") {
157
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
158
+ if (newValue !== void 0) {
159
+ assertValidReturnValue(kind, newValue);
160
+ if (kind === 0) {
161
+ init = newValue;
162
+ } else if (kind === 1) {
163
+ init = newValue.init;
164
+ get = newValue.get || value.get;
165
+ set = newValue.set || value.set;
166
+ value = {
167
+ get: get,
168
+ set: set
169
+ };
170
+ } else {
171
+ value = newValue;
172
+ }
173
+ }
174
+ } else {
175
+ for(var i = decs.length - 1; i >= 0; i--){
176
+ var dec = decs[i];
177
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
178
+ if (newValue !== void 0) {
179
+ assertValidReturnValue(kind, newValue);
180
+ var newInit;
181
+ if (kind === 0) {
182
+ newInit = newValue;
183
+ } else if (kind === 1) {
184
+ newInit = newValue.init;
185
+ get = newValue.get || value.get;
186
+ set = newValue.set || value.set;
187
+ value = {
188
+ get: get,
189
+ set: set
190
+ };
191
+ } else {
192
+ value = newValue;
193
+ }
194
+ if (newInit !== void 0) {
195
+ if (init === void 0) {
196
+ init = newInit;
197
+ } else if (typeof init === "function") {
198
+ init = [
199
+ init,
200
+ newInit
201
+ ];
202
+ } else {
203
+ init.push(newInit);
204
+ }
205
+ }
206
+ }
207
+ }
208
+ }
209
+ if (kind === 0 || kind === 1) {
210
+ if (init === void 0) {
211
+ init = function(instance, init) {
212
+ return init;
213
+ };
214
+ } else if (typeof init !== "function") {
215
+ var ownInitializers = init;
216
+ init = function(instance, init) {
217
+ var value = init;
218
+ for(var i = 0; i < ownInitializers.length; i++){
219
+ value = ownInitializers[i].call(instance, value);
220
+ }
221
+ return value;
222
+ };
223
+ } else {
224
+ var originalInitializer = init;
225
+ init = function(instance, init) {
226
+ return originalInitializer.call(instance, init);
227
+ };
228
+ }
229
+ ret.push(init);
230
+ }
231
+ if (kind !== 0) {
232
+ if (kind === 1) {
233
+ desc.get = value.get;
234
+ desc.set = value.set;
235
+ } else if (kind === 2) {
236
+ desc.value = value;
237
+ } else if (kind === 3) {
238
+ desc.get = value;
239
+ } else if (kind === 4) {
240
+ desc.set = value;
241
+ }
242
+ if (isPrivate) {
243
+ if (kind === 1) {
244
+ ret.push(function(instance, args) {
245
+ return value.get.call(instance, args);
246
+ });
247
+ ret.push(function(instance, args) {
248
+ return value.set.call(instance, args);
249
+ });
250
+ } else if (kind === 2) {
251
+ ret.push(value);
252
+ } else {
253
+ ret.push(function(instance, args) {
254
+ return value.call(instance, args);
255
+ });
256
+ }
257
+ } else {
258
+ Object.defineProperty(base, name, desc);
259
+ }
260
+ }
261
+ }
262
+ function applyMemberDecs(Class, decInfos, metadata) {
263
+ var ret = [];
264
+ var protoInitializers;
265
+ var staticInitializers;
266
+ var existingProtoNonFields = new Map();
267
+ var existingStaticNonFields = new Map();
268
+ for(var i = 0; i < decInfos.length; i++){
269
+ var decInfo = decInfos[i];
270
+ if (!Array.isArray(decInfo)) continue;
271
+ var kind = decInfo[1];
272
+ var name = decInfo[2];
273
+ var isPrivate = decInfo.length > 3;
274
+ var isStatic = kind >= 5;
275
+ var base;
276
+ var initializers;
277
+ if (isStatic) {
278
+ base = Class;
279
+ kind = kind - 5;
280
+ staticInitializers = staticInitializers || [];
281
+ initializers = staticInitializers;
282
+ } else {
283
+ base = Class.prototype;
284
+ protoInitializers = protoInitializers || [];
285
+ initializers = protoInitializers;
286
+ }
287
+ if (kind !== 0 && !isPrivate) {
288
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
289
+ var existingKind = existingNonFields.get(name) || 0;
290
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
291
+ throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
292
+ } else if (!existingKind && kind > 2) {
293
+ existingNonFields.set(name, kind);
294
+ } else {
295
+ existingNonFields.set(name, true);
296
+ }
297
+ }
298
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
299
+ }
300
+ pushInitializers(ret, protoInitializers);
301
+ pushInitializers(ret, staticInitializers);
302
+ return ret;
303
+ }
304
+ function pushInitializers(ret, initializers) {
305
+ if (initializers) {
306
+ ret.push(function(instance) {
307
+ for(var i = 0; i < initializers.length; i++){
308
+ initializers[i].call(instance);
309
+ }
310
+ return instance;
311
+ });
312
+ }
313
+ }
314
+ function applyClassDecs(targetClass, classDecs, metadata) {
315
+ if (classDecs.length > 0) {
316
+ var initializers = [];
317
+ var newClass = targetClass;
318
+ var name = targetClass.name;
319
+ for(var i = classDecs.length - 1; i >= 0; i--){
320
+ var decoratorFinishedRef = {
321
+ v: false
322
+ };
323
+ try {
324
+ var nextNewClass = classDecs[i](newClass, {
325
+ kind: "class",
326
+ name: name,
327
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
328
+ metadata
329
+ });
330
+ } finally{
331
+ decoratorFinishedRef.v = true;
332
+ }
333
+ if (nextNewClass !== undefined) {
334
+ assertValidReturnValue(10, nextNewClass);
335
+ newClass = nextNewClass;
336
+ }
337
+ }
338
+ return [
339
+ defineMetadata(newClass, metadata),
340
+ function() {
341
+ for(var i = 0; i < initializers.length; i++){
342
+ initializers[i].call(newClass);
343
+ }
344
+ }
345
+ ];
346
+ }
347
+ }
348
+ function defineMetadata(Class, metadata) {
349
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
350
+ configurable: true,
351
+ enumerable: true,
352
+ value: metadata
353
+ });
354
+ }
355
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
356
+ if (parentClass !== void 0) {
357
+ var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
358
+ }
359
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
360
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
361
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
362
+ return {
363
+ e: e,
364
+ get c () {
365
+ return applyClassDecs(targetClass, classDecs, metadata);
366
+ }
367
+ };
368
+ };
369
+ }
370
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
372
+ }
373
+ var _dec, _dec1, _dec2, _dec3, _initProto;
374
+ import { L1_TO_L2_MSG_TREE_HEIGHT } from '@aztec-labs/constants';
375
+ import { BlockNumber } from '@aztec-labs/foundation/branded-types';
376
+ import { AbortError } from '@aztec-labs/foundation/error';
377
+ import { promiseWithResolvers } from '@aztec-labs/foundation/promise';
378
+ import { assertLength } from '@aztec-labs/foundation/serialize';
379
+ import { appendL1ToL2MessagesToTree } from '@aztec-labs/stdlib/messaging';
380
+ import { PrivateTxBaseRollupPrivateInputs } from '@aztec-labs/stdlib/rollup';
381
+ import { MerkleTreeId } from '@aztec-labs/stdlib/trees';
382
+ import { Attributes, getTelemetryClient, trackSpan, wrapCallbackInSpan } from '@aztec-labs/telemetry-client';
383
+ import { inspect } from 'util';
384
+ import { buildHeaderFromCircuitOutputs, getFrontierSiblingPath, getLastSiblingPath, getPublicChonkVerifierPrivateInputsFromTx, getRootTreeSiblingPath, getTreeSnapshot, insertSideEffectsAndBuildBaseRollupHints, validatePartialState, validateTx } from './block-building-helpers.js';
385
+ import { CheckpointProvingState } from './checkpoint-proving-state.js';
386
+ import { ProvingOrchestratorMetrics } from './orchestrator_metrics.js';
387
+ import { ProvingScheduler } from './proving-scheduler.js';
388
+ import { TxProvingState } from './tx-proving-state.js';
389
+ _dec = trackSpan('CheckpointSubTreeOrchestrator.startNewBlock', (blockNumber)=>({
390
+ [Attributes.BLOCK_NUMBER]: blockNumber
391
+ })), _dec1 = trackSpan('CheckpointSubTreeOrchestrator.addTxs', (txs)=>({
392
+ [Attributes.BLOCK_TXS_COUNT]: txs.length
393
+ })), _dec2 = trackSpan('CheckpointSubTreeOrchestrator.setBlockCompleted', (blockNumber)=>({
394
+ [Attributes.BLOCK_NUMBER]: blockNumber
395
+ })), _dec3 = trackSpan('CheckpointSubTreeOrchestrator.prepareBaseRollupInputs', (tx)=>({
396
+ [Attributes.TX_HASH]: tx.hash.toString()
397
+ }));
398
+ /**
399
+ * Orchestrates block-level proving for a single checkpoint, stopping at the boundary
400
+ * where checkpoint root rollup would otherwise begin. Used by the per-checkpoint
401
+ * `CheckpointProver` in production; the top-tree orchestrator then composes the
402
+ * sub-tree's block proofs into the epoch proof.
403
+ *
404
+ * Wiring: a single-checkpoint mini-proving session is owned by the constructor. The
405
+ * canonical way to obtain a fully-started sub-tree is the `start` static factory,
406
+ * which also drives the single internal `startCheckpoint` call. The sub-tree never
407
+ * escalates past the checkpoint root boundary; `getSubTreeResult()` resolves once
408
+ * every block-level proof in the checkpoint's tree is ready.
409
+ */ export class CheckpointSubTreeOrchestrator extends ProvingScheduler {
410
+ dbProvider;
411
+ prover;
412
+ proverId;
413
+ chonkCache;
414
+ epochNumber;
415
+ cancelJobsOnStop;
416
+ static{
417
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
418
+ [
419
+ _dec,
420
+ 2,
421
+ "startNewBlock"
422
+ ],
423
+ [
424
+ _dec1,
425
+ 2,
426
+ "addTxs"
427
+ ],
428
+ [
429
+ _dec2,
430
+ 2,
431
+ "setBlockCompleted"
432
+ ],
433
+ [
434
+ _dec3,
435
+ 2,
436
+ "prepareBaseRollupInputs"
437
+ ]
438
+ ], []));
439
+ }
440
+ /** The single checkpoint proving state this sub-tree owns. Allocated in the `start` factory. */ provingState;
441
+ subTreeResult;
442
+ metrics;
443
+ dbs;
444
+ constructor(dbProvider, prover, proverId, /**
445
+ * Shared chonk-verifier proof cache. Every chonk-verifier proof started by this
446
+ * sub-tree lives on the cache and survives the sub-tree's cancellation, so a tx
447
+ * whose original checkpoint is reorged out and re-appears in a replacement
448
+ * checkpoint reuses the cached proof.
449
+ */ chonkCache, /** The epoch this sub-tree proves into. */ epochNumber, cancelJobsOnStop = false, deferredJobQueue, telemetryClient = getTelemetryClient(), bindings){
450
+ super(deferredJobQueue, 'prover-client:checkpoint-sub-tree-orchestrator', bindings), this.dbProvider = dbProvider, this.prover = prover, this.proverId = proverId, this.chonkCache = chonkCache, this.epochNumber = epochNumber, this.cancelJobsOnStop = cancelJobsOnStop, this.provingState = (_initProto(this), undefined), this.dbs = new Map(), this.cancelled = false;
451
+ this.metrics = new ProvingOrchestratorMetrics(telemetryClient, 'CheckpointSubTreeOrchestrator');
452
+ this.subTreeResult = promiseWithResolvers();
453
+ // Mark the rejection branch as observed so a `cancel()` or proving failure does not
454
+ // surface an unhandled rejection when no consumer awaits getSubTreeResult().
455
+ this.subTreeResult.promise.catch(()=>{});
456
+ }
457
+ /** Tracks whether `cancel()` has been called; flows into the checkpoint state's isAlive hook. */ cancelled;
458
+ get tracer() {
459
+ return this.metrics.tracer;
460
+ }
461
+ getProverId() {
462
+ return this.proverId;
463
+ }
464
+ getNumActiveForks() {
465
+ return this.dbs.size;
466
+ }
467
+ /** Returns a promise that resolves when block-level proving completes for the checkpoint. */ getSubTreeResult() {
468
+ return this.subTreeResult.promise;
469
+ }
470
+ /**
471
+ * Returns the archive sibling path captured at the internal checkpoint start.
472
+ * Available synchronously once `start` has resolved, before block-level proving
473
+ * completes. The top-tree consumer uses this to assemble checkpoint root rollup hints
474
+ * up-front so checkpoint root proofs can pipeline against in-flight sub-tree proving.
475
+ */ getPreviousArchiveSiblingPath() {
476
+ if (!this.provingState) {
477
+ throw new Error('Checkpoint not started; call CheckpointSubTreeOrchestrator.start first.');
478
+ }
479
+ return this.provingState.getLastArchiveSiblingPath();
480
+ }
481
+ /**
482
+ * Constructs and starts a sub-tree for a single checkpoint. The returned sub-tree
483
+ * has had its single internal checkpoint state allocated; callers proceed directly
484
+ * to per-block `startNewBlock` / `addTxs` / `setBlockCompleted`.
485
+ *
486
+ * If the internal start rejects, the partially-constructed sub-tree is stopped
487
+ * before the error propagates, so no broker resources leak.
488
+ */ static async start(dbProvider, prover, proverId, chonkCache, epochNumber, cancelJobsOnStop, deferredJobQueue, checkpointConstants, l1ToL2Messages, startInboxRollingHash, totalNumBlocks, headerOfLastBlockInPreviousCheckpoint, telemetryClient = getTelemetryClient(), bindings) {
489
+ const subTree = new CheckpointSubTreeOrchestrator(dbProvider, prover, proverId, chonkCache, epochNumber, cancelJobsOnStop, deferredJobQueue, telemetryClient, bindings);
490
+ try {
491
+ await subTree.startCheckpoint(checkpointConstants, l1ToL2Messages, startInboxRollingHash, totalNumBlocks, headerOfLastBlockInPreviousCheckpoint);
492
+ return subTree;
493
+ } catch (err) {
494
+ await subTree.stop().catch(()=>{});
495
+ throw err;
496
+ }
497
+ }
498
+ /**
499
+ * Kickstart chonk-verifier circuits via the shared `ChonkCache`. The cache owns the
500
+ * broker job lifecycle, so the proof survives this sub-tree's `cancel()` — a tx that
501
+ * ends up in a replacement checkpoint after a reorg can pick the cached promise up
502
+ * and skip re-proving.
503
+ */ startChonkVerifierCircuits(txs) {
504
+ if (!this.provingState?.verifyState()) {
505
+ return Promise.reject(new Error('Sub-tree proving state is not active.'));
506
+ }
507
+ const publicTxs = txs.filter((tx)=>tx.data.forPublic);
508
+ for (const tx of publicTxs){
509
+ const txHash = tx.getTxHash().toString();
510
+ const inputs = getPublicChonkVerifierPrivateInputsFromTx(tx, this.getProverId().toField());
511
+ // Fire and forget — getOrEnqueueChonkVerifier later picks up the cached promise
512
+ // when the tx is processed inside its block.
513
+ void this.chonkCache.getOrCompute(txHash, (signal)=>this.prover.getPublicChonkVerifierProof(inputs, signal, this.epochNumber));
514
+ }
515
+ return Promise.resolve();
516
+ }
517
+ // ---------------- per-block driving (called by the per-checkpoint CheckpointProver) ----------------
518
+ /**
519
+ * Starts off a new block.
520
+ * @param blockNumber - The block number
521
+ * @param timestamp - The timestamp of the block. Required for empty blocks to construct private inputs.
522
+ * @param totalNumTxs - The total number of txs in the block.
523
+ */ async startNewBlock(blockNumber, timestamp, totalNumTxs, l1ToL2Messages) {
524
+ if (!this.provingState) {
525
+ throw new Error('Empty proving state. The checkpoint sub-tree has not been started.');
526
+ }
527
+ if (!this.provingState.isAcceptingBlocks()) {
528
+ throw new Error(`Checkpoint not accepting further blocks.`);
529
+ }
530
+ const constants = this.provingState.constants;
531
+ this.logger.info(`Starting block ${blockNumber} for slot ${constants.slotNumber}.`);
532
+ // Fork the db only when it's not already set. The db for the first block is set in startCheckpoint.
533
+ if (!this.dbs.has(blockNumber)) {
534
+ // Fork world state at the end of the immediately previous block.
535
+ const db = await this.dbProvider.fork(BlockNumber(blockNumber - 1));
536
+ this.dbs.set(blockNumber, db);
537
+ }
538
+ const db = this.getDbForBlock(blockNumber);
539
+ // Get archive snapshot and sibling path before any txs in this block lands.
540
+ const lastArchiveTreeSnapshot = await getTreeSnapshot(MerkleTreeId.ARCHIVE, db);
541
+ const lastArchiveSiblingPath = await getRootTreeSiblingPath(MerkleTreeId.ARCHIVE, db);
542
+ // The previous block's full state reference, captured before this block's message bundle is appended. Feeds the
543
+ // msgs-only block root, whose zero-tx block carries no tx constants to pin the previous state.
544
+ const previousState = await db.getStateReference();
545
+ // Streaming Inbox: insert this block's own real message slice at compact indices, capturing
546
+ // the start snapshot + full-height frontier before the append and the block's own post-bundle end snapshot after.
547
+ const startL1ToL2Snapshot = await getTreeSnapshot(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, db);
548
+ const l1ToL2FrontierHint = assertLength(await getFrontierSiblingPath(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, db), L1_TO_L2_MSG_TREE_HEIGHT);
549
+ await appendL1ToL2MessagesToTree(db, l1ToL2Messages);
550
+ const endL1ToL2Snapshot = await getTreeSnapshot(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, db);
551
+ const blockProvingState = await this.provingState.startNewBlock(blockNumber, timestamp, totalNumTxs, lastArchiveTreeSnapshot, lastArchiveSiblingPath, previousState, startL1ToL2Snapshot, endL1ToL2Snapshot, l1ToL2FrontierHint, l1ToL2Messages);
552
+ // Because `addTxs` won't be called for a block without txs, and that's where the sponge blob state is computed,
553
+ // set its end sponge blob here. This becomes the start sponge blob for the next block.
554
+ if (totalNumTxs === 0) {
555
+ const endState = await db.getStateReference();
556
+ blockProvingState.setEndState(endState);
557
+ const endSpongeBlob = blockProvingState.getStartSpongeBlob().clone();
558
+ const blockEndBlobFields = blockProvingState.getBlockEndBlobFields();
559
+ await endSpongeBlob.absorb(blockEndBlobFields);
560
+ blockProvingState.setEndSpongeBlob(endSpongeBlob);
561
+ // A block with no txs has no base or merge proof whose completion would enqueue its block root,
562
+ // and parity now gates the checkpoint root rather than the first block root, so no other callback
563
+ // fires it. Enqueue it here. This drives the empty-tx first block root, or the msgs-only block root
564
+ // for a non-first zero-tx block carrying a message bundle.
565
+ this.checkAndEnqueueBlockRootRollup(blockProvingState);
566
+ }
567
+ }
568
+ /**
569
+ * The interface to add simulated transactions to the scheduler. Called at most once per block.
570
+ * @param txs - The transactions to be proven
571
+ */ async addTxs(txs) {
572
+ if (!this.provingState) {
573
+ throw new Error(`Empty proving state. The checkpoint sub-tree has not been started.`);
574
+ }
575
+ if (!txs.length) {
576
+ // Empty block: setBlockCompleted handles this without addTxs being called. Bail to
577
+ // avoid the throw below (we cannot find the blockNumber without any txs).
578
+ this.logger.verbose(`Provided no txs to addTxs.`);
579
+ return;
580
+ }
581
+ const blockNumber = BlockNumber(txs[0].globalVariables.blockNumber);
582
+ const provingState = this.provingState.getBlockProvingStateByBlockNumber(blockNumber);
583
+ if (!provingState) {
584
+ throw new Error(`Proving state for block ${blockNumber} not found. Call startNewBlock first.`);
585
+ }
586
+ if (provingState.totalNumTxs !== txs.length) {
587
+ throw new Error(`Block ${blockNumber} should be filled with ${provingState.totalNumTxs} txs. Received ${txs.length} txs.`);
588
+ }
589
+ if (!provingState.isAcceptingTxs()) {
590
+ throw new Error(`Block ${blockNumber} has been initialized with transactions.`);
591
+ }
592
+ this.logger.info(`Adding ${txs.length} transactions to block ${blockNumber}`);
593
+ const db = this.getDbForBlock(blockNumber);
594
+ const lastArchive = provingState.lastArchiveTreeSnapshot;
595
+ const newL1ToL2MessageTreeSnapshot = provingState.newL1ToL2MessageTreeSnapshot;
596
+ const spongeBlobState = provingState.getStartSpongeBlob().clone();
597
+ for (const tx of txs){
598
+ try {
599
+ if (!provingState.verifyState()) {
600
+ throw new Error(`Invalid proving state when adding a tx`);
601
+ }
602
+ validateTx(tx);
603
+ this.logger.debug(`Received transaction: ${tx.hash}`);
604
+ const startSpongeBlob = spongeBlobState.clone();
605
+ const [hints, treeSnapshots] = await this.prepareBaseRollupInputs(tx, lastArchive, newL1ToL2MessageTreeSnapshot, startSpongeBlob, db);
606
+ if (!provingState.verifyState()) {
607
+ throw new Error(`Unable to add transaction, preparing base inputs failed`);
608
+ }
609
+ await spongeBlobState.absorb(tx.txEffect.toBlobFields());
610
+ const txProvingState = new TxProvingState(tx, hints, treeSnapshots, this.proverId.toField());
611
+ const txIndex = provingState.addNewTx(txProvingState);
612
+ if (txProvingState.requireAvmProof) {
613
+ this.getOrEnqueueChonkVerifier(provingState, txIndex);
614
+ this.logger.debug(`Enqueueing public VM for tx ${txIndex}`);
615
+ this.enqueueVM(provingState, txIndex);
616
+ } else {
617
+ this.logger.debug(`Enqueueing base rollup for private-only tx ${txIndex}`);
618
+ this.enqueueBaseRollup(provingState, txIndex);
619
+ }
620
+ } catch (err) {
621
+ throw new Error(`Error adding transaction ${tx.hash.toString()} to block ${blockNumber}: ${err.message}`, {
622
+ cause: err
623
+ });
624
+ }
625
+ }
626
+ const endState = await db.getStateReference();
627
+ provingState.setEndState(endState);
628
+ const blockEndBlobFields = provingState.getBlockEndBlobFields();
629
+ await spongeBlobState.absorb(blockEndBlobFields);
630
+ provingState.setEndSpongeBlob(spongeBlobState);
631
+ }
632
+ /**
633
+ * Marks the block as completed.
634
+ * Computes the block header and updates the archive tree.
635
+ */ async setBlockCompleted(blockNumber, expectedHeader) {
636
+ const provingState = this.provingState?.getBlockProvingStateByBlockNumber(blockNumber);
637
+ if (!provingState) {
638
+ throw new Error(`Block proving state for ${blockNumber} not found`);
639
+ }
640
+ // Abort with specific error for the block if there's one.
641
+ const error = provingState.getError();
642
+ if (error) {
643
+ throw new Error(`Block proving failed: ${error}`);
644
+ }
645
+ // Abort if the proving state is not valid due to errors occurred elsewhere.
646
+ if (!provingState.verifyState()) {
647
+ throw new Error(`Invalid proving state when completing block ${blockNumber}.`);
648
+ }
649
+ if (provingState.isAcceptingTxs()) {
650
+ throw new Error(`Block ${blockNumber} is still accepting txs. Call setBlockCompleted after all txs have been added.`);
651
+ }
652
+ // Given we've applied every change from this block, now assemble the block header:
653
+ this.logger.verbose(`Block ${blockNumber} completed. Assembling header.`);
654
+ const header = await provingState.buildBlockHeader();
655
+ if (expectedHeader && !header.equals(expectedHeader)) {
656
+ this.logger.error(`Block header mismatch: header=${header} expectedHeader=${expectedHeader}`);
657
+ throw new Error('Block header mismatch');
658
+ }
659
+ // Get db for this block and remove from map — no other code should use it after this point.
660
+ const db = this.getDbForBlock(provingState.blockNumber);
661
+ this.dbs.delete(provingState.blockNumber);
662
+ // Update the archive tree, capture the snapshot, and close the fork deterministically.
663
+ try {
664
+ this.logger.verbose(`Updating archive tree with block ${provingState.blockNumber} header ${(await header.hash()).toString()}`);
665
+ await db.updateArchive(header);
666
+ provingState.setBuiltArchive(await getTreeSnapshot(MerkleTreeId.ARCHIVE, db));
667
+ } finally{
668
+ await db.close();
669
+ }
670
+ await this.verifyBuiltBlockAgainstSyncedState(provingState);
671
+ return header;
672
+ }
673
+ // ---------------- lifecycle ----------------
674
+ /**
675
+ * Cancels any further proving. If `cancelJobsOnStop` was set, aborts all pending broker jobs
676
+ * (used on reorg). Otherwise jobs remain in the broker queue and can be reused on restart.
677
+ */ cancel() {
678
+ this.cancelled = true;
679
+ this.resetSchedulerState(this.cancelJobsOnStop);
680
+ // Reject the proving state (and hence subTreeResult) so anyone awaiting the sub-tree result
681
+ // is released rather than hanging — matching TopTreeOrchestrator.cancel().
682
+ this.provingState?.cancel();
683
+ for (const [blockNumber, db] of this.dbs.entries()){
684
+ void db.close().catch((err)=>this.logger.error(`Error closing db for block ${blockNumber}`, err));
685
+ }
686
+ this.dbs.clear();
687
+ }
688
+ cancelInternal() {
689
+ this.cancel();
690
+ }
691
+ // ---------------- private: per-checkpoint init ----------------
692
+ /**
693
+ * Internal driver for the single-checkpoint init. Allocates the world-state fork,
694
+ * inserts L1-to-L2 messages, and creates the per-checkpoint proving state with this
695
+ * sub-tree as its parent. Only called once, from the `start` factory.
696
+ */ async startCheckpoint(constants, l1ToL2Messages, startInboxRollingHash, totalNumBlocks, headerOfLastBlockInPreviousCheckpoint) {
697
+ if (this.provingState) {
698
+ throw new Error('Checkpoint sub-tree already started.');
699
+ }
700
+ // Fork world state at the end of the immediately previous block.
701
+ const lastBlockNumber = headerOfLastBlockInPreviousCheckpoint.globalVariables.blockNumber;
702
+ const db = await this.dbProvider.fork(lastBlockNumber);
703
+ const firstBlockNumber = BlockNumber(lastBlockNumber + 1);
704
+ this.dbs.set(firstBlockNumber, db);
705
+ // Get archive sibling path before any block in this checkpoint lands.
706
+ const lastArchiveSiblingPath = await getLastSiblingPath(MerkleTreeId.ARCHIVE, db);
707
+ // Streaming Inbox: messages are inserted per block in `startNewBlock`, not the whole
708
+ // checkpoint up front. The message sponge is likewise threaded per block (each block's start sponge is the
709
+ // previous block's end), so the last block's end sponge matches the checkpoint's single InboxParity proof.
710
+ this.provingState = new CheckpointProvingState(/* index */ 0, constants, totalNumBlocks, headerOfLastBlockInPreviousCheckpoint, lastArchiveSiblingPath, l1ToL2Messages, startInboxRollingHash, Number(this.epochNumber), /* isAlive */ ()=>!this.cancelled, /* onReject */ (reason)=>this.subTreeResult.reject(new Error(reason)));
711
+ // Parity now gates the checkpoint root (not the first block root); prove the single sized InboxParity per
712
+ // checkpoint up front.
713
+ this.enqueueInboxParityCircuit(this.provingState);
714
+ }
715
+ // ---------------- private: per-block proof orchestration ----------------
716
+ // Updates the merkle trees for a transaction. The first enqueued job for a transaction.
717
+ async prepareBaseRollupInputs(tx, lastArchive, newL1ToL2MessageTreeSnapshot, startSpongeBlob, db) {
718
+ // These hints deliberately carry no recursive proof or verification key — see
719
+ // BaseRollupHintsWithoutProofAndVK. The tx's proof + VK are attached later in
720
+ // TxProvingState.getBaseRollupTypeAndInputs from the proven chonk-verifier / kernel / AVM
721
+ // proofs, which are required there and so cannot be silently omitted.
722
+ const start = performance.now();
723
+ const hints = await insertSideEffectsAndBuildBaseRollupHints(tx, lastArchive, newL1ToL2MessageTreeSnapshot, startSpongeBlob, this.proverId.toField(), db);
724
+ this.metrics.recordBaseRollupInputs(performance.now() - start);
725
+ const promises = [
726
+ MerkleTreeId.NOTE_HASH_TREE,
727
+ MerkleTreeId.NULLIFIER_TREE,
728
+ MerkleTreeId.PUBLIC_DATA_TREE
729
+ ].map(async (id)=>{
730
+ return {
731
+ key: id,
732
+ value: await getTreeSnapshot(id, db)
733
+ };
734
+ });
735
+ const treeSnapshots = new Map((await Promise.all(promises)).map((obj)=>[
736
+ obj.key,
737
+ obj.value
738
+ ]));
739
+ return [
740
+ hints,
741
+ treeSnapshots
742
+ ];
743
+ }
744
+ // Executes the base rollup circuit and stores the output as intermediate state for the parent merge/root circuit.
745
+ // Executes the next level of merge if all inputs are available.
746
+ enqueueBaseRollup(provingState, txIndex) {
747
+ if (!provingState.verifyState()) {
748
+ this.logger.debug('Not running base rollup, state invalid');
749
+ return;
750
+ }
751
+ if (!provingState.tryStartProvingBase(txIndex)) {
752
+ this.logger.debug(`Base rollup for tx ${txIndex} already started.`);
753
+ return;
754
+ }
755
+ const txProvingState = provingState.getTxProvingState(txIndex);
756
+ const { processedTx } = txProvingState;
757
+ const { rollupType, inputs } = txProvingState.getBaseRollupTypeAndInputs();
758
+ this.logger.debug(`Enqueuing deferred proving base rollup for ${processedTx.hash.toString()}`);
759
+ this.deferredProving(provingState, this.wrapCircuitCall(inputs instanceof PrivateTxBaseRollupPrivateInputs ? 'getPrivateTxBaseRollupProof' : 'getPublicTxBaseRollupProof', (signal)=>{
760
+ if (inputs instanceof PrivateTxBaseRollupPrivateInputs) {
761
+ return this.prover.getPrivateTxBaseRollupProof(inputs, signal, provingState.epochNumber);
762
+ } else {
763
+ return this.prover.getPublicTxBaseRollupProof(inputs, signal, provingState.epochNumber);
764
+ }
765
+ }, {
766
+ [Attributes.TX_HASH]: processedTx.hash.toString(),
767
+ [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType
768
+ }), (result)=>{
769
+ this.logger.debug(`Completed proof for ${rollupType} for tx ${processedTx.hash.toString()}`);
770
+ validatePartialState(result.inputs.endTreeSnapshots, txProvingState.treeSnapshots);
771
+ const leafLocation = provingState.setBaseRollupProof(txIndex, result);
772
+ if (provingState.totalNumTxs === 1) {
773
+ this.checkAndEnqueueBlockRootRollup(provingState);
774
+ } else {
775
+ this.checkAndEnqueueNextMergeRollup(provingState, leafLocation);
776
+ }
777
+ });
778
+ }
779
+ /**
780
+ * Route the tx's chonk-verifier dependency through the per-epoch context: read the
781
+ * cached promise (or enqueue if missing), then `.then(handleResult)` to progress to
782
+ * the base rollup once the proof lands.
783
+ */ getOrEnqueueChonkVerifier(provingState, txIndex) {
784
+ if (!provingState.verifyState()) {
785
+ return;
786
+ }
787
+ const txProvingState = provingState.getTxProvingState(txIndex);
788
+ const txHash = txProvingState.processedTx.hash.toString();
789
+ const handleResult = (result)=>{
790
+ if (!provingState.verifyState()) {
791
+ return;
792
+ }
793
+ txProvingState.setPublicChonkVerifierProof(result);
794
+ this.checkAndEnqueueBaseRollup(provingState, txIndex);
795
+ };
796
+ const promise = this.chonkCache.getOrCompute(txHash, (signal)=>this.prover.getPublicChonkVerifierProof(txProvingState.getPublicChonkVerifierPrivateInputs(), signal, this.epochNumber));
797
+ void promise.then(handleResult).catch((err)=>{
798
+ // The cache self-cleans on rejection, so a replacement sub-tree for this tx will see the
799
+ // miss and re-enqueue. But if this proving state is still active, the failure must abort
800
+ // it: otherwise the base rollup for this tx is never enqueued and the checkpoint (and
801
+ // epoch) orchestrators hang forever waiting for a proof that will never arrive.
802
+ if (err instanceof AbortError || !provingState.verifyState()) {
803
+ return;
804
+ }
805
+ this.logger.error(`Chonk verifier proof failed for tx ${txHash}`, err);
806
+ provingState.reject(`Chonk verifier proof failed for tx ${txHash}: ${err}`);
807
+ });
808
+ }
809
+ // Executes the merge rollup circuit. Enqueues the next level of merge if all inputs are available.
810
+ enqueueMergeRollup(provingState, location) {
811
+ if (!provingState.verifyState()) {
812
+ this.logger.debug('Not running merge rollup. State no longer valid.');
813
+ return;
814
+ }
815
+ if (!provingState.tryStartProvingMerge(location)) {
816
+ this.logger.debug('Merge rollup already started.');
817
+ return;
818
+ }
819
+ const inputs = provingState.getMergeRollupInputs(location);
820
+ this.deferredProving(provingState, this.wrapCircuitCall('getTxMergeRollupProof', (signal)=>this.prover.getTxMergeRollupProof(inputs, signal, provingState.epochNumber), {
821
+ [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-tx-merge'
822
+ }), (result)=>{
823
+ provingState.setMergeRollupProof(location, result);
824
+ this.checkAndEnqueueNextMergeRollup(provingState, location);
825
+ });
826
+ }
827
+ // Executes the block root rollup circuit.
828
+ enqueueBlockRootRollup(provingState) {
829
+ if (!provingState.verifyState()) {
830
+ this.logger.debug('Not running block root rollup, state no longer valid');
831
+ return;
832
+ }
833
+ if (!provingState.tryStartProvingBlockRoot()) {
834
+ this.logger.debug('Block root rollup already started.');
835
+ return;
836
+ }
837
+ // Kept whole (not destructured) so the switch on the `rollupType` discriminant narrows `inputs` per case.
838
+ const rollup = provingState.getBlockRootRollupTypeAndInputs();
839
+ const rollupType = rollup.rollupType;
840
+ this.logger.debug(`Enqueuing ${rollupType} for block ${provingState.blockNumber}.`);
841
+ this.deferredProving(provingState, this.wrapCircuitCall('getBlockRootRollupProof', (signal)=>{
842
+ switch(rollup.rollupType){
843
+ case 'rollup-block-root-no-txs':
844
+ return this.prover.getBlockRootNoTxsRollupProof(rollup.inputs, signal, provingState.epochNumber);
845
+ case 'rollup-block-root-single-tx':
846
+ return this.prover.getBlockRootSingleTxRollupProof(rollup.inputs, signal, provingState.epochNumber);
847
+ case 'rollup-block-root':
848
+ return this.prover.getBlockRootRollupProof(rollup.inputs, signal, provingState.epochNumber);
849
+ }
850
+ }, {
851
+ [Attributes.PROTOCOL_CIRCUIT_NAME]: rollupType
852
+ }), async (result)=>{
853
+ this.logger.debug(`Completed ${rollupType} proof for block ${provingState.blockNumber}`, {
854
+ blockNumber: provingState.blockNumber,
855
+ checkpointIndex: provingState.parentCheckpoint.index,
856
+ ...result.inputs.toInspect()
857
+ });
858
+ const leafLocation = provingState.setBlockRootRollupProof(result);
859
+ const checkpointProvingState = provingState.parentCheckpoint;
860
+ // Verification is called from both here and setBlockCompleted. Whichever runs last
861
+ // will be the first to see all three pieces (header, proof output, archive) and run the checks.
862
+ await this.verifyBuiltBlockAgainstSyncedState(provingState);
863
+ if (checkpointProvingState.totalNumBlocks === 1) {
864
+ this.checkAndEnqueueSubTreeResolution(checkpointProvingState);
865
+ } else {
866
+ this.checkAndEnqueueNextBlockMergeRollup(checkpointProvingState, leafLocation);
867
+ }
868
+ });
869
+ }
870
+ // Runs the checkpoint's single InboxParity circuit and stores the output. The proof feeds the checkpoint root (in
871
+ // the top tree), so completing it may resolve the sub-tree rather than a block root.
872
+ enqueueInboxParityCircuit(checkpointProvingState) {
873
+ if (!checkpointProvingState.verifyState()) {
874
+ this.logger.debug('Not running inbox parity. State no longer valid.');
875
+ return;
876
+ }
877
+ if (!checkpointProvingState.tryStartProvingInboxParity()) {
878
+ this.logger.debug('Inbox parity already started.');
879
+ return;
880
+ }
881
+ const inputs = checkpointProvingState.getInboxParityInputs();
882
+ const circuitName = `inbox-parity-${inputs.size}`;
883
+ this.deferredProving(checkpointProvingState, this.wrapCircuitCall('getInboxParityProof', (signal)=>this.prover.getInboxParityProof(inputs, signal, checkpointProvingState.epochNumber), {
884
+ [Attributes.PROTOCOL_CIRCUIT_NAME]: circuitName
885
+ }), (result)=>{
886
+ checkpointProvingState.setInboxParityProof(result);
887
+ this.checkAndEnqueueSubTreeResolution(checkpointProvingState);
888
+ });
889
+ }
890
+ // Executes the block merge rollup circuit.
891
+ enqueueBlockMergeRollup(provingState, location) {
892
+ if (!provingState.verifyState()) {
893
+ this.logger.debug('Not running block merge rollup. State no longer valid.');
894
+ return;
895
+ }
896
+ if (!provingState.tryStartProvingBlockMerge(location)) {
897
+ this.logger.debug('Block merge rollup already started.');
898
+ return;
899
+ }
900
+ const inputs = provingState.getBlockMergeRollupInputs(location);
901
+ this.deferredProving(provingState, this.wrapCircuitCall('getBlockMergeRollupProof', (signal)=>this.prover.getBlockMergeRollupProof(inputs, signal, provingState.epochNumber), {
902
+ [Attributes.PROTOCOL_CIRCUIT_NAME]: 'rollup-block-merge'
903
+ }), (result)=>{
904
+ this.logger.debug(`Completed block merge rollup proof for checkpoint ${provingState.index}`, {
905
+ checkpointIndex: provingState.index,
906
+ mergeLocation: location,
907
+ ...result.inputs.toInspect()
908
+ });
909
+ provingState.setBlockMergeRollupProof(location, result);
910
+ this.checkAndEnqueueNextBlockMergeRollup(provingState, location);
911
+ });
912
+ }
913
+ checkAndEnqueueNextMergeRollup(provingState, currentLocation) {
914
+ if (!provingState.isReadyForMergeRollup(currentLocation)) {
915
+ return;
916
+ }
917
+ const parentLocation = provingState.getParentLocation(currentLocation);
918
+ if (parentLocation.level === 0) {
919
+ this.checkAndEnqueueBlockRootRollup(provingState);
920
+ } else {
921
+ this.enqueueMergeRollup(provingState, parentLocation);
922
+ }
923
+ }
924
+ checkAndEnqueueBlockRootRollup(provingState) {
925
+ if (!provingState.isReadyForBlockRootRollup()) {
926
+ this.logger.debug('Not ready for block root rollup');
927
+ return;
928
+ }
929
+ this.enqueueBlockRootRollup(provingState);
930
+ }
931
+ checkAndEnqueueNextBlockMergeRollup(provingState, currentLocation) {
932
+ if (!provingState.isReadyForBlockMerge(currentLocation)) {
933
+ return;
934
+ }
935
+ const parentLocation = provingState.getParentLocation(currentLocation);
936
+ if (parentLocation.level === 0) {
937
+ this.checkAndEnqueueSubTreeResolution(provingState);
938
+ } else {
939
+ this.enqueueBlockMergeRollup(provingState, parentLocation);
940
+ }
941
+ }
942
+ /**
943
+ * Sub-tree analogue of the orchestrator's `checkAndEnqueueCheckpointRootRollup`:
944
+ * resolves the sub-tree promise with the block-level proof outputs once they're all ready,
945
+ * instead of escalating to the checkpoint root rollup.
946
+ */ checkAndEnqueueSubTreeResolution(provingState) {
947
+ const proofs = provingState.getSubTreeOutputProofs();
948
+ const nonEmpty = proofs.filter((p)=>!!p);
949
+ if (proofs.length !== nonEmpty.length) {
950
+ // Block merge tree not fully resolved yet — retried as more block proofs land.
951
+ return;
952
+ }
953
+ // The InboxParity proof gates the sub-tree result too (it feeds the checkpoint root in the top tree).
954
+ const inboxParityProof = provingState.getInboxParityProof();
955
+ if (!inboxParityProof) {
956
+ // Parity not proven yet — retried when the inbox parity proof lands.
957
+ return;
958
+ }
959
+ this.subTreeResult.resolve({
960
+ blockProofOutputs: nonEmpty,
961
+ inboxParityProof,
962
+ previousArchiveSiblingPath: provingState.getLastArchiveSiblingPath()
963
+ });
964
+ }
965
+ /**
966
+ * Executes the VM circuit for a public function. Enqueues the base rollup once the
967
+ * tx's chonk-verifier + VM proofs are both ready.
968
+ */ enqueueVM(provingState, txIndex) {
969
+ if (!provingState.verifyState()) {
970
+ this.logger.debug(`Not running VM circuit as state is no longer valid`);
971
+ return;
972
+ }
973
+ const txProvingState = provingState.getTxProvingState(txIndex);
974
+ this.deferredProving(provingState, this.wrapCircuitCall('getAvmProof', async (signal)=>{
975
+ const inputs = txProvingState.getAvmInputs();
976
+ return await this.prover.getAvmProof(inputs, signal, provingState.epochNumber);
977
+ }, {
978
+ [Attributes.TX_HASH]: txProvingState.processedTx.hash.toString()
979
+ }), (proof)=>{
980
+ this.logger.debug(`Proven VM for tx index: ${txIndex}`);
981
+ txProvingState.setAvmProof(proof);
982
+ this.checkAndEnqueueBaseRollup(provingState, txIndex);
983
+ });
984
+ }
985
+ checkAndEnqueueBaseRollup(provingState, txIndex) {
986
+ const txProvingState = provingState.getTxProvingState(txIndex);
987
+ if (!txProvingState.ready()) {
988
+ return;
989
+ }
990
+ // All upstream proofs (chonk verifier and, if required, vm) are ready — proceed to the base rollup.
991
+ this.logger.debug(`Public functions completed for tx ${txIndex} enqueueing base rollup`);
992
+ this.enqueueBaseRollup(provingState, txIndex);
993
+ }
994
+ // Flagged as protected so unit tests can override.
995
+ async verifyBuiltBlockAgainstSyncedState(provingState) {
996
+ const builtBlockHeader = provingState.getBuiltBlockHeader();
997
+ if (!builtBlockHeader) {
998
+ this.logger.debug('Block header not built yet, skipping header check.');
999
+ return;
1000
+ }
1001
+ const output = provingState.getBlockRootRollupOutput();
1002
+ if (!output) {
1003
+ this.logger.debug('Block root rollup proof not built yet, skipping header check.');
1004
+ return;
1005
+ }
1006
+ const newArchive = provingState.getBuiltArchive();
1007
+ if (!newArchive) {
1008
+ this.logger.debug('Archive snapshot not yet captured, skipping header check.');
1009
+ return;
1010
+ }
1011
+ const header = await buildHeaderFromCircuitOutputs(output);
1012
+ if (!(await header.hash()).equals(await builtBlockHeader.hash())) {
1013
+ this.logger.error(`Block header mismatch.\nCircuit: ${inspect(header)}\nComputed: ${inspect(builtBlockHeader)}`);
1014
+ provingState.reject(`Block header hash mismatch.`);
1015
+ return;
1016
+ }
1017
+ const blockNumber = provingState.blockNumber;
1018
+ const syncedArchive = await getTreeSnapshot(MerkleTreeId.ARCHIVE, this.dbProvider.getSnapshot(blockNumber));
1019
+ if (!syncedArchive.equals(newArchive)) {
1020
+ this.logger.error(`Archive tree mismatch for block ${blockNumber}: world state synced to ${inspect(syncedArchive)} but built ${inspect(newArchive)}`);
1021
+ provingState.reject(`Archive tree mismatch.`);
1022
+ return;
1023
+ }
1024
+ const circuitArchive = output.newArchive;
1025
+ if (!newArchive.equals(circuitArchive)) {
1026
+ this.logger.error(`New archive mismatch.\nCircuit: ${output.newArchive}\nComputed: ${newArchive}`);
1027
+ provingState.reject(`New archive mismatch.`);
1028
+ return;
1029
+ }
1030
+ }
1031
+ getDbForBlock(blockNumber) {
1032
+ const db = this.dbs.get(blockNumber);
1033
+ if (!db) {
1034
+ throw new Error(`World state fork for block ${blockNumber} not found.`);
1035
+ }
1036
+ return db;
1037
+ }
1038
+ /**
1039
+ * Wraps a circuit call with a tracer span and circuit attributes. Replaces the
1040
+ * `ProvingScheduler.wrapCircuitCall` indirection that used to live on the abstract base.
1041
+ */ wrapCircuitCall(circuitName, fn, attributes = {}) {
1042
+ return wrapCallbackInSpan(this.tracer, `CheckpointSubTreeOrchestrator.prover.${circuitName}`, {
1043
+ [Attributes.PROTOCOL_CIRCUIT_NAME]: circuitName,
1044
+ ...attributes
1045
+ }, fn);
1046
+ }
1047
+ }