@aztec-labs/sequencer-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 (165) hide show
  1. package/README.md +307 -0
  2. package/dest/client/index.d.ts +2 -0
  3. package/dest/client/index.d.ts.map +1 -0
  4. package/dest/client/index.js +1 -0
  5. package/dest/client/sequencer-client.d.ts +94 -0
  6. package/dest/client/sequencer-client.d.ts.map +1 -0
  7. package/dest/client/sequencer-client.js +177 -0
  8. package/dest/config.d.ts +56 -0
  9. package/dest/config.d.ts.map +1 -0
  10. package/dest/config.js +251 -0
  11. package/dest/global_variable_builder/fee_predictor.d.ts +49 -0
  12. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  13. package/dest/global_variable_builder/fee_predictor.js +127 -0
  14. package/dest/global_variable_builder/fee_provider.d.ts +28 -0
  15. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  16. package/dest/global_variable_builder/fee_provider.js +87 -0
  17. package/dest/global_variable_builder/global_builder.d.ts +28 -0
  18. package/dest/global_variable_builder/global_builder.d.ts.map +1 -0
  19. package/dest/global_variable_builder/global_builder.js +40 -0
  20. package/dest/global_variable_builder/index.d.ts +4 -0
  21. package/dest/global_variable_builder/index.d.ts.map +1 -0
  22. package/dest/global_variable_builder/index.js +3 -0
  23. package/dest/index.d.ts +7 -0
  24. package/dest/index.d.ts.map +1 -0
  25. package/dest/index.js +8 -0
  26. package/dest/publisher/config.d.ts +68 -0
  27. package/dest/publisher/config.d.ts.map +1 -0
  28. package/dest/publisher/config.js +137 -0
  29. package/dest/publisher/index.d.ts +5 -0
  30. package/dest/publisher/index.d.ts.map +1 -0
  31. package/dest/publisher/index.js +4 -0
  32. package/dest/publisher/l1_to_l2_messaging.d.ts +21 -0
  33. package/dest/publisher/l1_to_l2_messaging.d.ts.map +1 -0
  34. package/dest/publisher/l1_to_l2_messaging.js +70 -0
  35. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  36. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  37. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  38. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +101 -0
  39. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  40. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +68 -0
  41. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  42. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  43. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +36 -0
  44. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  45. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  46. package/dest/publisher/l1_tx_failed_store/index.js +3 -0
  47. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  48. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  49. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  50. package/dest/publisher/sequencer-publisher-factory.d.ts +50 -0
  51. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -0
  52. package/dest/publisher/sequencer-publisher-factory.js +75 -0
  53. package/dest/publisher/sequencer-publisher-metrics.d.ts +26 -0
  54. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -0
  55. package/dest/publisher/sequencer-publisher-metrics.js +101 -0
  56. package/dest/publisher/sequencer-publisher.d.ts +254 -0
  57. package/dest/publisher/sequencer-publisher.d.ts.map +1 -0
  58. package/dest/publisher/sequencer-publisher.js +1784 -0
  59. package/dest/publisher/write_json.d.ts +11 -0
  60. package/dest/publisher/write_json.d.ts.map +1 -0
  61. package/dest/publisher/write_json.js +57 -0
  62. package/dest/sequencer/automine/automine_factory.d.ts +56 -0
  63. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  64. package/dest/sequencer/automine/automine_factory.js +85 -0
  65. package/dest/sequencer/automine/automine_sequencer.d.ts +189 -0
  66. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  67. package/dest/sequencer/automine/automine_sequencer.js +732 -0
  68. package/dest/sequencer/automine/index.d.ts +3 -0
  69. package/dest/sequencer/automine/index.d.ts.map +1 -0
  70. package/dest/sequencer/automine/index.js +2 -0
  71. package/dest/sequencer/checkpoint_proposal_job.d.ts +169 -0
  72. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  73. package/dest/sequencer/checkpoint_proposal_job.js +1961 -0
  74. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  75. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  76. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  77. package/dest/sequencer/checkpoint_voter.d.ts +34 -0
  78. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  79. package/dest/sequencer/checkpoint_voter.js +106 -0
  80. package/dest/sequencer/config.d.ts +8 -0
  81. package/dest/sequencer/config.d.ts.map +1 -0
  82. package/dest/sequencer/config.js +1 -0
  83. package/dest/sequencer/errors.d.ts +11 -0
  84. package/dest/sequencer/errors.d.ts.map +1 -0
  85. package/dest/sequencer/errors.js +15 -0
  86. package/dest/sequencer/events.d.ts +103 -0
  87. package/dest/sequencer/events.d.ts.map +1 -0
  88. package/dest/sequencer/events.js +1 -0
  89. package/dest/sequencer/inbox_bucket_selector.d.ts +88 -0
  90. package/dest/sequencer/inbox_bucket_selector.d.ts.map +1 -0
  91. package/dest/sequencer/inbox_bucket_selector.js +80 -0
  92. package/dest/sequencer/index.d.ts +6 -0
  93. package/dest/sequencer/index.d.ts.map +1 -0
  94. package/dest/sequencer/index.js +5 -0
  95. package/dest/sequencer/metrics.d.ts +75 -0
  96. package/dest/sequencer/metrics.d.ts.map +1 -0
  97. package/dest/sequencer/metrics.js +343 -0
  98. package/dest/sequencer/missing_committee.d.ts +72 -0
  99. package/dest/sequencer/missing_committee.d.ts.map +1 -0
  100. package/dest/sequencer/missing_committee.js +139 -0
  101. package/dest/sequencer/requests_tracker.d.ts +22 -0
  102. package/dest/sequencer/requests_tracker.d.ts.map +1 -0
  103. package/dest/sequencer/requests_tracker.js +33 -0
  104. package/dest/sequencer/sequencer.d.ts +326 -0
  105. package/dest/sequencer/sequencer.d.ts.map +1 -0
  106. package/dest/sequencer/sequencer.js +1495 -0
  107. package/dest/sequencer/types.d.ts +3 -0
  108. package/dest/sequencer/types.d.ts.map +1 -0
  109. package/dest/sequencer/types.js +1 -0
  110. package/dest/sequencer/utils.d.ts +30 -0
  111. package/dest/sequencer/utils.d.ts.map +1 -0
  112. package/dest/sequencer/utils.js +18 -0
  113. package/dest/test/index.d.ts +23 -0
  114. package/dest/test/index.d.ts.map +1 -0
  115. package/dest/test/index.js +6 -0
  116. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  117. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  118. package/dest/test/mock_checkpoint_builder.js +230 -0
  119. package/dest/test/utils.d.ts +67 -0
  120. package/dest/test/utils.d.ts.map +1 -0
  121. package/dest/test/utils.js +121 -0
  122. package/package.json +118 -0
  123. package/src/client/index.ts +1 -0
  124. package/src/client/sequencer-client.ts +281 -0
  125. package/src/config.ts +309 -0
  126. package/src/global_variable_builder/README.md +44 -0
  127. package/src/global_variable_builder/fee_predictor.ts +176 -0
  128. package/src/global_variable_builder/fee_provider.ts +104 -0
  129. package/src/global_variable_builder/global_builder.ts +68 -0
  130. package/src/global_variable_builder/index.ts +3 -0
  131. package/src/index.ts +15 -0
  132. package/src/publisher/config.ts +220 -0
  133. package/src/publisher/index.ts +8 -0
  134. package/src/publisher/l1_to_l2_messaging.ts +85 -0
  135. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  136. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +166 -0
  137. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +47 -0
  138. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  139. package/src/publisher/sequencer-bundle-simulator.ts +253 -0
  140. package/src/publisher/sequencer-publisher-factory.ts +121 -0
  141. package/src/publisher/sequencer-publisher-metrics.ts +145 -0
  142. package/src/publisher/sequencer-publisher.ts +1719 -0
  143. package/src/publisher/write_json.ts +77 -0
  144. package/src/sequencer/README.md +243 -0
  145. package/src/sequencer/automine/README.md +60 -0
  146. package/src/sequencer/automine/automine_factory.ts +156 -0
  147. package/src/sequencer/automine/automine_sequencer.ts +841 -0
  148. package/src/sequencer/automine/index.ts +6 -0
  149. package/src/sequencer/checkpoint_proposal_job.ts +1889 -0
  150. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  151. package/src/sequencer/checkpoint_voter.ts +118 -0
  152. package/src/sequencer/config.ts +9 -0
  153. package/src/sequencer/errors.ts +21 -0
  154. package/src/sequencer/events.ts +93 -0
  155. package/src/sequencer/inbox_bucket_selector.ts +160 -0
  156. package/src/sequencer/index.ts +5 -0
  157. package/src/sequencer/metrics.ts +463 -0
  158. package/src/sequencer/missing_committee.ts +192 -0
  159. package/src/sequencer/requests_tracker.ts +43 -0
  160. package/src/sequencer/sequencer.ts +1401 -0
  161. package/src/sequencer/types.ts +6 -0
  162. package/src/sequencer/utils.ts +42 -0
  163. package/src/test/index.ts +26 -0
  164. package/src/test/mock_checkpoint_builder.ts +324 -0
  165. package/src/test/utils.ts +215 -0
@@ -0,0 +1,1961 @@
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
+ function applyDecs2203RFactory() {
67
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
68
+ return function addInitializer(initializer) {
69
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
70
+ assertCallable(initializer, "An initializer");
71
+ initializers.push(initializer);
72
+ };
73
+ }
74
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
75
+ var kindStr;
76
+ switch(kind){
77
+ case 1:
78
+ kindStr = "accessor";
79
+ break;
80
+ case 2:
81
+ kindStr = "method";
82
+ break;
83
+ case 3:
84
+ kindStr = "getter";
85
+ break;
86
+ case 4:
87
+ kindStr = "setter";
88
+ break;
89
+ default:
90
+ kindStr = "field";
91
+ }
92
+ var ctx = {
93
+ kind: kindStr,
94
+ name: isPrivate ? "#" + name : name,
95
+ static: isStatic,
96
+ private: isPrivate,
97
+ metadata: metadata
98
+ };
99
+ var decoratorFinishedRef = {
100
+ v: false
101
+ };
102
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
103
+ var get, set;
104
+ if (kind === 0) {
105
+ if (isPrivate) {
106
+ get = desc.get;
107
+ set = desc.set;
108
+ } else {
109
+ get = function() {
110
+ return this[name];
111
+ };
112
+ set = function(v) {
113
+ this[name] = v;
114
+ };
115
+ }
116
+ } else if (kind === 2) {
117
+ get = function() {
118
+ return desc.value;
119
+ };
120
+ } else {
121
+ if (kind === 1 || kind === 3) {
122
+ get = function() {
123
+ return desc.get.call(this);
124
+ };
125
+ }
126
+ if (kind === 1 || kind === 4) {
127
+ set = function(v) {
128
+ desc.set.call(this, v);
129
+ };
130
+ }
131
+ }
132
+ ctx.access = get && set ? {
133
+ get: get,
134
+ set: set
135
+ } : get ? {
136
+ get: get
137
+ } : {
138
+ set: set
139
+ };
140
+ try {
141
+ return dec(value, ctx);
142
+ } finally{
143
+ decoratorFinishedRef.v = true;
144
+ }
145
+ }
146
+ function assertNotFinished(decoratorFinishedRef, fnName) {
147
+ if (decoratorFinishedRef.v) {
148
+ throw new Error("attempted to call " + fnName + " after decoration was finished");
149
+ }
150
+ }
151
+ function assertCallable(fn, hint) {
152
+ if (typeof fn !== "function") {
153
+ throw new TypeError(hint + " must be a function");
154
+ }
155
+ }
156
+ function assertValidReturnValue(kind, value) {
157
+ var type = typeof value;
158
+ if (kind === 1) {
159
+ if (type !== "object" || value === null) {
160
+ throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
161
+ }
162
+ if (value.get !== undefined) {
163
+ assertCallable(value.get, "accessor.get");
164
+ }
165
+ if (value.set !== undefined) {
166
+ assertCallable(value.set, "accessor.set");
167
+ }
168
+ if (value.init !== undefined) {
169
+ assertCallable(value.init, "accessor.init");
170
+ }
171
+ } else if (type !== "function") {
172
+ var hint;
173
+ if (kind === 0) {
174
+ hint = "field";
175
+ } else if (kind === 10) {
176
+ hint = "class";
177
+ } else {
178
+ hint = "method";
179
+ }
180
+ throw new TypeError(hint + " decorators must return a function or void 0");
181
+ }
182
+ }
183
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
184
+ var decs = decInfo[0];
185
+ var desc, init, value;
186
+ if (isPrivate) {
187
+ if (kind === 0 || kind === 1) {
188
+ desc = {
189
+ get: decInfo[3],
190
+ set: decInfo[4]
191
+ };
192
+ } else if (kind === 3) {
193
+ desc = {
194
+ get: decInfo[3]
195
+ };
196
+ } else if (kind === 4) {
197
+ desc = {
198
+ set: decInfo[3]
199
+ };
200
+ } else {
201
+ desc = {
202
+ value: decInfo[3]
203
+ };
204
+ }
205
+ } else if (kind !== 0) {
206
+ desc = Object.getOwnPropertyDescriptor(base, name);
207
+ }
208
+ if (kind === 1) {
209
+ value = {
210
+ get: desc.get,
211
+ set: desc.set
212
+ };
213
+ } else if (kind === 2) {
214
+ value = desc.value;
215
+ } else if (kind === 3) {
216
+ value = desc.get;
217
+ } else if (kind === 4) {
218
+ value = desc.set;
219
+ }
220
+ var newValue, get, set;
221
+ if (typeof decs === "function") {
222
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
223
+ if (newValue !== void 0) {
224
+ assertValidReturnValue(kind, newValue);
225
+ if (kind === 0) {
226
+ init = newValue;
227
+ } else if (kind === 1) {
228
+ init = newValue.init;
229
+ get = newValue.get || value.get;
230
+ set = newValue.set || value.set;
231
+ value = {
232
+ get: get,
233
+ set: set
234
+ };
235
+ } else {
236
+ value = newValue;
237
+ }
238
+ }
239
+ } else {
240
+ for(var i = decs.length - 1; i >= 0; i--){
241
+ var dec = decs[i];
242
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
243
+ if (newValue !== void 0) {
244
+ assertValidReturnValue(kind, newValue);
245
+ var newInit;
246
+ if (kind === 0) {
247
+ newInit = newValue;
248
+ } else if (kind === 1) {
249
+ newInit = newValue.init;
250
+ get = newValue.get || value.get;
251
+ set = newValue.set || value.set;
252
+ value = {
253
+ get: get,
254
+ set: set
255
+ };
256
+ } else {
257
+ value = newValue;
258
+ }
259
+ if (newInit !== void 0) {
260
+ if (init === void 0) {
261
+ init = newInit;
262
+ } else if (typeof init === "function") {
263
+ init = [
264
+ init,
265
+ newInit
266
+ ];
267
+ } else {
268
+ init.push(newInit);
269
+ }
270
+ }
271
+ }
272
+ }
273
+ }
274
+ if (kind === 0 || kind === 1) {
275
+ if (init === void 0) {
276
+ init = function(instance, init) {
277
+ return init;
278
+ };
279
+ } else if (typeof init !== "function") {
280
+ var ownInitializers = init;
281
+ init = function(instance, init) {
282
+ var value = init;
283
+ for(var i = 0; i < ownInitializers.length; i++){
284
+ value = ownInitializers[i].call(instance, value);
285
+ }
286
+ return value;
287
+ };
288
+ } else {
289
+ var originalInitializer = init;
290
+ init = function(instance, init) {
291
+ return originalInitializer.call(instance, init);
292
+ };
293
+ }
294
+ ret.push(init);
295
+ }
296
+ if (kind !== 0) {
297
+ if (kind === 1) {
298
+ desc.get = value.get;
299
+ desc.set = value.set;
300
+ } else if (kind === 2) {
301
+ desc.value = value;
302
+ } else if (kind === 3) {
303
+ desc.get = value;
304
+ } else if (kind === 4) {
305
+ desc.set = value;
306
+ }
307
+ if (isPrivate) {
308
+ if (kind === 1) {
309
+ ret.push(function(instance, args) {
310
+ return value.get.call(instance, args);
311
+ });
312
+ ret.push(function(instance, args) {
313
+ return value.set.call(instance, args);
314
+ });
315
+ } else if (kind === 2) {
316
+ ret.push(value);
317
+ } else {
318
+ ret.push(function(instance, args) {
319
+ return value.call(instance, args);
320
+ });
321
+ }
322
+ } else {
323
+ Object.defineProperty(base, name, desc);
324
+ }
325
+ }
326
+ }
327
+ function applyMemberDecs(Class, decInfos, metadata) {
328
+ var ret = [];
329
+ var protoInitializers;
330
+ var staticInitializers;
331
+ var existingProtoNonFields = new Map();
332
+ var existingStaticNonFields = new Map();
333
+ for(var i = 0; i < decInfos.length; i++){
334
+ var decInfo = decInfos[i];
335
+ if (!Array.isArray(decInfo)) continue;
336
+ var kind = decInfo[1];
337
+ var name = decInfo[2];
338
+ var isPrivate = decInfo.length > 3;
339
+ var isStatic = kind >= 5;
340
+ var base;
341
+ var initializers;
342
+ if (isStatic) {
343
+ base = Class;
344
+ kind = kind - 5;
345
+ staticInitializers = staticInitializers || [];
346
+ initializers = staticInitializers;
347
+ } else {
348
+ base = Class.prototype;
349
+ protoInitializers = protoInitializers || [];
350
+ initializers = protoInitializers;
351
+ }
352
+ if (kind !== 0 && !isPrivate) {
353
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
354
+ var existingKind = existingNonFields.get(name) || 0;
355
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
356
+ 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);
357
+ } else if (!existingKind && kind > 2) {
358
+ existingNonFields.set(name, kind);
359
+ } else {
360
+ existingNonFields.set(name, true);
361
+ }
362
+ }
363
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
364
+ }
365
+ pushInitializers(ret, protoInitializers);
366
+ pushInitializers(ret, staticInitializers);
367
+ return ret;
368
+ }
369
+ function pushInitializers(ret, initializers) {
370
+ if (initializers) {
371
+ ret.push(function(instance) {
372
+ for(var i = 0; i < initializers.length; i++){
373
+ initializers[i].call(instance);
374
+ }
375
+ return instance;
376
+ });
377
+ }
378
+ }
379
+ function applyClassDecs(targetClass, classDecs, metadata) {
380
+ if (classDecs.length > 0) {
381
+ var initializers = [];
382
+ var newClass = targetClass;
383
+ var name = targetClass.name;
384
+ for(var i = classDecs.length - 1; i >= 0; i--){
385
+ var decoratorFinishedRef = {
386
+ v: false
387
+ };
388
+ try {
389
+ var nextNewClass = classDecs[i](newClass, {
390
+ kind: "class",
391
+ name: name,
392
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
393
+ metadata
394
+ });
395
+ } finally{
396
+ decoratorFinishedRef.v = true;
397
+ }
398
+ if (nextNewClass !== undefined) {
399
+ assertValidReturnValue(10, nextNewClass);
400
+ newClass = nextNewClass;
401
+ }
402
+ }
403
+ return [
404
+ defineMetadata(newClass, metadata),
405
+ function() {
406
+ for(var i = 0; i < initializers.length; i++){
407
+ initializers[i].call(newClass);
408
+ }
409
+ }
410
+ ];
411
+ }
412
+ }
413
+ function defineMetadata(Class, metadata) {
414
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
415
+ configurable: true,
416
+ enumerable: true,
417
+ value: metadata
418
+ });
419
+ }
420
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
421
+ if (parentClass !== void 0) {
422
+ var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
423
+ }
424
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
425
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
426
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
427
+ return {
428
+ e: e,
429
+ get c () {
430
+ return applyClassDecs(targetClass, classDecs, metadata);
431
+ }
432
+ };
433
+ };
434
+ }
435
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
436
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
437
+ }
438
+ var _dec, _dec1, _dec2, _dec3, _dec4, _dec5, _dec6, _initProto;
439
+ import { MAX_L1_TO_L2_MSGS_PER_BLOCK, MAX_L1_TO_L2_MSGS_PER_CHECKPOINT } from '@aztec-labs/constants';
440
+ import { PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec-labs/epoch-cache';
441
+ import { BlockNumber, CheckpointNumber, IndexWithinCheckpoint, SlotNumber } from '@aztec-labs/foundation/branded-types';
442
+ import { randomInt } from '@aztec-labs/foundation/crypto/random';
443
+ import { flipSignature, generateRecoverableSignature, generateUnrecoverableSignature } from '@aztec-labs/foundation/crypto/secp256k1-signer';
444
+ import { InterruptError, TimeoutError } from '@aztec-labs/foundation/error';
445
+ import { filter } from '@aztec-labs/foundation/iterator';
446
+ import { createLogger } from '@aztec-labs/foundation/log';
447
+ import { InterruptibleSleep } from '@aztec-labs/foundation/sleep';
448
+ import { Timer } from '@aztec-labs/foundation/timer';
449
+ import { isErrorClass, unfreeze } from '@aztec-labs/foundation/types';
450
+ import { CommitteeAttestationsAndSigners, MaliciousCommitteeAttestationsAndSigners, MaliciousYParityCommitteeAttestationsAndSigners } from '@aztec-labs/stdlib/block';
451
+ import { buildCheckpointSimulationOverridesPlan, getPreviousCheckpointInboxRollingHash, getPreviousCheckpointOutHashes, validateCheckpoint } from '@aztec-labs/stdlib/checkpoint';
452
+ import { computeQuorum, getTimestampForSlot } from '@aztec-labs/stdlib/epoch-helpers';
453
+ import { Gas } from '@aztec-labs/stdlib/gas';
454
+ import { InsufficientValidTxsError } from '@aztec-labs/stdlib/interfaces/server';
455
+ import { InboxBucketRef, getInboxCutoffTimestamp, isInboxConsumptionSufficient } from '@aztec-labs/stdlib/messaging';
456
+ import { orderAttestations, trimAttestations } from '@aztec-labs/stdlib/p2p';
457
+ import { MerkleTreeId } from '@aztec-labs/stdlib/trees';
458
+ import { AttestationTimeoutError } from '@aztec-labs/stdlib/validators';
459
+ import { Attributes, trackSpan } from '@aztec-labs/telemetry-client';
460
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec-labs/validator-ha-signer/errors';
461
+ import { CheckpointVoter } from './checkpoint_voter.js';
462
+ import { SequencerInterruptedError } from './errors.js';
463
+ import { selectInboxBucketForBlock } from './inbox_bucket_selector.js';
464
+ import { SequencerState } from './utils.js';
465
+ /** How much time to sleep while waiting for min transactions to accumulate for a block */ const TXS_POLLING_MS = 500;
466
+ const ARCHIVER_SYNC_POLLING_MS = 200;
467
+ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('CheckpointProposalJob.proposeCheckpoint', function() {
468
+ return {
469
+ // nullish operator needed for tests
470
+ [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
471
+ [Attributes.SLOT_NUMBER]: this.targetSlot
472
+ };
473
+ }), _dec2 = trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint'), _dec3 = trackSpan('CheckpointProposalJob.waitUntilNextSubslot'), _dec4 = trackSpan('CheckpointProposalJob.buildSingleBlock'), _dec5 = trackSpan('CheckpointProposalJob.waitForMinTxs'), _dec6 = trackSpan('CheckpointProposalJob.waitForAttestations');
474
+ /**
475
+ * Handles the execution of a checkpoint proposal after the initial preparation phase.
476
+ * This includes building blocks, collecting attestations, and publishing the checkpoint to L1,
477
+ * as well as enqueueing votes for slashing and governance proposals. This class is created from
478
+ * the Sequencer once the check for being the proposer for the slot has succeeded.
479
+ */ export class CheckpointProposalJob {
480
+ targetSlot;
481
+ targetEpoch;
482
+ checkpointNumber;
483
+ syncedToBlockNumber;
484
+ checkpointedCheckpointNumber;
485
+ proposer;
486
+ publisher;
487
+ attestorAddress;
488
+ invalidateCheckpoint;
489
+ validatorClient;
490
+ globalsBuilder;
491
+ p2pClient;
492
+ worldState;
493
+ l1ToL2MessageSource;
494
+ l2BlockSource;
495
+ checkpointsBuilder;
496
+ blockSink;
497
+ l1Constants;
498
+ signatureContext;
499
+ config;
500
+ timetable;
501
+ slasherClient;
502
+ epochCache;
503
+ dateProvider;
504
+ metrics;
505
+ checkpointMetrics;
506
+ eventEmitter;
507
+ pendingRequests;
508
+ setStateFn;
509
+ tracer;
510
+ proposedCheckpointData;
511
+ static{
512
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
513
+ [
514
+ _dec,
515
+ 2,
516
+ "execute"
517
+ ],
518
+ [
519
+ _dec1,
520
+ 2,
521
+ "proposeCheckpoint"
522
+ ],
523
+ [
524
+ _dec2,
525
+ 2,
526
+ "buildBlocksForCheckpoint"
527
+ ],
528
+ [
529
+ _dec3,
530
+ 2,
531
+ "waitUntilNextSubslot"
532
+ ],
533
+ [
534
+ _dec4,
535
+ 2,
536
+ "buildSingleBlock"
537
+ ],
538
+ [
539
+ _dec5,
540
+ 2,
541
+ "waitForMinTxs"
542
+ ],
543
+ [
544
+ _dec6,
545
+ 2,
546
+ "waitForAttestations"
547
+ ]
548
+ ], []));
549
+ }
550
+ log;
551
+ checkpointEventLog;
552
+ interruptibleSleep;
553
+ interrupted;
554
+ /**
555
+ * Chain state overrides built once per slot in proposeCheckpoint after the checkpoint is
556
+ * complete. Carries the pending parent override (archive + slot + fee header) for pipelining,
557
+ * or the invalidation pending override when rolling back. Consumed by
558
+ * publisher.validateCheckpointHeader before broadcast.
559
+ */ checkpointSimulationOverridesPlan;
560
+ getSignatureContext() {
561
+ return this.signatureContext;
562
+ }
563
+ constructor(targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, checkpointedCheckpointNumber, // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
564
+ proposer, publisher, attestorAddress, invalidateCheckpoint, validatorClient, globalsBuilder, p2pClient, worldState, l1ToL2MessageSource, l2BlockSource, checkpointsBuilder, blockSink, l1Constants, signatureContext, config, timetable, slasherClient, epochCache, dateProvider, metrics, checkpointMetrics, eventEmitter, // Shared with the owning sequencer, which drains it during shutdown; the fire-and-forget L1
565
+ // submission this job backgrounds is tracked here rather than in a job-local tracker.
566
+ pendingRequests, setStateFn, tracer, bindings, proposedCheckpointData){
567
+ this.targetSlot = targetSlot;
568
+ this.targetEpoch = targetEpoch;
569
+ this.checkpointNumber = checkpointNumber;
570
+ this.syncedToBlockNumber = syncedToBlockNumber;
571
+ this.checkpointedCheckpointNumber = checkpointedCheckpointNumber;
572
+ this.proposer = proposer;
573
+ this.publisher = publisher;
574
+ this.attestorAddress = attestorAddress;
575
+ this.invalidateCheckpoint = invalidateCheckpoint;
576
+ this.validatorClient = validatorClient;
577
+ this.globalsBuilder = globalsBuilder;
578
+ this.p2pClient = p2pClient;
579
+ this.worldState = worldState;
580
+ this.l1ToL2MessageSource = l1ToL2MessageSource;
581
+ this.l2BlockSource = l2BlockSource;
582
+ this.checkpointsBuilder = checkpointsBuilder;
583
+ this.blockSink = blockSink;
584
+ this.l1Constants = l1Constants;
585
+ this.signatureContext = signatureContext;
586
+ this.config = config;
587
+ this.timetable = timetable;
588
+ this.slasherClient = slasherClient;
589
+ this.epochCache = epochCache;
590
+ this.dateProvider = dateProvider;
591
+ this.metrics = metrics;
592
+ this.checkpointMetrics = checkpointMetrics;
593
+ this.eventEmitter = eventEmitter;
594
+ this.pendingRequests = pendingRequests;
595
+ this.setStateFn = setStateFn;
596
+ this.tracer = tracer;
597
+ this.proposedCheckpointData = proposedCheckpointData;
598
+ this.interruptibleSleep = (_initProto(this), new InterruptibleSleep());
599
+ this.interrupted = false;
600
+ this.log = createLogger('sequencer:checkpoint-proposal', {
601
+ ...bindings,
602
+ instanceId: `slot-${this.getBuildSlot()}`
603
+ });
604
+ this.checkpointEventLog = createLogger('sequencer:checkpoint-events', {
605
+ ...bindings,
606
+ instanceId: `slot-${this.getBuildSlot()}`
607
+ });
608
+ }
609
+ /**
610
+ * The wall-clock slot during which this job builds, i.e. the slot one before {@link targetSlot} under
611
+ * proposer pipelining. Also the slot of the parent checkpoint this job builds on top of.
612
+ */ getBuildSlot() {
613
+ return SlotNumber(this.targetSlot - PROPOSER_PIPELINING_SLOT_OFFSET);
614
+ }
615
+ /**
616
+ * Sets the sequencer state for this job, reporting the target slot the checkpoint is being proposed for
617
+ * (not the wall-clock build slot). The slot is informational on the event payload/metrics; the job knows
618
+ * its own target slot, so callers only pass the state.
619
+ */ setState(state) {
620
+ this.setStateFn(state, this.targetSlot);
621
+ }
622
+ /** Interrupts job-owned waits, including the publisher's send-at-slot sleep, so shutdown can finish. */ interrupt() {
623
+ this.interrupted = true;
624
+ this.interruptibleSleep.interrupt(true);
625
+ this.publisher.interrupt();
626
+ }
627
+ async awaitInterruptibleSleep(ms) {
628
+ if (this.interrupted) {
629
+ throw new SequencerInterruptedError();
630
+ }
631
+ if (ms <= 0) {
632
+ return;
633
+ }
634
+ try {
635
+ await this.interruptibleSleep.sleep(ms);
636
+ } catch (err) {
637
+ if (err instanceof InterruptError) {
638
+ throw new SequencerInterruptedError();
639
+ }
640
+ throw err;
641
+ }
642
+ }
643
+ logCheckpointEvent(eventName, message, fields) {
644
+ this.checkpointEventLog.debug(message, {
645
+ eventName: `sequencer-checkpoint-${eventName}`,
646
+ ...fields
647
+ });
648
+ }
649
+ /**
650
+ * Executes the checkpoint proposal job.
651
+ * Builds blocks, assembles checkpoint, and broadcasts the proposal (blocking).
652
+ * Attestation collection, signing, and L1 submission are backgrounded so the
653
+ * work loop can return to IDLE immediately for consecutive slot proposals.
654
+ * Returns the built checkpoint if successful, undefined otherwise.
655
+ */ async execute() {
656
+ // Enqueue governance and slashing votes (returns promises that will be awaited later)
657
+ // In fisherman mode, we simulate slashing but don't actually publish to L1
658
+ // These are constant for the whole slot, so we only enqueue them once
659
+ const votesPromises = new CheckpointVoter(this.targetSlot, this.publisher, this.attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log).enqueueVotes();
660
+ // Build blocks, assemble checkpoint, and broadcast proposal (BLOCKING).
661
+ // Returns after broadcast — attestation collection is deferred.
662
+ const broadcast = await this.proposeCheckpoint();
663
+ if (!broadcast) {
664
+ await Promise.all(votesPromises);
665
+ // Still submit votes even without a checkpoint.
666
+ // Under proposer pipelining, vote-offenses signatures are EIP-712-bound to `targetSlot`
667
+ // (the pipelined slot in which the multicall is expected to mine). Submitting at the
668
+ // wall-clock time would let the multicall mine in a different L2 slot, causing
669
+ // signature verification to fail silently inside Multicall3. Delay submission to the
670
+ // start of `targetSlot` so the tx mines in the slot the vote was signed for.
671
+ if (!this.config.fishermanMode) {
672
+ this.pendingRequests.trackRequest(this.publisher.sendRequestsAt(this.targetSlot), ()=>this.interrupt());
673
+ }
674
+ return undefined;
675
+ }
676
+ const { checkpoint } = broadcast;
677
+ this.metrics.recordCheckpointProposalSuccess();
678
+ // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
679
+ if (this.config.fishermanMode) {
680
+ await this.handleCheckpointEndAsFisherman(checkpoint);
681
+ return checkpoint;
682
+ }
683
+ // Background the attestation → signing → L1 pipeline so the work loop is unblocked
684
+ this.pendingRequests.trackRequest(this.waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises), ()=>this.interrupt());
685
+ // Return the built checkpoint immediately — the work loop is now unblocked
686
+ return checkpoint;
687
+ }
688
+ /**
689
+ * Background pipeline: collects attestations, signs them, enqueues the checkpoint, and submits to L1.
690
+ * Runs as a fire-and-forget task tracked in the sequencer's shared tracker so the work loop is unblocked.
691
+ */ async waitForAttestationsAndEnqueueSubmissionAsync(broadcast, votesPromises) {
692
+ const { checkpoint } = broadcast;
693
+ // The bucket the checkpoint consumed through, from the streaming cursor. Sourcing it from the held last-block
694
+ // proposal is wrong: when the checkpoint's final block fails to build after earlier blocks already consumed
695
+ // messages, no block is held, so the hint would fall back to genesis bucket 0 while the header commits to a
696
+ // non-genesis rolling hash, which L1 rejects with Rollup__InvalidInboxRollingHash.
697
+ const bucketHint = broadcast.bucketHint;
698
+ try {
699
+ // Wait for all votes actions, enqueued at the beginning, to resolve
700
+ await Promise.all(votesPromises);
701
+ // Try to collect attestations from the committee
702
+ const signedAttestations = await this.getSignedCommitteeAttestations(broadcast);
703
+ // Wait for the previous checkpoint to land on L1 before submitting, so we can check it
704
+ // matches the proposed checkpoint we used as parent, and has valid attestations.
705
+ if (signedAttestations && await this.waitForValidParentCheckpointOnL1()) {
706
+ await this.enqueueCheckpointForSubmission({
707
+ checkpoint,
708
+ ...signedAttestations,
709
+ bucketHint
710
+ });
711
+ }
712
+ // If we failed to collect attestations, at least check if we need to issue an invalidation
713
+ if (!signedAttestations && await this.waitForSyncedL2SlotNumber(this.getBuildSlot())) {
714
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
715
+ if (!validationStatus.valid) {
716
+ this.log.warn(`Checkpoint ${validationStatus.checkpoint.checkpointNumber} has invalid attestations, enqueuing invalidation in spite of attestation collection failure`, {
717
+ checkpoint: validationStatus.checkpoint,
718
+ reason: validationStatus.reason
719
+ });
720
+ await this.enqueueInvalidation(validationStatus);
721
+ }
722
+ }
723
+ // Send whatever was enqueued: votes + (propose | invalidation | nothing).
724
+ const l1Response = await this.publisher.sendRequestsAt(this.targetSlot);
725
+ const proposedAction = l1Response?.successfulActions.find((a)=>a === 'propose');
726
+ if (proposedAction) {
727
+ this.logCheckpointEvent('published', `Checkpoint published for slot ${this.targetSlot}`, {
728
+ slot: this.targetSlot,
729
+ checkpointNumber: this.checkpointNumber,
730
+ successfulActions: l1Response?.successfulActions,
731
+ sentActions: l1Response?.sentActions
732
+ });
733
+ this.eventEmitter.emit('checkpoint-published', {
734
+ checkpoint: this.checkpointNumber,
735
+ slot: this.targetSlot
736
+ });
737
+ const coinbase = checkpoint.header.coinbase;
738
+ await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
739
+ } else {
740
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
741
+ slot: this.targetSlot,
742
+ checkpointNumber: this.checkpointNumber,
743
+ successfulActions: l1Response?.successfulActions,
744
+ failedActions: l1Response?.failedActions,
745
+ sentActions: l1Response?.sentActions,
746
+ expiredActions: l1Response?.expiredActions,
747
+ reason: 'propose_action_not_successful'
748
+ });
749
+ this.log.warn(`Checkpoint publish failed for slot ${this.targetSlot}`, {
750
+ slot: this.targetSlot,
751
+ checkpointNumber: this.checkpointNumber,
752
+ successfulActions: l1Response?.successfulActions,
753
+ failedActions: l1Response?.failedActions,
754
+ sentActions: l1Response?.sentActions,
755
+ expiredActions: l1Response?.expiredActions,
756
+ reason: 'propose_action_not_successful'
757
+ });
758
+ this.eventEmitter.emit('checkpoint-publish-failed', {
759
+ ...l1Response,
760
+ slot: this.targetSlot
761
+ });
762
+ this.metrics.recordPipelineDiscard();
763
+ }
764
+ } catch (err) {
765
+ if (err instanceof SequencerInterruptedError) {
766
+ return;
767
+ }
768
+ this.logCheckpointEvent('publish-failed', `Checkpoint publish failed for slot ${this.targetSlot}`, {
769
+ slot: this.targetSlot,
770
+ checkpointNumber: this.checkpointNumber,
771
+ reason: err instanceof Error ? err.message : String(err)
772
+ });
773
+ this.log.error(`Background attestation/L1 pipeline failed for slot ${this.targetSlot}`, err, {
774
+ slot: this.targetSlot,
775
+ checkpointNumber: this.checkpointNumber,
776
+ reason: err instanceof Error ? err.message : String(err)
777
+ });
778
+ this.eventEmitter.emit('checkpoint-publish-failed', {
779
+ slot: this.targetSlot
780
+ });
781
+ this.metrics.recordPipelineDiscard();
782
+ }
783
+ }
784
+ /** Enqueues the checkpoint for L1 submission. Called after pipeline sleep in execute(). */ async enqueueCheckpointForSubmission(result) {
785
+ const { checkpoint, attestations, attestationsSignature, bucketHint } = result;
786
+ this.setState(SequencerState.PUBLISHING_CHECKPOINT);
787
+ // Latest L1 block the propose can still land in for the target slot: the last Ethereum block inside
788
+ // the target slot (`target_slot_start + S - E`). This is one ethereum slot later than
789
+ // `attestation_deadline` (= last_ethereum_block_in_target_slot - E), which bounds when validators must
790
+ // have signed, not when the proposer must have sent. Using the attestation deadline here is too tight:
791
+ // attestations are collected up to (and, when not enforcing, past) it, so the propose tx would be
792
+ // enqueued already expired and time out before it can mine.
793
+ const lastL1BlockInTargetSlot = Number(getTimestampForSlot(this.targetSlot, this.l1Constants)) + this.l1Constants.slotDuration - this.l1Constants.ethereumSlotDuration;
794
+ const txTimeoutAt = new Date(lastL1BlockInTargetSlot * 1000);
795
+ // If we have been configured to potentially skip publishing checkpoint then roll the dice here
796
+ if (this.config.skipPublishingCheckpointsPercent !== undefined && this.config.skipPublishingCheckpointsPercent > 0) {
797
+ const roll = Math.max(0, randomInt(100));
798
+ if (roll < this.config.skipPublishingCheckpointsPercent) {
799
+ this.log.warn(`Skipping publishing proposal for checkpoint ${checkpoint.number}. Configured percentage: ${this.config.skipPublishingCheckpointsPercent}, generated value: ${roll}`);
800
+ return;
801
+ }
802
+ }
803
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, bucketHint, {
804
+ txTimeoutAt
805
+ });
806
+ }
807
+ /**
808
+ * Wait until the archiver syncs past the given L2 slot number.
809
+ * The deadline is the end of `this.targetSlot`, beyond which any pipelined work would miss its
810
+ * L1 submission window and is no longer useful.
811
+ */ async waitForSyncedL2SlotNumber(waitForSlot) {
812
+ const targetSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
813
+ const targetSlotEndMs = (targetSlotStart + this.l1Constants.slotDuration) * 1000;
814
+ const syncDelayTolerance = this.l1Constants.ethereumSlotDuration * 2 * 1000;
815
+ const timeoutSeconds = Math.max(0.1, (targetSlotEndMs + syncDelayTolerance - this.dateProvider.now()) / 1000);
816
+ try {
817
+ const timer = new Timer();
818
+ while(true){
819
+ const syncedSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
820
+ if (syncedSlot !== undefined && syncedSlot >= waitForSlot) {
821
+ return true;
822
+ }
823
+ if (timeoutSeconds && timer.s() > timeoutSeconds) {
824
+ throw new TimeoutError(`Timeout awaiting archiver sync past slot ${waitForSlot}`);
825
+ }
826
+ await this.awaitInterruptibleSleep(ARCHIVER_SYNC_POLLING_MS);
827
+ }
828
+ } catch (err) {
829
+ if (err instanceof SequencerInterruptedError) {
830
+ throw err;
831
+ }
832
+ this.log.warn(`Archiver did not sync L1 past slot ${waitForSlot} before slot ${this.targetSlot} expired, discarding pipelined work`, {
833
+ checkpointNumber: this.checkpointNumber
834
+ });
835
+ this.emitPipelinedCheckpointDiscarded('archiver-sync-timeout');
836
+ return false;
837
+ }
838
+ }
839
+ /**
840
+ * Waits for the parent checkpoint to land on L1 before submitting a pipelined checkpoint.
841
+ * Polls until the archiver has synced L1 past the parent's slot, then verifies:
842
+ * - If we built on a proposed parent: it must have landed on L1 with matching hash and valid attestations.
843
+ * - If we built without a proposed parent: no new checkpoint must have appeared for that slot.
844
+ * If the parent has invalid attestations, enqueues an invalidation. Returns whether to proceed with the proposal.
845
+ */ async waitForValidParentCheckpointOnL1() {
846
+ if (this.config.skipWaitForValidParentCheckpointOnL1) {
847
+ this.log.warn(`Skipping waitForValidParentCheckpointOnL1 due to test configuration`, {
848
+ checkpointNumber: this.checkpointNumber
849
+ });
850
+ return true;
851
+ }
852
+ const parentCheckpointNumber = CheckpointNumber(this.checkpointNumber - 1);
853
+ // Wait until archiver has synced L1 past the parent's slot (the build slot, one before targetSlot)
854
+ if (!await this.waitForSyncedL2SlotNumber(this.getBuildSlot())) {
855
+ return false;
856
+ }
857
+ const tips = await this.l2BlockSource.getL2Tips();
858
+ const checkpointedNumber = tips.checkpointed.checkpoint.number;
859
+ // We built on top of a proposed checkpoint. Verify it landed on L1 as expected.
860
+ if (this.proposedCheckpointData) {
861
+ // After syncing from L1 we see the chain tip has invalid attestations. This means the parent checkpoint was posted
862
+ // with invalid attestations, or it built on top of something with invalid attestations and didnt invalidate them.
863
+ // Either way, we thought our parent would be valid, so we have to throw away our work. But at least we'll try and
864
+ // invalidate on L1 so we clean up the chain for the next proposer. And we'll slash them, but that's handled elsewhere.
865
+ const validationStatus = await this.l2BlockSource.getPendingChainValidationStatus();
866
+ if (!validationStatus.valid) {
867
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} has invalid attestations, discarding pipelined work`, {
868
+ checkpointNumber: this.checkpointNumber,
869
+ reason: validationStatus.reason
870
+ });
871
+ this.emitPipelinedCheckpointDiscarded('parent-invalid-attestations');
872
+ await this.enqueueInvalidation(validationStatus);
873
+ return false;
874
+ }
875
+ // The pending chain is valid. But did the parent checkpoint land on L1 at all?
876
+ if (checkpointedNumber < parentCheckpointNumber) {
877
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} did not land on L1, discarding pipelined work`, {
878
+ checkpointNumber: this.checkpointNumber,
879
+ checkpointedNumber
880
+ });
881
+ this.emitPipelinedCheckpointDiscarded('parent-not-on-l1');
882
+ return false;
883
+ }
884
+ // It landed. But is it the one we were expecting?
885
+ const expectedHash = this.proposedCheckpointData.header.hash().toString();
886
+ if (tips.checkpointed.checkpoint.hash !== expectedHash) {
887
+ this.log.warn(`Parent checkpoint ${parentCheckpointNumber} hash mismatch on L1, discarding pipelined work`, {
888
+ checkpointNumber: this.checkpointNumber,
889
+ expectedHash,
890
+ actualHash: tips.checkpointed.checkpoint.hash
891
+ });
892
+ this.emitPipelinedCheckpointDiscarded('parent-hash-mismatch');
893
+ return false;
894
+ }
895
+ return true;
896
+ } else {
897
+ // We didn't see a proposed checkpoint at build time, so we built on checkpointed parent from two slots ago.
898
+ // But if a new checkpoint for the previous slot appeared on L1 in the meantime, our checkpoint assumed the wrong parent,
899
+ // so we have to discard our work. This can happen if we're somehow cut off from p2p and fail to see the checkpoint
900
+ // proposal for the previous slot.
901
+ if (checkpointedNumber > parentCheckpointNumber) {
902
+ this.log.warn(`Unexpected checkpoint ${checkpointedNumber} landed on L1 after we built on top of parent ${parentCheckpointNumber}, discarding pipelined work`, {
903
+ checkpointNumber: this.checkpointNumber,
904
+ checkpointedNumber
905
+ });
906
+ this.emitPipelinedCheckpointDiscarded('unexpected-parent-appeared');
907
+ return false;
908
+ }
909
+ return true;
910
+ }
911
+ }
912
+ /** Emits the pipelined-checkpoint-discarded event and records the metric. */ emitPipelinedCheckpointDiscarded(reason) {
913
+ this.metrics.recordPipelineParentCheckpointMismatch(reason);
914
+ this.eventEmitter.emit('pipelined-checkpoint-discarded', {
915
+ slot: this.targetSlot,
916
+ checkpointNumber: this.checkpointNumber,
917
+ reason
918
+ });
919
+ }
920
+ /** Simulates and enqueues an invalidation request for the invalid parent checkpoint. */ async enqueueInvalidation(validationStatus) {
921
+ if (this.config.skipInvalidateBlockAsProposer) {
922
+ this.log.warn(`Skipping checkpoint invalidation as proposer due to test configuration`);
923
+ return;
924
+ }
925
+ const invalidateRequest = await this.publisher.simulateInvalidateCheckpoint(validationStatus);
926
+ if (invalidateRequest) {
927
+ const submissionSlotStart = Number(getTimestampForSlot(this.targetSlot, this.l1Constants));
928
+ const txTimeoutAt = new Date((submissionSlotStart + this.l1Constants.slotDuration) * 1000);
929
+ this.publisher.enqueueInvalidateCheckpoint(invalidateRequest, {
930
+ txTimeoutAt
931
+ });
932
+ } else {
933
+ this.log.info(`Invalidation simulation returned undefined, checkpoint may have been removed already`, {
934
+ checkpointNumber: this.checkpointNumber
935
+ });
936
+ }
937
+ }
938
+ async proposeCheckpoint() {
939
+ try {
940
+ const env = {
941
+ stack: [],
942
+ error: void 0,
943
+ hasError: false
944
+ };
945
+ try {
946
+ const now = this.dateProvider.now();
947
+ if (this.proposedCheckpointData) {
948
+ // Measure against the wall-clock slot whose build window we are currently using.
949
+ // In pipelining mode `targetSlot` is intentionally one slot ahead, which makes the
950
+ // target-slot boundary a full slot away from the actual build start time.
951
+ const slotBoundaryMs = Number(getTimestampForSlot(this.getBuildSlot(), this.l1Constants)) * 1000;
952
+ this.checkpointMetrics.recordPipelinedCheckpointBuildStartOffsetFromSlotBoundary(now - slotBoundaryMs);
953
+ }
954
+ this.checkpointMetrics.startCheckpointTiming(now);
955
+ // Get operator configured coinbase and fee recipient for this attestor
956
+ const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
957
+ const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
958
+ // Start the checkpoint
959
+ this.setState(SequencerState.INITIALIZING_CHECKPOINT);
960
+ this.logCheckpointEvent('slot-started', `Starting checkpoint proposal for slot ${this.targetSlot}`, {
961
+ buildSlot: this.getBuildSlot(),
962
+ submissionSlot: this.targetSlot,
963
+ slot: this.targetSlot,
964
+ checkpointNumber: this.checkpointNumber,
965
+ proposer: this.proposer?.toString(),
966
+ attestorAddress: this.attestorAddress.toString(),
967
+ publisherAddress: this.publisher.getSenderAddress().toString(),
968
+ coinbase: coinbase.toString()
969
+ });
970
+ this.metrics.incOpenSlot(this.targetSlot, this.proposer?.toString() ?? 'unknown');
971
+ // Enqueues checkpoint invalidation (constant for the whole slot)
972
+ if (this.invalidateCheckpoint && !this.config.skipInvalidateBlockAsProposer) {
973
+ this.publisher.enqueueInvalidateCheckpoint(this.invalidateCheckpoint);
974
+ }
975
+ // Build the simulation plan for this slot. When pipelining, this overrides L1's view of
976
+ // pending/archive/fee-header to "as if the proposed parent had landed", so both the
977
+ // mana-min-fee simulation (in the globals builder) and the pre-broadcast
978
+ // validateCheckpointHeader see the chain tip the eventual L1 send will see.
979
+ this.checkpointSimulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
980
+ checkpointNumber: this.checkpointNumber,
981
+ proposedCheckpointData: this.proposedCheckpointData,
982
+ invalidateToPendingCheckpointNumber: this.invalidateCheckpoint?.forcePendingCheckpointNumber,
983
+ checkpointedCheckpointNumber: this.checkpointedCheckpointNumber,
984
+ rollup: this.publisher.rollupContract,
985
+ signatureContext: this.signatureContext,
986
+ log: this.log
987
+ });
988
+ const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(coinbase, feeRecipient, this.targetSlot, this.checkpointSimulationOverridesPlan);
989
+ // Collect the out hashes of all the checkpoints before this one in the same epoch.
990
+ // Under pipelining the parent checkpoint may not be on L1 yet at build time, so the helper
991
+ // splices in the parent's checkpointOutHash from the locally-known proposed checkpoint so
992
+ // the resulting `epochOutHash` matches what validators (and L1) compute once the parent
993
+ // lands on L1.
994
+ const previousCheckpointOutHashes = await getPreviousCheckpointOutHashes({
995
+ blockSource: this.l2BlockSource,
996
+ epoch: this.targetEpoch,
997
+ checkpointNumber: this.checkpointNumber,
998
+ l1Constants: this.epochCache.getL1Constants(),
999
+ pipeliningEnabled: true,
1000
+ proposedCheckpointData: this.proposedCheckpointData,
1001
+ log: this.log
1002
+ });
1003
+ // Chain start for this checkpoint's inbox rolling hash: the parent checkpoint's `inboxRollingHash`. Unlike the
1004
+ // epoch out-hash tree, the chain is continuous across epochs, so this is always the immediately preceding
1005
+ // checkpoint's value (or zero at genesis).
1006
+ const previousInboxRollingHash = await getPreviousCheckpointInboxRollingHash({
1007
+ blockSource: this.l2BlockSource,
1008
+ checkpointNumber: this.checkpointNumber,
1009
+ proposedCheckpointData: this.proposedCheckpointData,
1010
+ log: this.log
1011
+ });
1012
+ // Anchor the modifier to the predicted parent fee header: L1 will apply it against
1013
+ // that, not against the latest published checkpoint (which lags by one under pipelining).
1014
+ const predictedParentEthPerFeeAssetE12 = this.checkpointSimulationOverridesPlan?.pendingCheckpointState?.feeHeader?.ethPerFeeAsset;
1015
+ const feeAssetPriceModifier = await this.publisher.getFeeAssetPriceModifier(predictedParentEthPerFeeAssetE12);
1016
+ const fork = _ts_add_disposable_resource(env, await this.worldState.fork(this.syncedToBlockNumber, {
1017
+ closeDelayMs: 12_000
1018
+ }), true);
1019
+ // Streaming Inbox: the consumption cursor starts at the parent state this checkpoint builds on. The fork's
1020
+ // L1-to-L2 tree leaf count is the parent's cumulative consumed total (compact indexing), which resolves the
1021
+ // parent's last-consumed bucket.
1022
+ const streamingState = await this.resolveStreamingCheckpointStart(fork);
1023
+ // Create checkpoint builder for the entire slot
1024
+ const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(this.checkpointNumber, checkpointGlobalVariables, feeAssetPriceModifier, previousCheckpointOutHashes, previousInboxRollingHash, fork, this.log.getBindings());
1025
+ // Options for the validator client when creating block and checkpoint proposals
1026
+ const blockProposalOptions = {
1027
+ publishFullTxs: !!this.config.publishTxsWithProposals,
1028
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
1029
+ };
1030
+ const checkpointProposalOptions = {
1031
+ publishFullTxs: !!this.config.publishTxsWithProposals,
1032
+ broadcastInvalidCheckpointProposal: this.config.broadcastInvalidCheckpointProposalOnly || this.config.broadcastInvalidBlockProposal
1033
+ };
1034
+ let blocksInCheckpoint = [];
1035
+ let blockPendingBroadcast = undefined;
1036
+ const checkpointBuildTimer = new Timer();
1037
+ try {
1038
+ // Main loop: build blocks for the checkpoint
1039
+ const result = await this.buildBlocksForCheckpoint(checkpointBuilder, checkpointGlobalVariables.timestamp, blockProposalOptions, streamingState);
1040
+ blocksInCheckpoint = result.blocksInCheckpoint;
1041
+ blockPendingBroadcast = result.blockPendingBroadcast;
1042
+ } catch (err) {
1043
+ // These errors are expected in HA mode, so we yield and let another HA node handle the slot
1044
+ // The only distinction between the 2 errors is SlashingProtectionError throws when the payload is different,
1045
+ // which is normal for block building (may have picked different txs)
1046
+ if (this.handleHASigningError(err, 'Block proposal')) {
1047
+ return undefined;
1048
+ }
1049
+ throw err;
1050
+ }
1051
+ if (blocksInCheckpoint.length === 0) {
1052
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
1053
+ slot: this.targetSlot,
1054
+ checkpointNumber: this.checkpointNumber,
1055
+ reason: 'no_blocks_built'
1056
+ });
1057
+ this.log.warn(`No blocks were built for slot ${this.targetSlot}`, {
1058
+ slot: this.targetSlot,
1059
+ checkpointNumber: this.checkpointNumber,
1060
+ reason: 'no_blocks_built'
1061
+ });
1062
+ this.eventEmitter.emit('checkpoint-empty', {
1063
+ slot: this.targetSlot
1064
+ });
1065
+ return undefined;
1066
+ }
1067
+ const minBlocksForCheckpoint = this.config.minBlocksForCheckpoint;
1068
+ if (minBlocksForCheckpoint !== undefined && blocksInCheckpoint.length < minBlocksForCheckpoint) {
1069
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
1070
+ slot: this.targetSlot,
1071
+ checkpointNumber: this.checkpointNumber,
1072
+ blocksBuilt: blocksInCheckpoint.length,
1073
+ minBlocksForCheckpoint,
1074
+ reason: 'min_blocks_not_met'
1075
+ });
1076
+ this.log.warn(`Checkpoint has fewer blocks than minimum (${blocksInCheckpoint.length} < ${minBlocksForCheckpoint}), skipping proposal`, {
1077
+ slot: this.targetSlot,
1078
+ checkpointNumber: this.checkpointNumber,
1079
+ blocksBuilt: blocksInCheckpoint.length,
1080
+ minBlocksForCheckpoint,
1081
+ reason: 'min_blocks_not_met'
1082
+ });
1083
+ return undefined;
1084
+ }
1085
+ // Streaming Inbox censorship floor: re-derive the mandatory-consumption verdict from the final consumed
1086
+ // position, independently of the per-block selection that produced it. Runs before the checkpoint is assembled,
1087
+ // so the held last block and the checkpoint proposal are both still ungossiped and the propose tx is never
1088
+ // sent for a checkpoint L1 would revert and validators would refuse to attest.
1089
+ const consumption = await this.checkCheckpointConsumption(streamingState);
1090
+ if (!consumption.sufficient) {
1091
+ const { cutoffTimestamp, nextBucket } = consumption;
1092
+ const context = {
1093
+ slot: this.targetSlot,
1094
+ checkpointNumber: this.checkpointNumber,
1095
+ blocksBuilt: blocksInCheckpoint.length,
1096
+ blocksRemaining: this.config.maxBlocksPerCheckpoint - blocksInCheckpoint.length,
1097
+ checkpointStartTotalMsgCount: streamingState.checkpointStartTotalMsgCount,
1098
+ consumedBucketSeq: streamingState.parent.seq,
1099
+ consumedTotalMsgCount: streamingState.parent.totalMsgCount,
1100
+ unconsumedBucketSeq: nextBucket?.seq,
1101
+ unconsumedBucketTotalMsgCount: nextBucket?.totalMsgCount,
1102
+ cutoffTimestamp,
1103
+ reason: 'inbox_consumption_insufficient'
1104
+ };
1105
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, context);
1106
+ this.log.warn(`Checkpoint leaves a mandatory Inbox bucket unconsumed, skipping proposal; the streaming backlog does not ` + `fit ${this.config.maxBlocksPerCheckpoint} blocks per checkpoint`, context);
1107
+ this.metrics.recordCheckpointProposalFailed('inbox_consumption_insufficient');
1108
+ return undefined;
1109
+ }
1110
+ // Assemble and broadcast the checkpoint proposal, including the last block that was not
1111
+ // broadcasted yet, and wait to collect the committee attestations.
1112
+ this.setState(SequencerState.ASSEMBLING_CHECKPOINT);
1113
+ const checkpoint = await checkpointBuilder.completeCheckpoint();
1114
+ // Final validation: per-block limits are only checked if the operator set them explicitly.
1115
+ // Otherwise, checkpoint-level budgets were already enforced by the redistribution logic.
1116
+ try {
1117
+ validateCheckpoint(checkpoint, {
1118
+ rollupManaLimit: this.l1Constants.rollupManaLimit,
1119
+ maxL2BlockGas: this.config.maxL2BlockGas,
1120
+ maxDABlockGas: this.config.maxDABlockGas,
1121
+ maxTxsPerBlock: this.config.maxTxsPerBlock,
1122
+ maxTxsPerCheckpoint: this.config.maxTxsPerCheckpoint
1123
+ });
1124
+ } catch (err) {
1125
+ this.logCheckpointEvent('build-failed', `Checkpoint build failed for slot ${this.targetSlot}`, {
1126
+ slot: this.targetSlot,
1127
+ checkpointNumber: this.checkpointNumber,
1128
+ blocksBuilt: blocksInCheckpoint.length,
1129
+ reason: 'invalid_checkpoint',
1130
+ checkpoint: checkpoint.header.toInspect()
1131
+ });
1132
+ this.log.error(`Built an invalid checkpoint at slot ${this.targetSlot} (skipping proposal)`, err, {
1133
+ slot: this.targetSlot,
1134
+ checkpointNumber: this.checkpointNumber,
1135
+ blocksBuilt: blocksInCheckpoint.length,
1136
+ reason: 'invalid_checkpoint',
1137
+ checkpoint: checkpoint.header.toInspect()
1138
+ });
1139
+ return undefined;
1140
+ }
1141
+ // Record checkpoint-level build metrics
1142
+ this.checkpointMetrics.recordCheckpointBuild(checkpointBuildTimer.ms(), blocksInCheckpoint.length, checkpoint.getStats().txCount, Number(checkpoint.header.totalManaUsed.toBigInt()));
1143
+ this.logCheckpointEvent('built', `Checkpoint built for slot ${this.targetSlot}`, {
1144
+ slot: this.targetSlot,
1145
+ buildSlot: this.getBuildSlot(),
1146
+ checkpointNumber: this.checkpointNumber,
1147
+ proposer: this.proposer?.toString(),
1148
+ attestorAddress: this.attestorAddress.toString(),
1149
+ publisherAddress: this.publisher.getSenderAddress().toString(),
1150
+ blocksBuilt: blocksInCheckpoint.length,
1151
+ txCount: checkpoint.getStats().txCount,
1152
+ totalMana: Number(checkpoint.header.totalManaUsed.toBigInt())
1153
+ });
1154
+ // In fisherman mode, return the checkpoint without broadcasting or collecting attestations
1155
+ if (this.config.fishermanMode) {
1156
+ this.log.info(`Built checkpoint for slot ${this.targetSlot} with ${blocksInCheckpoint.length} blocks. ` + `Skipping proposal in fisherman mode.`, {
1157
+ slot: this.targetSlot,
1158
+ checkpoint: checkpoint.header.toInspect(),
1159
+ blocksBuilt: blocksInCheckpoint.length
1160
+ });
1161
+ this.metrics.recordCheckpointSuccess();
1162
+ // Return a broadcast result with a dummy proposal — fisherman mode skips attestation collection
1163
+ return {
1164
+ checkpoint,
1165
+ proposal: undefined,
1166
+ blockProposedAt: this.dateProvider.now(),
1167
+ bucketHint: streamingState.lastBucketRef.bucketSeq
1168
+ };
1169
+ }
1170
+ // Validate the header against L1 state before broadcasting.
1171
+ // If this fails the slot is aborted before any gossip work; state drift between here
1172
+ // and the eventual L1 send is caught by the bundle simulate at send time.
1173
+ try {
1174
+ await this.publisher.validateCheckpointHeader(checkpoint.header, this.checkpointSimulationOverridesPlan);
1175
+ } catch (err) {
1176
+ this.log.error(`Pre-broadcast header validation failed for slot ${this.targetSlot}; aborting`, err, {
1177
+ slot: this.targetSlot,
1178
+ checkpointNumber: this.checkpointNumber
1179
+ });
1180
+ this.metrics.recordCheckpointProposalFailed('header_validation_failed');
1181
+ this.eventEmitter.emit('header-validation-failed', {
1182
+ slot: this.targetSlot,
1183
+ checkpointNumber: this.checkpointNumber,
1184
+ reason: err instanceof Error ? err.message : String(err)
1185
+ });
1186
+ return undefined;
1187
+ }
1188
+ // Create the checkpoint proposal and broadcast it
1189
+ const proposal = await this.validatorClient.createCheckpointProposal(checkpoint.header, checkpoint.archive.root, this.checkpointNumber, feeAssetPriceModifier, blockPendingBroadcast, this.proposer, checkpointProposalOptions);
1190
+ // Advance our own optimistic proposed-checkpoint tip locally before gossiping. Gossipsub
1191
+ // doesn't echo our own messages back, so this is how the proposer makes its own proposed
1192
+ // checkpoint visible for pipelining the next slot. Built from local checkpoint data — never
1193
+ // from the broadcast proposal archive, which may be deliberately corrupted under test flags.
1194
+ // Fail closed: if this throws, the outer catch aborts the slot before gossiping.
1195
+ await this.syncProposedCheckpointToArchiver(checkpoint, blocksInCheckpoint.length, feeAssetPriceModifier);
1196
+ const blockProposedAt = this.dateProvider.now();
1197
+ if (this.config.skipBroadcastCheckpointProposal) {
1198
+ // Test-only: suppress the CheckpointProposal so peers never see a proposed checkpoint for
1199
+ // this slot, but still broadcast the held last block standalone so peers' archivers ingest
1200
+ // it as a proposed-but-uncheckpointed tip — the exact orphan-block state that
1201
+ // pruneOrphanProposedBlocks / checkSync must handle.
1202
+ if (blockPendingBroadcast && !this.config.skipBroadcastProposals) {
1203
+ await this.p2pClient.broadcastProposal(blockPendingBroadcast);
1204
+ }
1205
+ } else if (!this.config.skipBroadcastProposals) {
1206
+ await this.p2pClient.broadcastCheckpointProposal(proposal);
1207
+ this.checkpointMetrics.noteCheckpointBroadcast(this.dateProvider.now());
1208
+ }
1209
+ // Return immediately after broadcast — attestation collection happens in the background. The bucket hint is
1210
+ // the streaming cursor's final consumed bucket, which matches the header's rolling hash whether or not a last
1211
+ // block was held for broadcast.
1212
+ return {
1213
+ checkpoint,
1214
+ proposal,
1215
+ blockProposedAt,
1216
+ bucketHint: streamingState.lastBucketRef.bucketSeq
1217
+ };
1218
+ } catch (e) {
1219
+ env.error = e;
1220
+ env.hasError = true;
1221
+ } finally{
1222
+ const result = _ts_dispose_resources(env);
1223
+ if (result) await result;
1224
+ }
1225
+ } catch (err) {
1226
+ if (err && (err instanceof DutyAlreadySignedError || err instanceof SlashingProtectionError)) {
1227
+ // swallow this error. It's already been logged by a function deeper in the stack
1228
+ return undefined;
1229
+ }
1230
+ this.log.error(`Error building checkpoint at slot ${this.targetSlot}`, err);
1231
+ return undefined;
1232
+ }
1233
+ }
1234
+ /**
1235
+ * Builds blocks for a checkpoint within the current slot.
1236
+ */ async buildBlocksForCheckpoint(checkpointBuilder, timestamp, blockProposalOptions, streamingState) {
1237
+ const blocksInCheckpoint = [];
1238
+ const txHashesAlreadyIncluded = new Set();
1239
+ const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
1240
+ // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
1241
+ let blockPendingBroadcast = undefined;
1242
+ while(true){
1243
+ const blocksBuilt = blocksInCheckpoint.length;
1244
+ const indexWithinCheckpoint = IndexWithinCheckpoint(blocksBuilt);
1245
+ const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
1246
+ if (blocksBuilt >= this.config.maxBlocksPerCheckpoint) {
1247
+ this.log.debug(`Reached max blocks per checkpoint`, {
1248
+ slot: this.targetSlot,
1249
+ blocksBuilt,
1250
+ maxBlocksPerCheckpoint: this.config.maxBlocksPerCheckpoint
1251
+ });
1252
+ break;
1253
+ }
1254
+ const nowSeconds = this.dateProvider.now() / 1000;
1255
+ const timingInfo = this.timetable.selectNextSubslot(this.targetSlot, nowSeconds);
1256
+ if (!timingInfo.canStart) {
1257
+ this.log.debug(`Not enough time left in slot to start another block`, {
1258
+ slot: this.targetSlot,
1259
+ blocksBuilt,
1260
+ nowSeconds
1261
+ });
1262
+ break;
1263
+ }
1264
+ // Streaming Inbox: select this block's message bundle against the current (not-yet-advanced) consumption
1265
+ // cursor. The state is only advanced once the block builds successfully, so a failed build (retried in a
1266
+ // later sub-slot) re-derives the bundle rather than losing it. The builder inserts the bundle and rolls it
1267
+ // back with the fork on failure. The censorship cutoff floor must apply on whichever block ends the
1268
+ // checkpoint, which includes the block that reaches the per-checkpoint block cap, not just the timetable's
1269
+ // last sub-slot.
1270
+ const isCheckpointFinalBlock = timingInfo.isLastBlock || blocksBuilt + 1 >= this.config.maxBlocksPerCheckpoint;
1271
+ const selection = streamingState ? await this.selectStreamingBundle(streamingState, isCheckpointFinalBlock, nowSeconds) : undefined;
1272
+ // No checkpoint ending on this block can satisfy the censorship floor, so building it would only waste the
1273
+ // sub-slot: stop here and let the post-loop consumption check abort the checkpoint before anything is gossiped.
1274
+ if (selection?.insufficientFinalBlockCapacity) {
1275
+ this.log.warn(`Streaming Inbox backlog does not fit the checkpoint's remaining blocks; stopping block building`, {
1276
+ slot: this.targetSlot,
1277
+ checkpointNumber: this.checkpointNumber,
1278
+ blocksBuilt,
1279
+ blockNumber
1280
+ });
1281
+ break;
1282
+ }
1283
+ const streamingBundle = streamingState ? selection && selection.consume ? selection.bundle : [] : undefined;
1284
+ const buildResult = await this.buildSingleBlock(checkpointBuilder, {
1285
+ // Create all blocks with the same timestamp
1286
+ blockTimestamp: timestamp,
1287
+ // Create an empty block if we haven't already and this is the last one
1288
+ forceCreate: timingInfo.isLastBlock && blocksBuilt === 0 && this.config.buildCheckpointIfEmpty,
1289
+ buildDeadline: new Date(timingInfo.deadline * 1000),
1290
+ blockNumber,
1291
+ indexWithinCheckpoint,
1292
+ txHashesAlreadyIncluded,
1293
+ l1ToL2Messages: streamingBundle
1294
+ });
1295
+ // If we failed to build the block due to insufficient txs, we try again if there is still time left in the slot
1296
+ if ('failure' in buildResult) {
1297
+ // If this was the last subslot, we're done.
1298
+ if (timingInfo.isLastBlock) {
1299
+ break;
1300
+ }
1301
+ // Otherwise, if there is still time for more blocks, we wait until the next subslot and try again
1302
+ await this.waitUntilNextSubslot(timingInfo.deadline);
1303
+ continue;
1304
+ }
1305
+ // If there was an error building the block, we just exit the loop and give up the rest of the slot.
1306
+ // We don't want to risk building more blocks if something went wrong.
1307
+ if ('error' in buildResult) {
1308
+ if (!(buildResult.error instanceof SequencerInterruptedError)) {
1309
+ this.log.warn(`Halting block building for slot ${this.targetSlot}`, {
1310
+ slot: this.targetSlot,
1311
+ blocksBuilt,
1312
+ error: buildResult.error
1313
+ });
1314
+ }
1315
+ break;
1316
+ }
1317
+ const { block, usedTxs } = buildResult;
1318
+ this.checkpointMetrics.noteCheckpointBlockBuilt(this.dateProvider.now(), {
1319
+ isFirstBlock: blocksBuilt === 0,
1320
+ isLastBlock: timingInfo.isLastBlock
1321
+ });
1322
+ blocksInCheckpoint.push(block);
1323
+ usedTxs.forEach((tx)=>txHashesAlreadyIncluded.add(tx.txHash.toString()));
1324
+ // Streaming Inbox: the block built successfully, so advance the consumption cursor and carry this block's
1325
+ // rolling-hash bucket reference. A block that consumed nothing reuses the parent bucket reference.
1326
+ let blockBucketRef = undefined;
1327
+ if (streamingState && selection) {
1328
+ if (selection.consume) {
1329
+ streamingState.parent = {
1330
+ seq: selection.bucket.seq,
1331
+ totalMsgCount: selection.bucket.totalMsgCount
1332
+ };
1333
+ streamingState.lastBucketRef = InboxBucketRef.fromBucket(selection.bucket);
1334
+ }
1335
+ blockBucketRef = streamingState.lastBucketRef;
1336
+ }
1337
+ // Sign the block proposal. This will throw if HA signing fails.
1338
+ const proposal = await this.createBlockProposal(block, usedTxs, {
1339
+ ...blockProposalOptions,
1340
+ broadcastInvalidBlockProposal: blockProposalOptions.broadcastInvalidBlockProposal || block.indexWithinCheckpoint === this.config.invalidBlockProposalIndexWithinCheckpoint
1341
+ }, blockBucketRef);
1342
+ // Sync the proposed block to the archiver to make it available, only after we've managed to sign the proposal,
1343
+ // so we avoid polluting our archive with a block that would fail.
1344
+ // We wait for the sync to succeed, as this helps catch consistency errors, even if it means we lose some time for block-building.
1345
+ // If this throws, we abort the entire checkpoint.
1346
+ await this.syncProposedBlockToArchiver(block);
1347
+ // If this is the last block, do not broadcast it, since it will be included in the checkpoint proposal.
1348
+ if (timingInfo.isLastBlock) {
1349
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.targetSlot}`, {
1350
+ slot: this.targetSlot,
1351
+ blockNumber,
1352
+ blocksBuilt
1353
+ });
1354
+ blockPendingBroadcast = proposal;
1355
+ break;
1356
+ }
1357
+ // Once we have a signed proposal and the archiver agreed with our proposed block, then we broadcast it.
1358
+ if (proposal && !this.config.skipBroadcastProposals) {
1359
+ await this.p2pClient.broadcastProposal(proposal);
1360
+ }
1361
+ // Wait until the next block's start time
1362
+ await this.waitUntilNextSubslot(timingInfo.deadline);
1363
+ }
1364
+ this.log.verbose(`Block building loop completed for slot ${this.targetSlot}`, {
1365
+ slot: this.targetSlot,
1366
+ blocksBuilt: blocksInCheckpoint.length
1367
+ });
1368
+ return {
1369
+ blocksInCheckpoint,
1370
+ blockPendingBroadcast
1371
+ };
1372
+ }
1373
+ /** Creates a block proposal for a given block via the validator client (unless in fisherman mode) */ createBlockProposal(block, usedTxs, blockProposalOptions, bucketRef) {
1374
+ if (this.config.fishermanMode) {
1375
+ this.log.info(`Skipping block proposal for block ${block.number} in fisherman mode`);
1376
+ return Promise.resolve(undefined);
1377
+ }
1378
+ return this.validatorClient.createBlockProposal(block.header, this.checkpointNumber, block.indexWithinCheckpoint, block.archive.root, usedTxs, this.proposer, blockProposalOptions, bucketRef);
1379
+ }
1380
+ /**
1381
+ * Resolves where a streaming-Inbox checkpoint's consumption starts: the parent checkpoint's last-consumed bucket.
1382
+ * The parent's cumulative consumed total is the L1-to-L2 message tree leaf count of the fork
1383
+ * this checkpoint builds on (compact indexing makes leaf count equal cumulative message count), which resolves the
1384
+ * parent bucket by total. Genesis is the `total = 0` case, resolving the genesis bucket 0.
1385
+ */ async resolveStreamingCheckpointStart(fork) {
1386
+ const parentInfo = await fork.getTreeInfo(MerkleTreeId.L1_TO_L2_MESSAGE_TREE);
1387
+ const parentTotalMsgCount = parentInfo.size;
1388
+ const parentBucket = await this.l1ToL2MessageSource.getInboxBucketByTotalMsgCount(parentTotalMsgCount);
1389
+ if (parentBucket === undefined) {
1390
+ throw new Error(`Streaming inbox: cannot resolve parent Inbox bucket for cumulative total ${parentTotalMsgCount} ` + `(checkpoint ${this.checkpointNumber}); local Inbox view has not synced it`);
1391
+ }
1392
+ return {
1393
+ checkpointStartTotalMsgCount: parentTotalMsgCount,
1394
+ parent: {
1395
+ seq: parentBucket.seq,
1396
+ totalMsgCount: parentBucket.totalMsgCount
1397
+ },
1398
+ lastBucketRef: InboxBucketRef.fromBucket(parentBucket)
1399
+ };
1400
+ }
1401
+ /**
1402
+ * Whether the checkpoint's final consumed position satisfies the streaming-Inbox censorship floor, mirroring the
1403
+ * mandatory-consumption assert in `ProposeLib.validateInboxConsumption`: the first bucket left unconsumed must be
1404
+ * absent, past the cutoff, or a cap-escape. The bucket and cutoff the verdict was taken against are returned for
1405
+ * diagnostics.
1406
+ *
1407
+ * Derived from the consumption cursor rather than from the per-block selections that advanced it, so a selector that
1408
+ * stops short of a mandatory bucket is caught here regardless of how it reported the shortfall.
1409
+ */ async checkCheckpointConsumption(state) {
1410
+ const nextBucket = await this.l1ToL2MessageSource.getInboxBucket(state.parent.seq + 1n);
1411
+ const cutoffTimestamp = getInboxCutoffTimestamp(this.targetSlot, this.l1Constants);
1412
+ const sufficient = isInboxConsumptionSufficient({
1413
+ nextBucket,
1414
+ cutoffTimestamp,
1415
+ checkpointStartTotalMsgCount: state.checkpointStartTotalMsgCount,
1416
+ perCheckpointCap: MAX_L1_TO_L2_MSGS_PER_CHECKPOINT
1417
+ });
1418
+ return {
1419
+ sufficient,
1420
+ nextBucket,
1421
+ cutoffTimestamp
1422
+ };
1423
+ }
1424
+ /**
1425
+ * Selects this block's streaming-Inbox message bundle against the current consumption cursor, mirroring the L1
1426
+ * predicate in `ProposeLib.validateInboxConsumption`. Does not mutate the cursor; the caller
1427
+ * advances it only after the block builds successfully.
1428
+ */ selectStreamingBundle(state, isLastBlock, nowSeconds) {
1429
+ const cutoffTimestamp = getInboxCutoffTimestamp(this.targetSlot, this.l1Constants);
1430
+ return selectInboxBucketForBlock({
1431
+ messageSource: this.l1ToL2MessageSource,
1432
+ now: BigInt(Math.floor(nowSeconds)),
1433
+ minBucketAgeSeconds: BigInt(this.l1Constants.ethereumSlotDuration),
1434
+ parent: state.parent,
1435
+ checkpointStartTotalMsgCount: state.checkpointStartTotalMsgCount,
1436
+ perBlockCap: MAX_L1_TO_L2_MSGS_PER_BLOCK,
1437
+ perCheckpointCap: MAX_L1_TO_L2_MSGS_PER_CHECKPOINT,
1438
+ isLastBlock,
1439
+ cutoffTimestamp
1440
+ });
1441
+ }
1442
+ /**
1443
+ * Sleeps until it is time to produce the next block in the slot.
1444
+ * @param nextSubslotStart - Absolute wall-clock timestamp in seconds of the previous sub-slot deadline.
1445
+ */ async waitUntilNextSubslot(nextSubslotStart) {
1446
+ this.setState(SequencerState.WAITING_UNTIL_NEXT_BLOCK);
1447
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s`, {
1448
+ slot: this.targetSlot
1449
+ });
1450
+ await this.awaitInterruptibleSleep(Math.max(0, nextSubslotStart * 1000 - this.dateProvider.now()));
1451
+ }
1452
+ /** Builds a single block. Called from the main block building loop. */ async buildSingleBlock(checkpointBuilder, opts) {
1453
+ const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded, l1ToL2Messages } = opts;
1454
+ this.log.verbose(`Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot}`, {
1455
+ ...checkpointBuilder.getConstantData(),
1456
+ ...opts
1457
+ });
1458
+ try {
1459
+ // Wait until we have enough txs to build the block
1460
+ const { canStartBuilding, minTxs } = await this.waitForMinTxs(opts);
1461
+ if (!canStartBuilding) {
1462
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1463
+ reason: 'insufficient_txs',
1464
+ blockNumber,
1465
+ slot: this.targetSlot,
1466
+ checkpointNumber: this.checkpointNumber,
1467
+ indexWithinCheckpoint,
1468
+ minTxs
1469
+ });
1470
+ this.log.verbose(`Not enough age-eligible txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot} (needs ${minTxs} eligible)`, {
1471
+ reason: 'insufficient_txs',
1472
+ blockNumber,
1473
+ slot: this.targetSlot,
1474
+ checkpointNumber: this.checkpointNumber,
1475
+ indexWithinCheckpoint,
1476
+ minTxs
1477
+ });
1478
+ this.eventEmitter.emit('block-tx-count-check-failed', {
1479
+ minTxs,
1480
+ slot: this.targetSlot
1481
+ });
1482
+ this.metrics.recordBlockProposalFailed('insufficient_txs');
1483
+ return {
1484
+ failure: 'insufficient-txs'
1485
+ };
1486
+ }
1487
+ // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
1488
+ // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
1489
+ // Block building only executes txs, so we skip loading their proofs unless these same tx objects get attached
1490
+ // to the broadcasted proposals via publishTxsWithProposals.
1491
+ const pendingTxs = filter(this.p2pClient.iterateEligiblePendingTxs({
1492
+ includeProof: !!this.config.publishTxsWithProposals
1493
+ }), (tx)=>!txHashesAlreadyIncluded.has(tx.txHash.toString()));
1494
+ this.log.debug(`Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.targetSlot}`, {
1495
+ slot: this.targetSlot,
1496
+ blockNumber,
1497
+ indexWithinCheckpoint
1498
+ });
1499
+ this.setState(SequencerState.CREATING_BLOCK);
1500
+ // Per-block limits are operator overrides (from SEQ_MAX_L2_BLOCK_GAS etc.) further capped
1501
+ // by remaining checkpoint-level budgets inside CheckpointBuilder before each block is built.
1502
+ // minValidTxs is passed into the builder so it can reject the block *before* updating state.
1503
+ // A zero-tx block is proven by the no-txs block-root circuit at any index, but one carrying neither txs
1504
+ // nor messages past the first block is pure padding, so the floor for minValidTxs is 1 there.
1505
+ const configuredMinValidTxs = forceCreate ? 0 : this.config.minValidTxsPerBlock ?? minTxs;
1506
+ const minValidTxs = indexWithinCheckpoint > 0 && (l1ToL2Messages?.length ?? 0) === 0 ? Math.max(configuredMinValidTxs, 1) : configuredMinValidTxs;
1507
+ const blockBuilderOptions = {
1508
+ maxTransactions: this.config.maxTxsPerBlock,
1509
+ maxBlockGas: this.config.maxL2BlockGas !== undefined || this.config.maxDABlockGas !== undefined ? new Gas(this.config.maxDABlockGas ?? Infinity, this.config.maxL2BlockGas ?? Infinity) : undefined,
1510
+ deadline: buildDeadline,
1511
+ isBuildingProposal: true,
1512
+ minValidTxs,
1513
+ maxBlocksPerCheckpoint: this.timetable.getMaxBlocksPerCheckpoint(),
1514
+ perBlockAllocationMultiplier: this.config.perBlockAllocationMultiplier,
1515
+ perBlockDAAllocationMultiplier: this.config.perBlockDAAllocationMultiplier,
1516
+ l1ToL2Messages
1517
+ };
1518
+ // Actually build the block by executing txs. The builder throws InsufficientValidTxsError
1519
+ // if the number of successfully processed txs is below minValidTxs, ensuring state is not
1520
+ // updated for blocks that will be discarded.
1521
+ const buildResult = await this.buildSingleBlockWithCheckpointBuilder(checkpointBuilder, pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
1522
+ // If any txs failed during execution, drop them from the mempool so we don't pick them up again
1523
+ await this.dropFailedTxsFromP2P(buildResult.failedTxs);
1524
+ if (buildResult.status === 'insufficient-valid-txs') {
1525
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1526
+ reason: 'insufficient_valid_txs',
1527
+ slot: this.targetSlot,
1528
+ checkpointNumber: this.checkpointNumber,
1529
+ blockNumber,
1530
+ numTxs: buildResult.processedCount,
1531
+ indexWithinCheckpoint,
1532
+ minValidTxs
1533
+ });
1534
+ this.log.warn(`Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.targetSlot} has too few valid txs to be proposed`, {
1535
+ reason: 'insufficient_valid_txs',
1536
+ slot: this.targetSlot,
1537
+ checkpointNumber: this.checkpointNumber,
1538
+ blockNumber,
1539
+ numTxs: buildResult.processedCount,
1540
+ indexWithinCheckpoint,
1541
+ minValidTxs
1542
+ });
1543
+ this.eventEmitter.emit('block-build-failed', {
1544
+ reason: `Insufficient valid txs`,
1545
+ slot: this.targetSlot
1546
+ });
1547
+ this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
1548
+ return {
1549
+ failure: 'insufficient-valid-txs'
1550
+ };
1551
+ }
1552
+ // Block creation succeeded, emit stats and metrics
1553
+ const { block, publicProcessorDuration, usedTxs, blockBuildDuration, numTxs } = buildResult;
1554
+ const blockStats = {
1555
+ eventName: 'l2-block-built',
1556
+ duration: blockBuildDuration,
1557
+ publicProcessDuration: publicProcessorDuration,
1558
+ ...block.getStats()
1559
+ };
1560
+ const blockHash = await block.hash();
1561
+ const txHashes = block.body.txEffects.map((tx)=>tx.txHash);
1562
+ const manaPerSec = block.header.totalManaUsed.toNumberUnsafe() / (blockBuildDuration / 1000);
1563
+ this.log.info(`Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.targetSlot} with ${numTxs} txs`, {
1564
+ blockHash,
1565
+ txHashes,
1566
+ manaPerSec,
1567
+ ...blockStats
1568
+ });
1569
+ // `slot` is the target/submission slot (may be one ahead when pipelining),
1570
+ // `buildSlot` is the wall-clock slot during which the block was actually built.
1571
+ this.eventEmitter.emit('block-proposed', {
1572
+ blockNumber: block.number,
1573
+ blockHash,
1574
+ checkpointNumber: this.checkpointNumber,
1575
+ indexWithinCheckpoint: block.indexWithinCheckpoint,
1576
+ slot: this.targetSlot,
1577
+ buildSlot: this.getBuildSlot()
1578
+ });
1579
+ this.metrics.recordBuiltBlock(blockBuildDuration, block.header.totalManaUsed.toNumberUnsafe(), this.targetSlot);
1580
+ return {
1581
+ block,
1582
+ usedTxs
1583
+ };
1584
+ } catch (err) {
1585
+ this.eventEmitter.emit('block-build-failed', {
1586
+ reason: err.message,
1587
+ slot: this.targetSlot
1588
+ });
1589
+ this.logCheckpointEvent('block-build-failed', `Block build failed for slot ${this.targetSlot}`, {
1590
+ reason: err instanceof Error ? err.message : String(err),
1591
+ slot: this.targetSlot,
1592
+ checkpointNumber: this.checkpointNumber,
1593
+ blockNumber
1594
+ });
1595
+ this.log.error(`Error building block`, err, {
1596
+ reason: err instanceof Error ? err.message : String(err),
1597
+ slot: this.targetSlot,
1598
+ checkpointNumber: this.checkpointNumber,
1599
+ blockNumber
1600
+ });
1601
+ this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
1602
+ this.metrics.recordFailedBlock();
1603
+ return {
1604
+ error: err
1605
+ };
1606
+ }
1607
+ }
1608
+ /** Uses the checkpoint builder to build a block, catching InsufficientValidTxsError. */ async buildSingleBlockWithCheckpointBuilder(checkpointBuilder, pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions) {
1609
+ try {
1610
+ const workTimer = new Timer();
1611
+ const result = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
1612
+ const blockBuildDuration = workTimer.ms();
1613
+ return {
1614
+ ...result,
1615
+ blockBuildDuration,
1616
+ status: 'success'
1617
+ };
1618
+ } catch (err) {
1619
+ if (isErrorClass(err, InsufficientValidTxsError)) {
1620
+ return {
1621
+ failedTxs: err.failedTxs,
1622
+ processedCount: err.processedCount,
1623
+ status: 'insufficient-valid-txs'
1624
+ };
1625
+ }
1626
+ throw err;
1627
+ }
1628
+ }
1629
+ /** Waits until minTxs are available on the pool for building a block. */ async waitForMinTxs(opts) {
1630
+ const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
1631
+ // A non-empty streaming Inbox bundle is work on its own: the block must be produced even with zero txs,
1632
+ // regardless of minTxsPerBlock, so the messages get inserted (message-only block).
1633
+ // Without a bundle, a non-first block needs at least one tx to avoid empty filler blocks even when
1634
+ // minTxsPerBlock is zero.
1635
+ const hasStreamingBundle = (opts.l1ToL2Messages?.length ?? 0) > 0;
1636
+ const minTxs = hasStreamingBundle ? 0 : indexWithinCheckpoint > 0 && this.config.minTxsPerBlock === 0 ? 1 : this.config.minTxsPerBlock;
1637
+ // Latest time to keep waiting for txs: wait_for_txs_deadline = block_build_deadline(k) - min_block_duration.
1638
+ const startBuildingDeadline = buildDeadline ? new Date(buildDeadline.getTime() - this.timetable.minBlockDuration * 1000) : undefined;
1639
+ // Gate on age-eligible txs so we don't start building on txs the builder would then filter out for being
1640
+ // too fresh. hasEligiblePendingTxs early-exits once minTxs are eligible instead of counting the whole pool.
1641
+ while(!forceCreate && !await this.p2pClient.hasEligiblePendingTxs(minTxs)){
1642
+ // If we're past deadline, or we have no deadline, give up
1643
+ const now = this.dateProvider.nowAsDate();
1644
+ if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
1645
+ return {
1646
+ canStartBuilding: false,
1647
+ minTxs
1648
+ };
1649
+ }
1650
+ // Wait a bit before checking again
1651
+ this.setState(SequencerState.WAITING_FOR_TXS);
1652
+ this.log.verbose(`Waiting for ${minTxs} age-eligible txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.targetSlot}`, {
1653
+ blockNumber,
1654
+ slot: this.targetSlot,
1655
+ indexWithinCheckpoint,
1656
+ minTxs
1657
+ });
1658
+ await this.waitForTxsPollingInterval();
1659
+ }
1660
+ return {
1661
+ canStartBuilding: true,
1662
+ minTxs
1663
+ };
1664
+ }
1665
+ async getSignedCommitteeAttestations(broadcast) {
1666
+ const { proposal, blockProposedAt } = broadcast;
1667
+ this.setState(SequencerState.COLLECTING_ATTESTATIONS);
1668
+ const attestations = await this.waitForAttestations(proposal);
1669
+ if (!attestations) {
1670
+ return undefined;
1671
+ }
1672
+ this.checkpointMetrics.recordCheckpointAttestationDelay(this.dateProvider.now() - blockProposedAt);
1673
+ // Proposer must sign over the attestations before pushing them to L1
1674
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
1675
+ try {
1676
+ const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer, this.targetSlot, this.checkpointNumber);
1677
+ return {
1678
+ attestations,
1679
+ attestationsSignature
1680
+ };
1681
+ } catch (err) {
1682
+ if (this.handleHASigningError(err, 'Attestations signature')) {
1683
+ return;
1684
+ }
1685
+ this.log.error(`Error signing attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
1686
+ return undefined;
1687
+ }
1688
+ }
1689
+ /**
1690
+ * Waits for enough attestations to be collected via p2p.
1691
+ * This is run after all blocks for the checkpoint have been built.
1692
+ */ async waitForAttestations(proposal) {
1693
+ if (this.config.fishermanMode) {
1694
+ this.log.debug('Skipping attestation collection in fisherman mode');
1695
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
1696
+ }
1697
+ const slotNumber = proposal.slotNumber;
1698
+ const { committee, seed, epoch } = await this.epochCache.getCommittee(slotNumber);
1699
+ if (!committee) {
1700
+ throw new Error('No committee when collecting attestations');
1701
+ } else if (committee.length === 0) {
1702
+ this.log.verbose(`Attesting committee is empty`);
1703
+ return CommitteeAttestationsAndSigners.empty(this.getSignatureContext());
1704
+ } else {
1705
+ this.log.debug(`Attesting committee length is ${committee.length}`, {
1706
+ committee
1707
+ });
1708
+ }
1709
+ const numberOfRequiredAttestations = computeQuorum(committee.length);
1710
+ if (this.config.skipCollectingAttestations) {
1711
+ this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
1712
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal, this.checkpointNumber);
1713
+ this.logCheckpointAttestations('collected', committee, attestations ?? [], numberOfRequiredAttestations, {
1714
+ reason: 'collect_own_only'
1715
+ });
1716
+ return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee), this.getSignatureContext());
1717
+ }
1718
+ // Hard attestation-collection cutoff = the single consensus attestation_deadline (target_slot_start + S - 2E).
1719
+ const attestationDeadlineSeconds = this.timetable.getAttestationDeadline(this.targetSlot);
1720
+ const attestationDeadline = new Date(attestationDeadlineSeconds * 1000);
1721
+ this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, Math.max(0, attestationDeadline.getTime() - this.dateProvider.now()));
1722
+ const collectAttestationsTimer = new Timer();
1723
+ let collectedAttestationsCount = 0;
1724
+ try {
1725
+ const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline, this.checkpointNumber);
1726
+ collectedAttestationsCount = attestations.length;
1727
+ // Trim attestations to minimum required to save L1 calldata gas
1728
+ const localAddresses = this.validatorClient.getValidatorAddresses();
1729
+ const trimmed = trimAttestations(attestations, numberOfRequiredAttestations, this.attestorAddress, localAddresses);
1730
+ if (trimmed.length < attestations.length) {
1731
+ this.log.debug(`Trimmed attestations from ${attestations.length} to ${trimmed.length} for L1 submission`);
1732
+ }
1733
+ // Rollup contract requires that the signatures are provided in the order of the committee
1734
+ const sorted = orderAttestations(trimmed, committee);
1735
+ this.logCheckpointAttestations('collected', committee, attestations, numberOfRequiredAttestations, {
1736
+ submittedCount: trimmed.length
1737
+ });
1738
+ // Manipulate the attestations if we've been configured to do so
1739
+ if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation || this.config.injectYParityAttestation || this.config.shuffleAttestationOrdering) {
1740
+ return this.manipulateAttestations(proposal.slotNumber, epoch, seed, committee, sorted);
1741
+ }
1742
+ return new CommitteeAttestationsAndSigners(sorted, this.getSignatureContext());
1743
+ } catch (err) {
1744
+ if (err && err instanceof AttestationTimeoutError) {
1745
+ collectedAttestationsCount = err.collectedCount;
1746
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1747
+ collectedCount: collectedAttestationsCount,
1748
+ reason: 'timeout'
1749
+ });
1750
+ this.log.error(`Timeout while waiting for attestations for checkpoint proposal at slot ${proposal.slotNumber} (collected ${collectedAttestationsCount}/${numberOfRequiredAttestations})`, err);
1751
+ } else {
1752
+ this.logCheckpointAttestations('failed', committee, undefined, numberOfRequiredAttestations, {
1753
+ collectedCount: collectedAttestationsCount,
1754
+ reason: err instanceof Error ? err.message : String(err)
1755
+ });
1756
+ this.log.error(`Error collecting attestations for checkpoint proposal at slot ${proposal.slotNumber}`, err);
1757
+ }
1758
+ return undefined;
1759
+ } finally{
1760
+ this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
1761
+ }
1762
+ }
1763
+ logCheckpointAttestations(status, committee, attestations, requiredAttestations, opts = {}) {
1764
+ const signedValidators = attestations?.map((attestation)=>attestation.getSender()?.toString()).filter((address)=>address !== undefined) ?? [];
1765
+ const collectedCount = opts.collectedCount ?? new Set(signedValidators).size;
1766
+ const missingValidatorCount = status === 'failed' ? Math.max(0, requiredAttestations - collectedCount) : undefined;
1767
+ this.logCheckpointEvent(`attestations-${status}`, `Checkpoint attestations ${status} for slot ${this.targetSlot}`, {
1768
+ slot: this.targetSlot,
1769
+ checkpointNumber: this.checkpointNumber,
1770
+ committeeSize: committee.length,
1771
+ requiredAttestations,
1772
+ collectedAttestations: collectedCount,
1773
+ ...opts.submittedCount !== undefined && {
1774
+ submittedAttestations: opts.submittedCount
1775
+ },
1776
+ ...missingValidatorCount !== undefined && {
1777
+ missingValidatorCount
1778
+ },
1779
+ ...opts.reason !== undefined && {
1780
+ reason: opts.reason
1781
+ }
1782
+ });
1783
+ }
1784
+ /** Breaks the attestations before publishing based on attack configs */ manipulateAttestations(slotNumber, epoch, seed, committee, attestations) {
1785
+ // Compute the proposer index in the committee, since we dont want to tweak it.
1786
+ // Otherwise, the L1 rollup contract will reject the block outright.
1787
+ const proposerIndex = Number(this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)));
1788
+ if (this.config.injectFakeAttestation || this.config.injectHighSValueAttestation || this.config.injectUnrecoverableSignatureAttestation) {
1789
+ // Find non-empty attestations that are not from the proposer
1790
+ const nonProposerIndices = [];
1791
+ for(let i = 0; i < attestations.length; i++){
1792
+ if (!attestations[i].signature.isEmpty() && i !== proposerIndex) {
1793
+ nonProposerIndices.push(i);
1794
+ }
1795
+ }
1796
+ if (nonProposerIndices.length > 0) {
1797
+ const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
1798
+ if (this.config.injectHighSValueAttestation) {
1799
+ this.log.warn(`Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1800
+ unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
1801
+ } else if (this.config.injectUnrecoverableSignatureAttestation) {
1802
+ this.log.warn(`Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1803
+ unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
1804
+ } else {
1805
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
1806
+ unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
1807
+ }
1808
+ }
1809
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1810
+ }
1811
+ if (this.config.injectYParityAttestation) {
1812
+ // Force every non-proposer signed slot's recovery byte to yParity (v ∈ {0, 1}) form in the packed L1
1813
+ // tuple, after packAttestations has canonicalized it. The proposer's own slot is left canonical so
1814
+ // propose() still passes verifyProposer. Models a malicious proposer landing a checkpoint L1 accepts
1815
+ // but that can never be proven (ECDSA.recover rejects v ∉ {27, 28}).
1816
+ this.log.warn(`Injecting yParity attestations in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
1817
+ return new MaliciousYParityCommitteeAttestationsAndSigners(attestations, proposerIndex, this.getSignatureContext());
1818
+ }
1819
+ if (this.config.shuffleAttestationOrdering) {
1820
+ this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
1821
+ const shuffled = [
1822
+ ...attestations
1823
+ ];
1824
+ // Find two non-proposer positions that both have non-empty signatures to swap.
1825
+ // This ensures the bitmap doesn't change, so the MaliciousCommitteeAttestationsAndSigners
1826
+ // signers array stays correctly aligned with L1's committee reconstruction.
1827
+ const swappable = [];
1828
+ for(let k = 0; k < shuffled.length; k++){
1829
+ if (!shuffled[k].signature.isEmpty() && k !== proposerIndex) {
1830
+ swappable.push(k);
1831
+ }
1832
+ }
1833
+ if (swappable.length >= 2) {
1834
+ const [i, j] = [
1835
+ swappable[0],
1836
+ swappable[1]
1837
+ ];
1838
+ [shuffled[i], shuffled[j]] = [
1839
+ shuffled[j],
1840
+ shuffled[i]
1841
+ ];
1842
+ }
1843
+ const signers = new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext()).getSigners();
1844
+ return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers, this.getSignatureContext());
1845
+ }
1846
+ return new CommitteeAttestationsAndSigners(attestations, this.getSignatureContext());
1847
+ }
1848
+ async dropFailedTxsFromP2P(failedTxs) {
1849
+ if (failedTxs.length === 0) {
1850
+ return;
1851
+ }
1852
+ const failedTxData = failedTxs.map((fail)=>fail.tx);
1853
+ const failedTxHashes = failedTxData.map((tx)=>tx.getTxHash());
1854
+ const failures = failedTxs.map((fail)=>({
1855
+ txHash: fail.tx.getTxHash().toString(),
1856
+ reason: fail.error.message
1857
+ }));
1858
+ this.log.warn(`Dropping ${failedTxs.length} txs from mempool due to failures during block building for slot ${this.targetSlot}`, {
1859
+ slot: this.targetSlot,
1860
+ checkpointNumber: this.checkpointNumber,
1861
+ failures
1862
+ });
1863
+ await this.p2pClient.handleFailedExecution(failedTxHashes);
1864
+ }
1865
+ /**
1866
+ * Adds the proposed block to the archiver so it's available via P2P.
1867
+ * Gossip doesn't echo messages back to the sender, so the proposer's archiver/world-state
1868
+ * would never receive its own block without this explicit sync.
1869
+ *
1870
+ * In fisherman mode we skip this push: the fisherman builds blocks locally for validation
1871
+ * and fee analysis only, and pushing them to the archiver causes spurious reorg cascades
1872
+ * whenever the real proposer's block arrives from L1.
1873
+ */ async syncProposedBlockToArchiver(block) {
1874
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1875
+ this.log.warn(`Skipping push of proposed block ${block.number} to archiver`, {
1876
+ blockNumber: block.number,
1877
+ slot: block.header.globalVariables.slotNumber
1878
+ });
1879
+ return;
1880
+ }
1881
+ this.log.debug(`Syncing proposed block ${block.number} to archiver`, {
1882
+ blockNumber: block.number,
1883
+ slot: block.header.globalVariables.slotNumber
1884
+ });
1885
+ await this.blockSink.addBlock(block);
1886
+ }
1887
+ /**
1888
+ * Adds the proposed checkpoint to the archiver so the proposer's optimistic proposed-checkpoint
1889
+ * tip advances locally. Gossip doesn't echo our own messages back, so without this the proposer
1890
+ * would never see its own proposed checkpoint and couldn't pipeline the next slot.
1891
+ *
1892
+ * Skipped whenever proposed blocks aren't pushed (`skipPushProposedBlocksToArchiver`, fisherman
1893
+ * mode): the archiver derives the checkpoint archive from its stored blocks, so without them the
1894
+ * push would fail. All blocks were already added (and awaited) during block building, so this
1895
+ * needs no retry — they are guaranteed present by the time we get here.
1896
+ */ async syncProposedCheckpointToArchiver(checkpoint, blockCount, feeAssetPriceModifier) {
1897
+ if (this.config.skipPushProposedBlocksToArchiver || this.config.fishermanMode) {
1898
+ return;
1899
+ }
1900
+ const startBlock = BlockNumber(this.syncedToBlockNumber + 1);
1901
+ this.log.debug(`Syncing proposed checkpoint ${this.checkpointNumber} to archiver`, {
1902
+ checkpointNumber: this.checkpointNumber,
1903
+ slot: this.targetSlot,
1904
+ startBlock,
1905
+ blockCount
1906
+ });
1907
+ await this.blockSink.addProposedCheckpoint({
1908
+ header: checkpoint.header,
1909
+ checkpointNumber: this.checkpointNumber,
1910
+ startBlock,
1911
+ blockCount,
1912
+ totalManaUsed: checkpoint.header.totalManaUsed.toBigInt(),
1913
+ feeAssetPriceModifier
1914
+ });
1915
+ }
1916
+ /** Runs fee analysis and logs checkpoint outcome as fisherman */ async handleCheckpointEndAsFisherman(checkpoint) {
1917
+ // Perform L1 fee analysis before clearing requests
1918
+ // The callback is invoked asynchronously after the next block is mined
1919
+ const feeAnalysis = await this.publisher.analyzeL1Fees(this.targetSlot, (analysis)=>this.metrics.recordFishermanFeeAnalysis(analysis));
1920
+ if (checkpoint) {
1921
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.targetSlot}`, {
1922
+ ...checkpoint.toCheckpointInfo(),
1923
+ ...checkpoint.getStats(),
1924
+ feeAnalysisId: feeAnalysis?.id
1925
+ });
1926
+ } else {
1927
+ this.log.warn(`Validation block building FAILED for slot ${this.targetSlot}`, {
1928
+ slot: this.targetSlot,
1929
+ feeAnalysisId: feeAnalysis?.id
1930
+ });
1931
+ this.metrics.recordCheckpointProposalFailed('block_build_failed');
1932
+ }
1933
+ this.publisher.clearPendingRequests();
1934
+ }
1935
+ /**
1936
+ * Helper to handle HA double-signing errors. Returns true if the error was handled (caller should yield).
1937
+ */ handleHASigningError(err, errorContext) {
1938
+ if (err instanceof DutyAlreadySignedError) {
1939
+ this.log.info(`${errorContext} for slot ${this.targetSlot} already signed by another HA node, yielding`, {
1940
+ slot: this.targetSlot,
1941
+ signedByNode: err.signedByNode
1942
+ });
1943
+ return true;
1944
+ }
1945
+ if (err instanceof SlashingProtectionError) {
1946
+ this.log.info(`${errorContext} for slot ${this.targetSlot} blocked by slashing protection, yielding`, {
1947
+ slot: this.targetSlot,
1948
+ existingMessageHash: err.existingMessageHash,
1949
+ attemptedMessageHash: err.attemptedMessageHash
1950
+ });
1951
+ return true;
1952
+ }
1953
+ return false;
1954
+ }
1955
+ /** Waits the polling interval for transactions. Extracted for test overriding. */ async waitForTxsPollingInterval() {
1956
+ await this.awaitInterruptibleSleep(TXS_POLLING_MS);
1957
+ }
1958
+ getPublisher() {
1959
+ return this.publisher;
1960
+ }
1961
+ }