@aztec/sequencer-client 0.0.0-test.1 → 0.0.1-commit.017a351

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 (185) hide show
  1. package/README.md +281 -21
  2. package/dest/client/index.d.ts +1 -1
  3. package/dest/client/sequencer-client.d.ts +43 -33
  4. package/dest/client/sequencer-client.d.ts.map +1 -1
  5. package/dest/client/sequencer-client.js +117 -62
  6. package/dest/config.d.ts +38 -17
  7. package/dest/config.d.ts.map +1 -1
  8. package/dest/config.js +172 -85
  9. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  10. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  11. package/dest/global_variable_builder/fee_predictor.js +128 -0
  12. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  13. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  14. package/dest/global_variable_builder/fee_provider.js +58 -0
  15. package/dest/global_variable_builder/global_builder.d.ts +26 -17
  16. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  17. package/dest/global_variable_builder/global_builder.js +45 -61
  18. package/dest/global_variable_builder/index.d.ts +4 -2
  19. package/dest/global_variable_builder/index.d.ts.map +1 -1
  20. package/dest/global_variable_builder/index.js +2 -0
  21. package/dest/index.d.ts +2 -4
  22. package/dest/index.d.ts.map +1 -1
  23. package/dest/index.js +1 -3
  24. package/dest/publisher/config.d.ts +60 -27
  25. package/dest/publisher/config.d.ts.map +1 -1
  26. package/dest/publisher/config.js +124 -32
  27. package/dest/publisher/index.d.ts +4 -1
  28. package/dest/publisher/index.d.ts.map +1 -1
  29. package/dest/publisher/index.js +3 -0
  30. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  31. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  32. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  33. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +58 -0
  34. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  35. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  36. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  37. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  38. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  39. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  40. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  41. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  42. package/dest/publisher/sequencer-bundle-simulator.d.ts +96 -0
  43. package/dest/publisher/sequencer-bundle-simulator.d.ts.map +1 -0
  44. package/dest/publisher/sequencer-bundle-simulator.js +198 -0
  45. package/dest/publisher/sequencer-publisher-factory.d.ts +50 -0
  46. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -0
  47. package/dest/publisher/sequencer-publisher-factory.js +75 -0
  48. package/dest/publisher/sequencer-publisher-metrics.d.ts +5 -4
  49. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  50. package/dest/publisher/sequencer-publisher-metrics.js +34 -62
  51. package/dest/publisher/sequencer-publisher.d.ts +170 -97
  52. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  53. package/dest/publisher/sequencer-publisher.js +1255 -276
  54. package/dest/sequencer/automine/automine_factory.d.ts +54 -0
  55. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -0
  56. package/dest/sequencer/automine/automine_factory.js +84 -0
  57. package/dest/sequencer/automine/automine_sequencer.d.ts +151 -0
  58. package/dest/sequencer/automine/automine_sequencer.d.ts.map +1 -0
  59. package/dest/sequencer/automine/automine_sequencer.js +509 -0
  60. package/dest/sequencer/chain_state_overrides.d.ts +61 -0
  61. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  62. package/dest/sequencer/chain_state_overrides.js +98 -0
  63. package/dest/sequencer/checkpoint_proposal_job.d.ts +150 -0
  64. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  65. package/dest/sequencer/checkpoint_proposal_job.js +1792 -0
  66. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  67. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  68. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  69. package/dest/sequencer/checkpoint_voter.d.ts +34 -0
  70. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  71. package/dest/sequencer/checkpoint_voter.js +106 -0
  72. package/dest/sequencer/config.d.ts +7 -1
  73. package/dest/sequencer/config.d.ts.map +1 -1
  74. package/dest/sequencer/errors.d.ts +11 -0
  75. package/dest/sequencer/errors.d.ts.map +1 -0
  76. package/dest/sequencer/errors.js +15 -0
  77. package/dest/sequencer/events.d.ts +92 -0
  78. package/dest/sequencer/events.d.ts.map +1 -0
  79. package/dest/sequencer/events.js +1 -0
  80. package/dest/sequencer/index.d.ts +6 -2
  81. package/dest/sequencer/index.d.ts.map +1 -1
  82. package/dest/sequencer/index.js +5 -1
  83. package/dest/sequencer/metrics.d.ts +64 -13
  84. package/dest/sequencer/metrics.d.ts.map +1 -1
  85. package/dest/sequencer/metrics.js +309 -68
  86. package/dest/sequencer/sequencer.d.ts +205 -135
  87. package/dest/sequencer/sequencer.d.ts.map +1 -1
  88. package/dest/sequencer/sequencer.js +1208 -523
  89. package/dest/sequencer/timetable.d.ts +85 -25
  90. package/dest/sequencer/timetable.d.ts.map +1 -1
  91. package/dest/sequencer/timetable.js +177 -60
  92. package/dest/sequencer/types.d.ts +3 -0
  93. package/dest/sequencer/types.d.ts.map +1 -0
  94. package/dest/sequencer/types.js +1 -0
  95. package/dest/sequencer/utils.d.ts +20 -38
  96. package/dest/sequencer/utils.d.ts.map +1 -1
  97. package/dest/sequencer/utils.js +12 -47
  98. package/dest/test/index.d.ts +9 -3
  99. package/dest/test/index.d.ts.map +1 -1
  100. package/dest/test/index.js +0 -4
  101. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  102. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  103. package/dest/test/mock_checkpoint_builder.js +231 -0
  104. package/dest/test/utils.d.ts +53 -0
  105. package/dest/test/utils.d.ts.map +1 -0
  106. package/dest/test/utils.js +105 -0
  107. package/package.json +46 -45
  108. package/src/client/sequencer-client.ts +158 -103
  109. package/src/config.ts +201 -99
  110. package/src/global_variable_builder/README.md +44 -0
  111. package/src/global_variable_builder/fee_predictor.ts +172 -0
  112. package/src/global_variable_builder/fee_provider.ts +75 -0
  113. package/src/global_variable_builder/global_builder.ts +68 -76
  114. package/src/global_variable_builder/index.ts +3 -1
  115. package/src/index.ts +10 -3
  116. package/src/publisher/config.ts +184 -59
  117. package/src/publisher/index.ts +7 -0
  118. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  119. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  120. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  121. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  122. package/src/publisher/sequencer-bundle-simulator.ts +254 -0
  123. package/src/publisher/sequencer-publisher-factory.ts +121 -0
  124. package/src/publisher/sequencer-publisher-metrics.ts +33 -63
  125. package/src/publisher/sequencer-publisher.ts +1101 -350
  126. package/src/sequencer/README.md +243 -0
  127. package/src/sequencer/automine/README.md +46 -0
  128. package/src/sequencer/automine/automine_factory.ts +145 -0
  129. package/src/sequencer/automine/automine_sequencer.ts +595 -0
  130. package/src/sequencer/chain_state_overrides.ts +162 -0
  131. package/src/sequencer/checkpoint_proposal_job.ts +1632 -0
  132. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  133. package/src/sequencer/checkpoint_voter.ts +119 -0
  134. package/src/sequencer/config.ts +8 -0
  135. package/src/sequencer/errors.ts +21 -0
  136. package/src/sequencer/events.ts +76 -0
  137. package/src/sequencer/index.ts +5 -1
  138. package/src/sequencer/metrics.ts +397 -75
  139. package/src/sequencer/sequencer.ts +1013 -579
  140. package/src/sequencer/timetable.ts +225 -60
  141. package/src/sequencer/types.ts +6 -0
  142. package/src/sequencer/utils.ts +28 -60
  143. package/src/test/index.ts +11 -5
  144. package/src/test/mock_checkpoint_builder.ts +323 -0
  145. package/src/test/utils.ts +185 -0
  146. package/dest/sequencer/allowed.d.ts +0 -3
  147. package/dest/sequencer/allowed.d.ts.map +0 -1
  148. package/dest/sequencer/allowed.js +0 -27
  149. package/dest/slasher/factory.d.ts +0 -7
  150. package/dest/slasher/factory.d.ts.map +0 -1
  151. package/dest/slasher/factory.js +0 -8
  152. package/dest/slasher/index.d.ts +0 -3
  153. package/dest/slasher/index.d.ts.map +0 -1
  154. package/dest/slasher/index.js +0 -2
  155. package/dest/slasher/slasher_client.d.ts +0 -75
  156. package/dest/slasher/slasher_client.d.ts.map +0 -1
  157. package/dest/slasher/slasher_client.js +0 -132
  158. package/dest/tx_validator/archive_cache.d.ts +0 -14
  159. package/dest/tx_validator/archive_cache.d.ts.map +0 -1
  160. package/dest/tx_validator/archive_cache.js +0 -22
  161. package/dest/tx_validator/gas_validator.d.ts +0 -14
  162. package/dest/tx_validator/gas_validator.d.ts.map +0 -1
  163. package/dest/tx_validator/gas_validator.js +0 -78
  164. package/dest/tx_validator/nullifier_cache.d.ts +0 -16
  165. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  166. package/dest/tx_validator/nullifier_cache.js +0 -24
  167. package/dest/tx_validator/phases_validator.d.ts +0 -12
  168. package/dest/tx_validator/phases_validator.d.ts.map +0 -1
  169. package/dest/tx_validator/phases_validator.js +0 -80
  170. package/dest/tx_validator/test_utils.d.ts +0 -23
  171. package/dest/tx_validator/test_utils.d.ts.map +0 -1
  172. package/dest/tx_validator/test_utils.js +0 -26
  173. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  174. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  175. package/dest/tx_validator/tx_validator_factory.js +0 -50
  176. package/src/sequencer/allowed.ts +0 -36
  177. package/src/slasher/factory.ts +0 -15
  178. package/src/slasher/index.ts +0 -2
  179. package/src/slasher/slasher_client.ts +0 -193
  180. package/src/tx_validator/archive_cache.ts +0 -28
  181. package/src/tx_validator/gas_validator.ts +0 -101
  182. package/src/tx_validator/nullifier_cache.ts +0 -30
  183. package/src/tx_validator/phases_validator.ts +0 -98
  184. package/src/tx_validator/test_utils.ts +0 -48
  185. package/src/tx_validator/tx_validator_factory.ts +0 -120
@@ -1,623 +1,1308 @@
1
- function _ts_decorate(decorators, target, key, desc) {
2
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
- else for(var i = decorators.length - 1; i >= 0; i--)if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
- return c > 3 && r && Object.defineProperty(target, key, r), r;
1
+ function applyDecs2203RFactory() {
2
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
3
+ return function addInitializer(initializer) {
4
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
5
+ assertCallable(initializer, "An initializer");
6
+ initializers.push(initializer);
7
+ };
8
+ }
9
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
10
+ var kindStr;
11
+ switch(kind){
12
+ case 1:
13
+ kindStr = "accessor";
14
+ break;
15
+ case 2:
16
+ kindStr = "method";
17
+ break;
18
+ case 3:
19
+ kindStr = "getter";
20
+ break;
21
+ case 4:
22
+ kindStr = "setter";
23
+ break;
24
+ default:
25
+ kindStr = "field";
26
+ }
27
+ var ctx = {
28
+ kind: kindStr,
29
+ name: isPrivate ? "#" + name : name,
30
+ static: isStatic,
31
+ private: isPrivate,
32
+ metadata: metadata
33
+ };
34
+ var decoratorFinishedRef = {
35
+ v: false
36
+ };
37
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
38
+ var get, set;
39
+ if (kind === 0) {
40
+ if (isPrivate) {
41
+ get = desc.get;
42
+ set = desc.set;
43
+ } else {
44
+ get = function() {
45
+ return this[name];
46
+ };
47
+ set = function(v) {
48
+ this[name] = v;
49
+ };
50
+ }
51
+ } else if (kind === 2) {
52
+ get = function() {
53
+ return desc.value;
54
+ };
55
+ } else {
56
+ if (kind === 1 || kind === 3) {
57
+ get = function() {
58
+ return desc.get.call(this);
59
+ };
60
+ }
61
+ if (kind === 1 || kind === 4) {
62
+ set = function(v) {
63
+ desc.set.call(this, v);
64
+ };
65
+ }
66
+ }
67
+ ctx.access = get && set ? {
68
+ get: get,
69
+ set: set
70
+ } : get ? {
71
+ get: get
72
+ } : {
73
+ set: set
74
+ };
75
+ try {
76
+ return dec(value, ctx);
77
+ } finally{
78
+ decoratorFinishedRef.v = true;
79
+ }
80
+ }
81
+ function assertNotFinished(decoratorFinishedRef, fnName) {
82
+ if (decoratorFinishedRef.v) {
83
+ throw new Error("attempted to call " + fnName + " after decoration was finished");
84
+ }
85
+ }
86
+ function assertCallable(fn, hint) {
87
+ if (typeof fn !== "function") {
88
+ throw new TypeError(hint + " must be a function");
89
+ }
90
+ }
91
+ function assertValidReturnValue(kind, value) {
92
+ var type = typeof value;
93
+ if (kind === 1) {
94
+ if (type !== "object" || value === null) {
95
+ throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
96
+ }
97
+ if (value.get !== undefined) {
98
+ assertCallable(value.get, "accessor.get");
99
+ }
100
+ if (value.set !== undefined) {
101
+ assertCallable(value.set, "accessor.set");
102
+ }
103
+ if (value.init !== undefined) {
104
+ assertCallable(value.init, "accessor.init");
105
+ }
106
+ } else if (type !== "function") {
107
+ var hint;
108
+ if (kind === 0) {
109
+ hint = "field";
110
+ } else if (kind === 10) {
111
+ hint = "class";
112
+ } else {
113
+ hint = "method";
114
+ }
115
+ throw new TypeError(hint + " decorators must return a function or void 0");
116
+ }
117
+ }
118
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
119
+ var decs = decInfo[0];
120
+ var desc, init, value;
121
+ if (isPrivate) {
122
+ if (kind === 0 || kind === 1) {
123
+ desc = {
124
+ get: decInfo[3],
125
+ set: decInfo[4]
126
+ };
127
+ } else if (kind === 3) {
128
+ desc = {
129
+ get: decInfo[3]
130
+ };
131
+ } else if (kind === 4) {
132
+ desc = {
133
+ set: decInfo[3]
134
+ };
135
+ } else {
136
+ desc = {
137
+ value: decInfo[3]
138
+ };
139
+ }
140
+ } else if (kind !== 0) {
141
+ desc = Object.getOwnPropertyDescriptor(base, name);
142
+ }
143
+ if (kind === 1) {
144
+ value = {
145
+ get: desc.get,
146
+ set: desc.set
147
+ };
148
+ } else if (kind === 2) {
149
+ value = desc.value;
150
+ } else if (kind === 3) {
151
+ value = desc.get;
152
+ } else if (kind === 4) {
153
+ value = desc.set;
154
+ }
155
+ var newValue, get, set;
156
+ if (typeof decs === "function") {
157
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
158
+ if (newValue !== void 0) {
159
+ assertValidReturnValue(kind, newValue);
160
+ if (kind === 0) {
161
+ init = newValue;
162
+ } else if (kind === 1) {
163
+ init = newValue.init;
164
+ get = newValue.get || value.get;
165
+ set = newValue.set || value.set;
166
+ value = {
167
+ get: get,
168
+ set: set
169
+ };
170
+ } else {
171
+ value = newValue;
172
+ }
173
+ }
174
+ } else {
175
+ for(var i = decs.length - 1; i >= 0; i--){
176
+ var dec = decs[i];
177
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
178
+ if (newValue !== void 0) {
179
+ assertValidReturnValue(kind, newValue);
180
+ var newInit;
181
+ if (kind === 0) {
182
+ newInit = newValue;
183
+ } else if (kind === 1) {
184
+ newInit = newValue.init;
185
+ get = newValue.get || value.get;
186
+ set = newValue.set || value.set;
187
+ value = {
188
+ get: get,
189
+ set: set
190
+ };
191
+ } else {
192
+ value = newValue;
193
+ }
194
+ if (newInit !== void 0) {
195
+ if (init === void 0) {
196
+ init = newInit;
197
+ } else if (typeof init === "function") {
198
+ init = [
199
+ init,
200
+ newInit
201
+ ];
202
+ } else {
203
+ init.push(newInit);
204
+ }
205
+ }
206
+ }
207
+ }
208
+ }
209
+ if (kind === 0 || kind === 1) {
210
+ if (init === void 0) {
211
+ init = function(instance, init) {
212
+ return init;
213
+ };
214
+ } else if (typeof init !== "function") {
215
+ var ownInitializers = init;
216
+ init = function(instance, init) {
217
+ var value = init;
218
+ for(var i = 0; i < ownInitializers.length; i++){
219
+ value = ownInitializers[i].call(instance, value);
220
+ }
221
+ return value;
222
+ };
223
+ } else {
224
+ var originalInitializer = init;
225
+ init = function(instance, init) {
226
+ return originalInitializer.call(instance, init);
227
+ };
228
+ }
229
+ ret.push(init);
230
+ }
231
+ if (kind !== 0) {
232
+ if (kind === 1) {
233
+ desc.get = value.get;
234
+ desc.set = value.set;
235
+ } else if (kind === 2) {
236
+ desc.value = value;
237
+ } else if (kind === 3) {
238
+ desc.get = value;
239
+ } else if (kind === 4) {
240
+ desc.set = value;
241
+ }
242
+ if (isPrivate) {
243
+ if (kind === 1) {
244
+ ret.push(function(instance, args) {
245
+ return value.get.call(instance, args);
246
+ });
247
+ ret.push(function(instance, args) {
248
+ return value.set.call(instance, args);
249
+ });
250
+ } else if (kind === 2) {
251
+ ret.push(value);
252
+ } else {
253
+ ret.push(function(instance, args) {
254
+ return value.call(instance, args);
255
+ });
256
+ }
257
+ } else {
258
+ Object.defineProperty(base, name, desc);
259
+ }
260
+ }
261
+ }
262
+ function applyMemberDecs(Class, decInfos, metadata) {
263
+ var ret = [];
264
+ var protoInitializers;
265
+ var staticInitializers;
266
+ var existingProtoNonFields = new Map();
267
+ var existingStaticNonFields = new Map();
268
+ for(var i = 0; i < decInfos.length; i++){
269
+ var decInfo = decInfos[i];
270
+ if (!Array.isArray(decInfo)) continue;
271
+ var kind = decInfo[1];
272
+ var name = decInfo[2];
273
+ var isPrivate = decInfo.length > 3;
274
+ var isStatic = kind >= 5;
275
+ var base;
276
+ var initializers;
277
+ if (isStatic) {
278
+ base = Class;
279
+ kind = kind - 5;
280
+ staticInitializers = staticInitializers || [];
281
+ initializers = staticInitializers;
282
+ } else {
283
+ base = Class.prototype;
284
+ protoInitializers = protoInitializers || [];
285
+ initializers = protoInitializers;
286
+ }
287
+ if (kind !== 0 && !isPrivate) {
288
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
289
+ var existingKind = existingNonFields.get(name) || 0;
290
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
291
+ throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
292
+ } else if (!existingKind && kind > 2) {
293
+ existingNonFields.set(name, kind);
294
+ } else {
295
+ existingNonFields.set(name, true);
296
+ }
297
+ }
298
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
299
+ }
300
+ pushInitializers(ret, protoInitializers);
301
+ pushInitializers(ret, staticInitializers);
302
+ return ret;
303
+ }
304
+ function pushInitializers(ret, initializers) {
305
+ if (initializers) {
306
+ ret.push(function(instance) {
307
+ for(var i = 0; i < initializers.length; i++){
308
+ initializers[i].call(instance);
309
+ }
310
+ return instance;
311
+ });
312
+ }
313
+ }
314
+ function applyClassDecs(targetClass, classDecs, metadata) {
315
+ if (classDecs.length > 0) {
316
+ var initializers = [];
317
+ var newClass = targetClass;
318
+ var name = targetClass.name;
319
+ for(var i = classDecs.length - 1; i >= 0; i--){
320
+ var decoratorFinishedRef = {
321
+ v: false
322
+ };
323
+ try {
324
+ var nextNewClass = classDecs[i](newClass, {
325
+ kind: "class",
326
+ name: name,
327
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
328
+ metadata
329
+ });
330
+ } finally{
331
+ decoratorFinishedRef.v = true;
332
+ }
333
+ if (nextNewClass !== undefined) {
334
+ assertValidReturnValue(10, nextNewClass);
335
+ newClass = nextNewClass;
336
+ }
337
+ }
338
+ return [
339
+ defineMetadata(newClass, metadata),
340
+ function() {
341
+ for(var i = 0; i < initializers.length; i++){
342
+ initializers[i].call(newClass);
343
+ }
344
+ }
345
+ ];
346
+ }
347
+ }
348
+ function defineMetadata(Class, metadata) {
349
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
350
+ configurable: true,
351
+ enumerable: true,
352
+ value: metadata
353
+ });
354
+ }
355
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
356
+ if (parentClass !== void 0) {
357
+ var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
358
+ }
359
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
360
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
361
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
362
+ return {
363
+ e: e,
364
+ get c () {
365
+ return applyClassDecs(targetClass, classDecs, metadata);
366
+ }
367
+ };
368
+ };
369
+ }
370
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
6
372
  }
7
- import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
8
- import { omit } from '@aztec/foundation/collection';
373
+ var _dec, _dec1, _dec2, _dec3, _initProto;
374
+ import { getKzg } from '@aztec/blob-lib';
375
+ import { PROPOSER_PIPELINING_SLOT_OFFSET } from '@aztec/epoch-cache';
376
+ import { NoCommitteeError } from '@aztec/ethereum/contracts';
377
+ import { CheckpointNumber, SlotNumber } from '@aztec/foundation/branded-types';
378
+ import { merge, omit, pick } from '@aztec/foundation/collection';
9
379
  import { EthAddress } from '@aztec/foundation/eth-address';
10
- import { Fr } from '@aztec/foundation/fields';
11
380
  import { createLogger } from '@aztec/foundation/log';
12
381
  import { RunningPromise } from '@aztec/foundation/running-promise';
13
- import { Timer, elapsed } from '@aztec/foundation/timer';
14
- import { AztecAddress } from '@aztec/stdlib/aztec-address';
15
- import { Gas } from '@aztec/stdlib/gas';
382
+ import { getEpochAtSlot, getSlotStartBuildTimestamp, getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
16
383
  import { SequencerConfigSchema } from '@aztec/stdlib/interfaces/server';
17
384
  import { pickFromSchema } from '@aztec/stdlib/schemas';
18
- import { AppendOnlyTreeSnapshot, MerkleTreeId } from '@aztec/stdlib/trees';
19
- import { BlockHeader, ContentCommitment, StateReference, Tx } from '@aztec/stdlib/tx';
385
+ import { MIN_EXECUTION_TIME } from '@aztec/stdlib/timetable';
20
386
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
21
- import { VoteType } from '../publisher/sequencer-publisher.js';
22
- import { createValidatorsForBlockBuilding } from '../tx_validator/tx_validator_factory.js';
23
- import { getDefaultAllowedSetupFunctions } from './allowed.js';
387
+ import EventEmitter from 'node:events';
388
+ import { DefaultSequencerConfig } from '../config.js';
389
+ import { buildCheckpointSimulationOverridesPlan } from './chain_state_overrides.js';
390
+ import { CheckpointProposalJob } from './checkpoint_proposal_job.js';
391
+ import { CheckpointProposalJobMetrics } from './checkpoint_proposal_job_metrics.js';
392
+ import { CheckpointVoter } from './checkpoint_voter.js';
393
+ import { SequencerInterruptedError, SequencerTooSlowError } from './errors.js';
24
394
  import { SequencerMetrics } from './metrics.js';
25
- import { SequencerTimetable, SequencerTooSlowError } from './timetable.js';
26
- import { SequencerState, orderAttestations } from './utils.js';
395
+ import { SequencerTimetable } from './timetable.js';
396
+ import { SequencerState } from './utils.js';
27
397
  export { SequencerState };
398
+ _dec = trackSpan('Sequencer.work'), _dec1 = trackSpan('Sequencer.prepareCheckpointProposal'), _dec2 = trackSpan('Seqeuencer.tryVoteWhenSyncFails', ({ slot })=>({
399
+ [Attributes.SLOT_NUMBER]: slot
400
+ })), _dec3 = trackSpan('Sequencer.tryVoteWhenEscapeHatchOpen', ({ slot })=>({
401
+ [Attributes.SLOT_NUMBER]: slot
402
+ }));
28
403
  /**
29
404
  * Sequencer client
30
- * - Wins a period of time to become the sequencer (depending on finalized protocol).
31
- * - Chooses a set of txs from the tx pool to be in the rollup.
32
- * - Simulate the rollup of txs.
33
- * - Adds proof requests to the request pool (not for this milestone).
34
- * - Receives results to those proofs from the network (repeats as necessary) (not for this milestone).
35
- * - Publishes L1 tx(s) to the rollup contract via RollupPublisher.
36
- */ export class Sequencer {
37
- publisher;
405
+ * - Checks whether it is elected as proposer for the next slot
406
+ * - Builds multiple blocks and broadcasts them
407
+ * - Collects attestations for the checkpoint
408
+ * - Publishes the checkpoint to L1
409
+ * - Votes for proposals and slashes on L1
410
+ */ export class Sequencer extends EventEmitter {
411
+ publisherFactory;
38
412
  validatorClient;
39
413
  globalsBuilder;
40
414
  p2pClient;
41
415
  worldState;
42
416
  slasherClient;
43
- blockBuilderFactory;
44
417
  l2BlockSource;
45
418
  l1ToL2MessageSource;
46
- publicProcessorFactory;
47
- contractDataSource;
419
+ checkpointsBuilder;
48
420
  l1Constants;
49
421
  dateProvider;
50
- config;
422
+ epochCache;
423
+ rollupContract;
424
+ telemetry;
51
425
  log;
426
+ static{
427
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
428
+ [
429
+ _dec,
430
+ 2,
431
+ "work"
432
+ ],
433
+ [
434
+ _dec1,
435
+ 2,
436
+ "prepareCheckpointProposal"
437
+ ],
438
+ [
439
+ _dec2,
440
+ 2,
441
+ "tryVoteWhenSyncFails"
442
+ ],
443
+ [
444
+ _dec3,
445
+ 2,
446
+ "tryVoteWhenEscapeHatchOpen"
447
+ ]
448
+ ], []));
449
+ }
52
450
  runningPromise;
53
- pollingIntervalMs;
54
- maxTxsPerBlock;
55
- minTxsPerBlock;
56
- maxL1TxInclusionTimeIntoSlot;
57
- // TODO: zero values should not be allowed for the following 2 values in PROD
58
- _coinbase;
59
- _feeRecipient;
60
451
  state;
61
- allowedInSetup;
62
- maxBlockSizeInBytes;
63
- maxBlockGas;
452
+ stateSlotNumber;
453
+ stateEnteredAtMs;
64
454
  metrics;
65
- isFlushing;
455
+ checkpointProposalJobMetrics;
456
+ stateLog;
457
+ /** The last slot for which we attempted to perform our voting duties with degraded block production */ lastSlotForFallbackVote;
458
+ /** The last slot for which we logged "no committee" warning, to avoid spam */ lastSlotForNoCommitteeWarning;
459
+ /** The last slot for which we triggered a checkpoint proposal job, to prevent duplicate attempts. */ lastSlotForCheckpointProposalJob;
460
+ /** Last successful checkpoint proposed */ lastCheckpointProposed;
461
+ /** The last epoch for which we logged strategy comparison in fisherman mode. */ lastEpochForStrategyComparison;
462
+ /** The last checkpoint proposal job, tracked so we can await its pending L1 submission during shutdown. */ lastCheckpointProposalJob;
66
463
  /** The maximum number of seconds that the sequencer can be into a slot to transition to a particular state. */ timetable;
67
- enforceTimeTable;
68
- constructor(publisher, validatorClient, globalsBuilder, p2pClient, worldState, slasherClient, blockBuilderFactory, l2BlockSource, l1ToL2MessageSource, publicProcessorFactory, contractDataSource, l1Constants, dateProvider, config = {}, telemetry = getTelemetryClient(), log = createLogger('sequencer')){
69
- this.publisher = publisher;
70
- this.validatorClient = validatorClient;
71
- this.globalsBuilder = globalsBuilder;
72
- this.p2pClient = p2pClient;
73
- this.worldState = worldState;
74
- this.slasherClient = slasherClient;
75
- this.blockBuilderFactory = blockBuilderFactory;
76
- this.l2BlockSource = l2BlockSource;
77
- this.l1ToL2MessageSource = l1ToL2MessageSource;
78
- this.publicProcessorFactory = publicProcessorFactory;
79
- this.contractDataSource = contractDataSource;
80
- this.l1Constants = l1Constants;
81
- this.dateProvider = dateProvider;
82
- this.config = config;
83
- this.log = log;
84
- this.pollingIntervalMs = 1000;
85
- this.maxTxsPerBlock = 32;
86
- this.minTxsPerBlock = 1;
87
- this.maxL1TxInclusionTimeIntoSlot = 0;
88
- this._coinbase = EthAddress.ZERO;
89
- this._feeRecipient = AztecAddress.ZERO;
90
- this.state = SequencerState.STOPPED;
91
- this.allowedInSetup = [];
92
- this.maxBlockSizeInBytes = 1024 * 1024;
93
- this.maxBlockGas = new Gas(100e9, 100e9);
94
- this.isFlushing = false;
95
- this.enforceTimeTable = false;
96
- this.metrics = new SequencerMetrics(telemetry, ()=>this.state, 'Sequencer');
97
- // Register the block builder with the validator client for re-execution
98
- this.validatorClient?.registerBlockBuilder(this.buildBlock.bind(this));
99
- // Register the slasher on the publisher to fetch slashing payloads
100
- this.publisher.registerSlashPayloadGetter(this.slasherClient.getSlashPayload.bind(this.slasherClient));
464
+ /** Config for the sequencer */ config;
465
+ signatureContext;
466
+ constructor(publisherFactory, validatorClient, globalsBuilder, p2pClient, worldState, slasherClient, l2BlockSource, l1ToL2MessageSource, checkpointsBuilder, l1Constants, dateProvider, epochCache, rollupContract, config, telemetry = getTelemetryClient(), log = createLogger('sequencer')){
467
+ super(), this.publisherFactory = publisherFactory, this.validatorClient = validatorClient, this.globalsBuilder = globalsBuilder, this.p2pClient = p2pClient, this.worldState = worldState, this.slasherClient = slasherClient, this.l2BlockSource = l2BlockSource, this.l1ToL2MessageSource = l1ToL2MessageSource, this.checkpointsBuilder = checkpointsBuilder, this.l1Constants = l1Constants, this.dateProvider = dateProvider, this.epochCache = epochCache, this.rollupContract = rollupContract, this.telemetry = telemetry, this.log = log, this.state = (_initProto(this), SequencerState.STOPPED), this.stateEnteredAtMs = performance.now(), this.config = DefaultSequencerConfig;
468
+ this.stateLog = log.createChild('state');
469
+ // Add [FISHERMAN] prefix to logger if in fisherman mode
470
+ if (config.fishermanMode) {
471
+ this.log = log.createChild('[FISHERMAN]');
472
+ }
473
+ this.signatureContext = {
474
+ chainId: config.l1ChainId,
475
+ rollupAddress: config.rollupAddress
476
+ };
477
+ this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
478
+ this.checkpointProposalJobMetrics = new CheckpointProposalJobMetrics(telemetry);
479
+ this.updateConfig(config);
101
480
  }
102
- get tracer() {
103
- return this.metrics.tracer;
481
+ /** Updates sequencer config by the defined values and updates the timetable */ updateConfig(config) {
482
+ const filteredConfig = pickFromSchema(config, SequencerConfigSchema);
483
+ this.log.info(`Updated sequencer config`, omit(filteredConfig, 'txPublicSetupAllowListExtend'));
484
+ this.config = merge(this.config, filteredConfig);
485
+ const p2pPropagationTime = this.config.attestationPropagationTime;
486
+ this.timetable = new SequencerTimetable({
487
+ ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
488
+ aztecSlotDuration: this.aztecSlotDuration,
489
+ l1PublishingTime: this.l1PublishingTime,
490
+ p2pPropagationTime,
491
+ blockDurationMs: this.config.blockDurationMs,
492
+ enforce: this.config.enforceTimeTable
493
+ }, this.metrics, this.log);
104
494
  }
105
- /**
106
- * Updates sequencer config.
107
- * @param config - New parameters.
108
- */ async updateConfig(config) {
109
- this.log.info(`Sequencer config set`, omit(pickFromSchema(config, SequencerConfigSchema), 'allowedInSetup'));
110
- if (config.transactionPollingIntervalMS !== undefined) {
111
- this.pollingIntervalMs = config.transactionPollingIntervalMS;
112
- }
113
- if (config.maxTxsPerBlock !== undefined) {
114
- this.maxTxsPerBlock = config.maxTxsPerBlock;
115
- }
116
- if (config.minTxsPerBlock !== undefined) {
117
- this.minTxsPerBlock = config.minTxsPerBlock;
118
- }
119
- if (config.maxDABlockGas !== undefined) {
120
- this.maxBlockGas = new Gas(config.maxDABlockGas, this.maxBlockGas.l2Gas);
121
- }
122
- if (config.maxL2BlockGas !== undefined) {
123
- this.maxBlockGas = new Gas(this.maxBlockGas.daGas, config.maxL2BlockGas);
124
- }
125
- if (config.coinbase) {
126
- this._coinbase = config.coinbase;
127
- }
128
- if (config.feeRecipient) {
129
- this._feeRecipient = config.feeRecipient;
130
- }
131
- if (config.allowedInSetup) {
132
- this.allowedInSetup = config.allowedInSetup;
133
- } else {
134
- this.allowedInSetup = await getDefaultAllowedSetupFunctions();
135
- }
136
- if (config.maxBlockSizeInBytes !== undefined) {
137
- this.maxBlockSizeInBytes = config.maxBlockSizeInBytes;
138
- }
139
- if (config.governanceProposerPayload) {
140
- this.publisher.setGovernancePayload(config.governanceProposerPayload);
141
- }
142
- if (config.maxL1TxInclusionTimeIntoSlot !== undefined) {
143
- this.maxL1TxInclusionTimeIntoSlot = config.maxL1TxInclusionTimeIntoSlot;
144
- }
145
- if (config.enforceTimeTable !== undefined) {
146
- this.enforceTimeTable = config.enforceTimeTable;
147
- }
148
- this.setTimeTable();
149
- // TODO: Just read everything from the config object as needed instead of copying everything into local vars.
150
- this.config = config;
495
+ /** Initializes the sequencer (precomputes tables). Takes about 3s. */ init() {
496
+ getKzg();
151
497
  }
152
- setTimeTable() {
153
- this.timetable = new SequencerTimetable(this.l1Constants.ethereumSlotDuration, this.aztecSlotDuration, this.maxL1TxInclusionTimeIntoSlot, this.enforceTimeTable, this.metrics, this.log);
154
- this.log.verbose(`Sequencer timetable updated`, {
155
- enforceTimeTable: this.enforceTimeTable
498
+ /** Starts the sequencer and moves to IDLE state. */ start() {
499
+ this.runningPromise = new RunningPromise(this.safeWork.bind(this), this.log, this.config.sequencerPollingIntervalMS);
500
+ this.setState(SequencerState.IDLE, undefined, {
501
+ force: true
156
502
  });
157
- }
158
- /**
159
- * Starts the sequencer and moves to IDLE state.
160
- */ async start() {
161
- await this.updateConfig(this.config);
162
- this.runningPromise = new RunningPromise(this.work.bind(this), this.log, this.pollingIntervalMs);
163
- this.setState(SequencerState.IDLE, 0n, true);
164
503
  this.runningPromise.start();
165
- this.log.info(`Sequencer started with address ${this.publisher.getSenderAddress().toString()}`);
504
+ this.log.info('Started sequencer');
166
505
  }
167
- /**
168
- * Stops the sequencer from processing txs and moves to STOPPED state.
169
- */ async stop() {
170
- this.log.debug(`Stopping sequencer`);
171
- await this.validatorClient?.stop();
506
+ /** Triggers an immediate run of the sequencer, bypassing the polling interval. */ trigger() {
507
+ return this.runningPromise?.trigger();
508
+ }
509
+ /** Stops the sequencer from building blocks and moves to STOPPED state. */ async stop() {
510
+ this.log.info(`Stopping sequencer`);
511
+ this.setState(SequencerState.STOPPING, undefined, {
512
+ force: true
513
+ });
514
+ this.lastCheckpointProposalJob?.interrupt();
515
+ await this.publisherFactory.stopAll();
172
516
  await this.runningPromise?.stop();
173
- this.slasherClient.stop();
174
- this.publisher.interrupt();
175
- this.setState(SequencerState.STOPPED, 0n, true);
517
+ await this.lastCheckpointProposalJob?.awaitPendingSubmission();
518
+ this.setState(SequencerState.STOPPED, undefined, {
519
+ force: true
520
+ });
176
521
  this.log.info('Stopped sequencer');
177
522
  }
178
- /**
179
- * Starts a previously stopped sequencer.
180
- */ restart() {
181
- this.log.info('Restarting sequencer');
182
- this.publisher.restart();
183
- this.runningPromise.start();
184
- this.setState(SequencerState.IDLE, 0n, true);
523
+ /** Main sequencer loop with a try/catch */ async safeWork() {
524
+ try {
525
+ await this.work();
526
+ } catch (err) {
527
+ if (err instanceof SequencerTooSlowError && [
528
+ SequencerState.INITIALIZING_CHECKPOINT,
529
+ SequencerState.PROPOSER_CHECK
530
+ ].includes(err.proposedState)) {
531
+ // No need to alert if we just didn't get to start in time
532
+ this.log.debug(err.message, {
533
+ now: this.dateProvider.nowInSeconds()
534
+ });
535
+ } else {
536
+ // Re-throw other errors
537
+ this.emit('checkpoint-error', {
538
+ error: err
539
+ });
540
+ throw err;
541
+ }
542
+ } finally{
543
+ this.setState(SequencerState.IDLE, undefined);
544
+ }
185
545
  }
186
- /**
187
- * Returns the current state of the sequencer.
188
- * @returns An object with a state entry with one of SequencerState.
189
- */ status() {
546
+ /** Returns the current state of the sequencer. */ status() {
190
547
  return {
191
548
  state: this.state
192
549
  };
193
550
  }
194
- /** Forces the sequencer to bypass all time and tx count checks for the next block and build anyway. */ flush() {
195
- this.isFlushing = true;
196
- }
197
551
  /**
198
- * @notice Performs most of the sequencer duties:
199
- * - Checks if we are up to date
200
- * - If we are and we are the sequencer, collect txs and build a block
201
- * - Collect attestations for the block
202
- * - Submit block
203
- * - If our block for some reason is not included, revert the state
204
- */ async doRealWork() {
205
- this.setState(SequencerState.SYNCHRONIZING, 0n);
206
- // Update state when the previous block has been synced
207
- const chainTip = await this.getChainTip();
208
- // Do not go forward with new block if the previous one has not been mined and processed
209
- if (!chainTip) {
552
+ * Main sequencer loop:
553
+ * - Checks if we are up to date
554
+ * - If we are and we are the sequencer, collect txs and build blocks
555
+ * - Build multiple blocks per slot when configured
556
+ * - Collect attestations for the final block
557
+ * - Submit checkpoint
558
+ */ async work() {
559
+ this.setState(SequencerState.SYNCHRONIZING, undefined);
560
+ const { slot, targetSlot, epoch, targetEpoch, ts, nowSeconds } = this.getSlotContextInNextL1Slot();
561
+ // Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
562
+ const checkpointProposalJob = await this.prepareCheckpointProposal(slot, targetSlot, epoch, targetEpoch, ts, nowSeconds);
563
+ if (!checkpointProposalJob) {
210
564
  return;
211
565
  }
212
- this.setState(SequencerState.PROPOSER_CHECK, 0n);
213
- const newBlockNumber = chainTip.blockNumber + 1;
214
- // If we cannot find a tip archive, assume genesis.
215
- const chainTipArchive = chainTip.archive;
216
- const slot = await this.slotForProposal(chainTipArchive.toBuffer(), BigInt(newBlockNumber));
217
- if (!slot) {
218
- this.log.debug(`Cannot propose block ${newBlockNumber}`);
219
- return;
566
+ // Track the job so we can await its pending L1 submission during shutdown
567
+ this.lastCheckpointProposalJob = checkpointProposalJob;
568
+ // Execute the checkpoint proposal job
569
+ const checkpoint = await checkpointProposalJob.execute();
570
+ // Update last checkpoint proposed (currently unused)
571
+ if (checkpoint) {
572
+ this.lastCheckpointProposed = checkpoint;
573
+ }
574
+ // Log fee strategy comparison if on fisherman (uses target epoch since we mirror the proposer's perspective)
575
+ if (this.config.fishermanMode && (this.lastEpochForStrategyComparison === undefined || targetEpoch > this.lastEpochForStrategyComparison)) {
576
+ this.logStrategyComparison(targetEpoch, checkpointProposalJob.getPublisher());
577
+ this.lastEpochForStrategyComparison = targetEpoch;
578
+ }
579
+ return checkpoint;
580
+ }
581
+ /** Returns slot and target slot from a single clock snapshot. */ getSlotContextInNextL1Slot() {
582
+ const { slot, ts, nowSeconds, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
583
+ const targetSlot = SlotNumber(slot + PROPOSER_PIPELINING_SLOT_OFFSET);
584
+ return {
585
+ slot,
586
+ targetSlot,
587
+ epoch,
588
+ targetEpoch: getEpochAtSlot(targetSlot, this.l1Constants),
589
+ ts,
590
+ nowSeconds
591
+ };
592
+ }
593
+ /**
594
+ * Prepares the checkpoint proposal by performing all necessary checks and setup.
595
+ * This is the initial step in the main loop.
596
+ * @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
597
+ */ async prepareCheckpointProposal(slot, targetSlot, epoch, targetEpoch, ts, nowSeconds) {
598
+ // Check we have not already processed this target slot (cheapest check)
599
+ // We only check this if enforce timetable is set, since we want to keep processing the same slot if we are not
600
+ // running against actual time (eg when we use sandbox-style automining)
601
+ if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= targetSlot && this.config.enforceTimeTable) {
602
+ this.log.trace(`Target slot ${targetSlot} has already been processed`);
603
+ return undefined;
604
+ }
605
+ // But if we have already proposed for this slot, then we definitely have to skip it, automining or not
606
+ if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= targetSlot) {
607
+ this.log.trace(`Slot ${targetSlot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`);
608
+ return undefined;
220
609
  }
221
- this.log.debug(`Can propose block ${newBlockNumber} at slot ${slot}`);
222
- const newGlobalVariables = await this.globalsBuilder.buildGlobalVariables(new Fr(newBlockNumber), this._coinbase, this._feeRecipient, slot);
223
- const enqueueGovernanceVotePromise = this.publisher.enqueueCastVote(slot, newGlobalVariables.timestamp.toBigInt(), VoteType.GOVERNANCE);
224
- const enqueueSlashingVotePromise = this.publisher.enqueueCastVote(slot, newGlobalVariables.timestamp.toBigInt(), VoteType.SLASHING);
225
- this.setState(SequencerState.INITIALIZING_PROPOSAL, slot);
226
- this.log.verbose(`Preparing proposal for block ${newBlockNumber} at slot ${slot}`, {
227
- chainTipArchive,
228
- blockNumber: newBlockNumber,
610
+ // Test-only: skip proposing for explicitly paused slots. Attestation paths run in the validator
611
+ // client and are not gated by this hook, so paused proposers still attest to others' proposals.
612
+ if (this.config.pauseProposingForSlots?.some((s)=>s === targetSlot)) {
613
+ this.log.warn(`Skipping proposal for paused slot ${targetSlot} (test-only pauseProposingForSlots hook)`, {
614
+ targetSlot
615
+ });
616
+ return undefined;
617
+ }
618
+ // Check all components are synced to latest as seen by the archiver (queries all subsystems)
619
+ const syncedTo = await this.checkSync({
620
+ ts,
229
621
  slot
230
622
  });
231
- // If I created a "partial" header here that should make our job much easier.
232
- const proposalHeader = new BlockHeader(new AppendOnlyTreeSnapshot(chainTipArchive, 1), ContentCommitment.empty(), StateReference.empty(), newGlobalVariables, Fr.ZERO, Fr.ZERO);
233
- let finishedFlushing = false;
234
- const pendingTxCount = await this.p2pClient.getPendingTxCount();
235
- if (pendingTxCount >= this.minTxsPerBlock || this.isFlushing) {
236
- // We don't fetch exactly maxTxsPerBlock txs here because we may not need all of them if we hit a limit before,
237
- // and also we may need to fetch more if we don't have enough valid txs.
238
- const pendingTxs = this.p2pClient.iteratePendingTxs();
239
- await this.buildBlockAndEnqueuePublish(pendingTxs, proposalHeader).catch((err)=>{
240
- this.log.error(`Error building/enqueuing block`, err, {
241
- blockNumber: newBlockNumber,
242
- slot
623
+ if (!syncedTo) {
624
+ await this.tryVoteWhenSyncFails({
625
+ slot,
626
+ targetSlot,
627
+ ts
628
+ });
629
+ return undefined;
630
+ }
631
+ // If escape hatch is open for the target epoch, do not start checkpoint proposal work and do not attempt invalidations.
632
+ // Still perform governance/slashing voting (as proposer) once per slot.
633
+ // When pipelining, we check the target epoch (slot+1's epoch) since that's the epoch we're building for.
634
+ const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(targetEpoch);
635
+ if (isEscapeHatchOpen) {
636
+ this.setState(SequencerState.PROPOSER_CHECK, slot);
637
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
638
+ if (canPropose) {
639
+ await this.tryVoteWhenEscapeHatchOpen({
640
+ slot,
641
+ targetSlot,
642
+ proposer
243
643
  });
644
+ } else {
645
+ this.log.trace(`Escape hatch open but we are not proposer, skipping vote-only actions`, {
646
+ slot,
647
+ epoch,
648
+ proposer
649
+ });
650
+ }
651
+ return undefined;
652
+ }
653
+ // Next checkpoint follows from the last synced one
654
+ const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
655
+ const logCtx = {
656
+ nowSeconds,
657
+ syncedToL2Slot: syncedTo.syncedL2Slot,
658
+ slot,
659
+ targetSlot,
660
+ slotTs: ts,
661
+ checkpointNumber,
662
+ isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex')
663
+ };
664
+ // Check that we are a proposer for the target slot.
665
+ this.setState(SequencerState.PROPOSER_CHECK, slot);
666
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
667
+ // If we are not a proposer check if we should invalidate an invalid checkpoint, and bail
668
+ if (!canPropose) {
669
+ await this.considerInvalidatingCheckpoint(syncedTo, slot);
670
+ return undefined;
671
+ }
672
+ // Guard: don't exceed 1-deep pipeline. Without a proposed checkpoint, we can only build
673
+ // confirmed + 1. With a proposed checkpoint, we can build confirmed + 2.
674
+ const confirmedCkpt = syncedTo.checkpointedCheckpointNumber;
675
+ if (checkpointNumber > confirmedCkpt + 2) {
676
+ this.log.verbose(`Skipping slot ${targetSlot}: checkpoint ${checkpointNumber} exceeds max pipeline depth (confirmed=${confirmedCkpt})`);
677
+ return undefined;
678
+ }
679
+ // Check that the target slot is not taken by a block already (should never happen, since only us can propose for this slot)
680
+ if (syncedTo.blockData && syncedTo.blockData.header.getSlot() >= targetSlot) {
681
+ this.log.warn(`Cannot propose block at target slot ${targetSlot} since that slot was taken by block ${syncedTo.blockNumber}`, {
682
+ ...logCtx,
683
+ block: syncedTo.blockData.header.toInspect()
684
+ });
685
+ this.metrics.recordCheckpointPrecheckFailed('slot_already_taken');
686
+ return undefined;
687
+ }
688
+ // We now need to get ourselves a publisher.
689
+ // The returned attestor will be the one we provided if we provided one.
690
+ // Otherwise it will be a valid attestor for the returned publisher.
691
+ // In fisherman mode, pass undefined to use the fisherman's own keystore instead of the actual proposer's
692
+ const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
693
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
694
+ this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
695
+ // Prepare invalidation request if the pending chain is invalid (returns undefined if no need).
696
+ // Only simulate invalidation when there's no proposed parent, since we assume the proposed parent
697
+ // will invalidate the currently invalid checkpoint on L1.
698
+ const invalidateCheckpoint = syncedTo.hasProposedCheckpoint || syncedTo.pendingChainValidationStatus.valid ? undefined : await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
699
+ // Determine the correct archive and L1 state overrides for the canProposeAt check.
700
+ // The L1 contract reads archives[proposedCheckpointNumber] and compares it with the provided archive.
701
+ // When invalidating or pipelining, the local archive may differ from L1's, so we adjust accordingly.
702
+ let archiveForCheck = syncedTo.archive;
703
+ if (syncedTo.hasProposedCheckpoint) {
704
+ this.metrics.recordPipelineDepth(syncedTo.checkpointNumber - syncedTo.checkpointedCheckpointNumber);
705
+ this.log.verbose(`Building on top of proposed checkpoint (pending=${syncedTo.proposedCheckpointData?.checkpointNumber}) for target slot ${targetSlot}`, {
706
+ targetSlot,
707
+ parentCheckpointNumber: CheckpointNumber(checkpointNumber - 1)
244
708
  });
245
- finishedFlushing = true;
709
+ // Match what L1 will see at archives[pending] once the proposed parent lands: the parent's
710
+ // own archive root from the gossiped proposal. `syncedTo.archive` is the world-state-local
711
+ // view and can transiently diverge from the proposed parent (e.g. before the proposed
712
+ // parent's blocks have been applied locally); diverging here would cause the canProposeAt
713
+ // override to set archives[pending] to one value while we present another for comparison.
714
+ archiveForCheck = syncedTo.proposedCheckpointData.archive.root;
715
+ } else if (invalidateCheckpoint) {
716
+ // After invalidation, L1 will roll back to checkpoint N-1. The archive at N-1 already
717
+ // exists on L1, so we just pass the matching archive (the lastArchive of the invalid checkpoint).
718
+ archiveForCheck = invalidateCheckpoint.lastArchive;
719
+ this.metrics.recordPipelineDepth(0);
246
720
  } else {
247
- this.log.debug(`Not enough txs to build block ${newBlockNumber} at slot ${slot}: got ${pendingTxCount} txs, need ${this.minTxsPerBlock}`);
721
+ this.metrics.recordPipelineDepth(0);
248
722
  }
249
- await enqueueGovernanceVotePromise.catch((err)=>{
250
- this.log.error(`Error enqueuing governance vote`, err, {
251
- blockNumber: newBlockNumber,
252
- slot
723
+ // Build the simulation plan: pending/proven override from pipelining or invalidation (or the
724
+ // current snapshot when neither applies, to short-circuit any pending prune in simulation),
725
+ // plus the parent checkpoint cell and fee header when pipelining.
726
+ const simulationOverridesPlan = await buildCheckpointSimulationOverridesPlan({
727
+ checkpointNumber,
728
+ proposedCheckpointData: syncedTo.hasProposedCheckpoint ? syncedTo.proposedCheckpointData : undefined,
729
+ invalidateToPendingCheckpointNumber: invalidateCheckpoint?.forcePendingCheckpointNumber,
730
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
731
+ rollup: this.rollupContract,
732
+ signatureContext: this.signatureContext,
733
+ log: this.log
734
+ });
735
+ // The plan always pins both pending/proven (to short-circuit `canPruneAtTime` in simulation),
736
+ // so `provenOverride` always reflects the assumed proven checkpoint we are pinning the
737
+ // simulation to. We additionally warn when the pin is load-bearing — i.e. when a prune would
738
+ // actually fire at the target slot without it — so observers can spot "we are building
739
+ // optimistically across a pruning boundary" in the logs.
740
+ const provenOverride = simulationOverridesPlan?.chainTipsOverride?.proven;
741
+ if (provenOverride !== undefined && await this.l2BlockSource.isPruneDueAtSlot(targetSlot)) {
742
+ this.log.warn(`Assuming proof for epoch ending at checkpoint ${provenOverride} lands by target slot ${targetSlot}`, {
743
+ checkpointNumber,
744
+ slot,
745
+ targetSlot,
746
+ provenOverride
253
747
  });
748
+ }
749
+ this.emit('preparing-checkpoint', {
750
+ targetSlot,
751
+ checkpointNumber,
752
+ hadProposedParent: syncedTo.hasProposedCheckpoint,
753
+ provenOverride,
754
+ simulatedPending: simulationOverridesPlan?.chainTipsOverride?.pending
254
755
  });
255
- await enqueueSlashingVotePromise.catch((err)=>{
256
- this.log.error(`Error enqueuing slashing vote`, err, {
257
- blockNumber: newBlockNumber,
756
+ const canProposeCheck = await publisher.canProposeAt(archiveForCheck, proposer ?? EthAddress.ZERO, simulationOverridesPlan);
757
+ const proposeContext = {
758
+ hasProposedCheckpoint: syncedTo.hasProposedCheckpoint,
759
+ proposedCheckpointNumber: syncedTo.proposedCheckpointData?.checkpointNumber,
760
+ checkpointedCheckpointNumber: syncedTo.checkpointedCheckpointNumber,
761
+ isInvalidating: !!invalidateCheckpoint,
762
+ invalidatingCheckpointNumber: invalidateCheckpoint?.checkpointNumber,
763
+ archiveForCheck: archiveForCheck.toString(),
764
+ overridePendingCheckpointNumber: simulationOverridesPlan?.chainTipsOverride?.pending,
765
+ overrideArchive: simulationOverridesPlan?.pendingCheckpointState?.archive,
766
+ overrideFeeHeader: simulationOverridesPlan?.pendingCheckpointState?.feeHeader
767
+ };
768
+ if (canProposeCheck === undefined) {
769
+ this.log.warn(`Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`, {
770
+ ...logCtx,
771
+ ...proposeContext
772
+ });
773
+ this.emit('proposer-rollup-check-failed', {
774
+ reason: 'Rollup contract check failed',
258
775
  slot
259
776
  });
260
- });
261
- await this.publisher.sendRequests();
262
- if (finishedFlushing) {
263
- this.isFlushing = false;
777
+ this.metrics.recordCheckpointPrecheckFailed('rollup_contract_check_failed');
778
+ return undefined;
264
779
  }
265
- this.setState(SequencerState.IDLE, 0n);
266
- }
267
- async work() {
268
- try {
269
- await this.doRealWork();
270
- } catch (err) {
271
- if (err instanceof SequencerTooSlowError) {
272
- this.log.warn(err.message);
273
- } else {
274
- // Re-throw other errors
275
- throw err;
276
- }
277
- } finally{
278
- this.setState(SequencerState.IDLE, 0n);
780
+ if (canProposeCheck.slot !== targetSlot) {
781
+ this.log.warn(`Cannot propose block due to slot mismatch with rollup contract (this can be caused by a clock out of sync). Expected slot ${targetSlot} but got ${canProposeCheck.slot}.`, {
782
+ ...logCtx,
783
+ ...proposeContext,
784
+ rollup: canProposeCheck,
785
+ expectedSlot: targetSlot
786
+ });
787
+ this.emit('proposer-rollup-check-failed', {
788
+ reason: 'Slot mismatch',
789
+ slot
790
+ });
791
+ this.metrics.recordCheckpointPrecheckFailed('slot_mismatch');
792
+ return undefined;
793
+ }
794
+ if (canProposeCheck.checkpointNumber !== checkpointNumber) {
795
+ this.log.warn(`Cannot propose due to block mismatch with rollup contract (this can be caused by a pending archiver sync). Expected checkpoint ${checkpointNumber} but got ${canProposeCheck.checkpointNumber}.`, {
796
+ ...logCtx,
797
+ ...proposeContext,
798
+ rollup: canProposeCheck,
799
+ expectedSlot: slot
800
+ });
801
+ this.emit('proposer-rollup-check-failed', {
802
+ reason: 'Block mismatch',
803
+ slot
804
+ });
805
+ this.metrics.recordCheckpointPrecheckFailed('block_number_mismatch');
806
+ return undefined;
279
807
  }
808
+ this.lastSlotForCheckpointProposalJob = targetSlot;
809
+ await this.p2pClient.prepareForSlot(targetSlot);
810
+ this.log.info(`Preparing checkpoint proposal ${checkpointNumber} for target slot ${targetSlot} during wall-clock slot ${slot}`, {
811
+ ...logCtx,
812
+ ...proposeContext,
813
+ proposer
814
+ });
815
+ // Create and return the checkpoint proposal job
816
+ return this.createCheckpointProposalJob(slot, targetSlot, targetEpoch, checkpointNumber, syncedTo.blockNumber, syncedTo.checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, syncedTo.proposedCheckpointData);
280
817
  }
281
- getForwarderAddress() {
282
- return this.publisher.getForwarderAddress();
818
+ createCheckpointProposalJob(slot, targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, proposedCheckpointData) {
819
+ return new CheckpointProposalJob(slot, targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, checkpointedCheckpointNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, this.validatorClient, this.globalsBuilder, this.p2pClient, this.worldState, this.l1ToL2MessageSource, this.l2BlockSource, this.checkpointsBuilder, this.l2BlockSource, this.l1Constants, this.signatureContext, this.config, this.timetable, this.slasherClient, this.epochCache, this.dateProvider, this.metrics, this.checkpointProposalJobMetrics.createRecorder(), this, (state, slot, timeReferenceSlot)=>this.setState(state, slot, {
820
+ timeReferenceSlot
821
+ }), this.tracer, this.log.getBindings(), proposedCheckpointData);
283
822
  }
284
823
  /**
285
- * Checks if we can propose at the next block and returns the slot number if we can.
286
- * @param tipArchive - The archive of the previous block.
287
- * @param proposalBlockNumber - The block number of the proposal.
288
- * @returns The slot number if we can propose at the next block, otherwise undefined.
289
- */ async slotForProposal(tipArchive, proposalBlockNumber) {
290
- const result = await this.publisher.canProposeAtNextEthBlock(tipArchive);
291
- if (!result) {
292
- return undefined;
293
- }
294
- const [slot, blockNumber] = result;
295
- if (proposalBlockNumber !== blockNumber) {
296
- const msg = `Sequencer block number mismatch. Expected ${proposalBlockNumber} but got ${blockNumber}.`;
297
- this.log.warn(msg);
298
- throw new Error(msg);
299
- }
300
- return slot;
824
+ * Returns the current sequencer state.
825
+ */ getState() {
826
+ return this.state;
301
827
  }
302
828
  /**
303
- * Sets the sequencer state and checks if we have enough time left in the slot to transition to the new state.
829
+ * Internal helper for setting the sequencer state and checks if we have enough time left in the slot to transition to the new state.
304
830
  * @param proposedState - The new state to transition to.
305
- * @param currentSlotNumber - The current slot number.
831
+ * @param slotNumber - The logical slot associated with the new state.
306
832
  * @param force - Whether to force the transition even if the sequencer is stopped.
307
- *
308
- * @dev If the `currentSlotNumber` doesn't matter (e.g. transitioning to IDLE), pass in `0n`;
309
- * it is only used to check if we have enough time left in the slot to transition to the new state.
310
- */ setState(proposedState, currentSlotNumber, force = false) {
311
- if (this.state === SequencerState.STOPPED && force !== true) {
833
+ * @param timeReferenceSlot - The slot to use for deadline checks when it differs from the logical slot.
834
+ */ setState(proposedState, slotNumber, opts = {}) {
835
+ if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
836
+ this.log.warn(`Cannot set sequencer to ${proposedState} as it is stopping.`);
837
+ throw new SequencerInterruptedError();
838
+ }
839
+ if (this.state === SequencerState.STOPPED && !opts.force) {
312
840
  this.log.warn(`Cannot set sequencer from ${this.state} to ${proposedState} as it is stopped.`);
313
841
  return;
314
842
  }
315
- const secondsIntoSlot = this.getSecondsIntoSlot(currentSlotNumber);
316
- this.timetable.assertTimeLeft(proposedState, secondsIntoSlot);
317
- this.log.debug(`Transitioning from ${this.state} to ${proposedState}`);
843
+ let secondsIntoSlot = undefined;
844
+ const timeReferenceSlot = opts.timeReferenceSlot ?? slotNumber;
845
+ if (timeReferenceSlot !== undefined) {
846
+ secondsIntoSlot = this.getSecondsIntoSlot(timeReferenceSlot);
847
+ this.timetable.assertTimeLeft(proposedState, secondsIntoSlot);
848
+ }
849
+ const oldState = this.state;
850
+ const oldStateSlotNumber = this.stateSlotNumber;
851
+ const stateChanged = proposedState !== oldState;
852
+ const transitionAtMs = performance.now();
853
+ const stateDurationMs = transitionAtMs - this.stateEnteredAtMs;
854
+ const boringStates = [
855
+ SequencerState.IDLE,
856
+ SequencerState.SYNCHRONIZING
857
+ ];
858
+ const logLevel = boringStates.includes(proposedState) && boringStates.includes(oldState) ? 'trace' : 'debug';
859
+ this.stateLog[logLevel](`Transitioning from ${oldState} to ${proposedState}`, {
860
+ oldState,
861
+ newState: proposedState,
862
+ slotNumber,
863
+ timeReferenceSlot,
864
+ stateSlotNumber: oldStateSlotNumber,
865
+ secondsIntoSlot,
866
+ ...stateChanged && {
867
+ stateDurationMs: Math.ceil(stateDurationMs)
868
+ }
869
+ });
870
+ this.emit('state-changed', {
871
+ oldState,
872
+ newState: proposedState,
873
+ secondsIntoSlot,
874
+ slot: slotNumber,
875
+ timeReferenceSlot
876
+ });
877
+ if (stateChanged) {
878
+ this.metrics.recordStateDuration(stateDurationMs, oldState);
879
+ this.stateEnteredAtMs = transitionAtMs;
880
+ this.stateSlotNumber = slotNumber;
881
+ }
318
882
  this.state = proposedState;
319
883
  }
320
884
  /**
321
- * Build a block
322
- *
323
- * Shared between the sequencer and the validator for re-execution
324
- *
325
- * @param pendingTxs - The pending transactions to construct the block from
326
- * @param newGlobalVariables - The global variables for the new block
327
- * @param historicalHeader - The historical header of the parent
328
- * @param opts - Whether to just validate the block as a validator, as opposed to building it as a proposal
329
- */ async buildBlock(pendingTxs, newGlobalVariables, opts = {}) {
330
- const blockNumber = newGlobalVariables.blockNumber.toNumber();
331
- const slot = newGlobalVariables.slotNumber.toBigInt();
332
- this.log.debug(`Requesting L1 to L2 messages from contract for block ${blockNumber}`);
333
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(BigInt(blockNumber));
334
- const msgCount = l1ToL2Messages.length;
335
- this.log.verbose(`Building block ${blockNumber} for slot ${slot}`, {
336
- slot,
337
- blockNumber,
338
- msgCount,
339
- validator: opts.validateOnly
340
- });
341
- // Sync to the previous block at least
342
- await this.worldState.syncImmediate(blockNumber - 1);
343
- this.log.debug(`Synced to previous block ${blockNumber - 1}`);
344
- // NB: separating the dbs because both should update the state
345
- const publicProcessorFork = await this.worldState.fork();
346
- const orchestratorFork = await this.worldState.fork();
347
- const previousBlockHeader = (await this.l2BlockSource.getBlock(blockNumber - 1))?.header ?? orchestratorFork.getInitialHeader();
348
- try {
349
- const processor = this.publicProcessorFactory.create(publicProcessorFork, newGlobalVariables, true);
350
- const blockBuildingTimer = new Timer();
351
- const blockBuilder = this.blockBuilderFactory.create(orchestratorFork);
352
- await blockBuilder.startNewBlock(newGlobalVariables, l1ToL2Messages, previousBlockHeader);
353
- // Deadline for processing depends on whether we're proposing a block
354
- const secondsIntoSlot = this.getSecondsIntoSlot(slot);
355
- const processingEndTimeWithinSlot = opts.validateOnly ? this.timetable.getValidatorReexecTimeEnd(secondsIntoSlot) : this.timetable.getBlockProposalExecTimeEnd(secondsIntoSlot);
356
- // Deadline is only set if enforceTimeTable is enabled.
357
- const deadline = this.enforceTimeTable ? new Date((this.getSlotStartTimestamp(slot) + processingEndTimeWithinSlot) * 1000) : undefined;
358
- this.log.verbose(`Processing pending txs`, {
885
+ * Returns whether all dependencies have caught up.
886
+ * We don't check against the previous block submitted since it may have been reorg'd out.
887
+ */ async checkSync(args) {
888
+ // Check that the archiver has fully synced the L2 slot before the one we want to propose in.
889
+ // The archiver reports sync progress via L1 block timestamps and synced checkpoint slots.
890
+ // See getSyncedL2SlotNumber for how missed L1 blocks are handled.
891
+ const syncedL2Slot = await this.l2BlockSource.getSyncedL2SlotNumber();
892
+ const { slot } = args;
893
+ if (syncedL2Slot === undefined || syncedL2Slot + 1 < slot) {
894
+ this.log.debug(`Cannot propose block at next L2 slot ${slot} due to pending sync from L1`, {
359
895
  slot,
360
- slotStart: new Date(this.getSlotStartTimestamp(slot) * 1000),
361
- now: new Date(this.dateProvider.now()),
362
- deadline
896
+ syncedL2Slot
363
897
  });
364
- const validators = createValidatorsForBlockBuilding(publicProcessorFork, this.contractDataSource, newGlobalVariables, this.allowedInSetup);
365
- // TODO(#11000): Public processor should just handle processing, one tx at a time. It should be responsibility
366
- // of the sequencer to update world state and iterate over txs. We should refactor this along with unifying the
367
- // publicProcessorFork and orchestratorFork, to avoid doing tree insertions twice when building the block.
368
- const proposerLimits = {
369
- maxTransactions: this.maxTxsPerBlock,
370
- maxBlockSize: this.maxBlockSizeInBytes,
371
- maxBlockGas: this.maxBlockGas
372
- };
373
- const limits = opts.validateOnly ? {
374
- deadline
375
- } : {
376
- deadline,
377
- ...proposerLimits
898
+ return undefined;
899
+ }
900
+ const syncedBlocks = await Promise.all([
901
+ this.worldState.status().then(({ syncSummary })=>({
902
+ number: syncSummary.latestBlockNumber,
903
+ hash: syncSummary.latestBlockHash
904
+ })),
905
+ this.l2BlockSource.getL2Tips().then((t)=>({
906
+ proposed: t.proposed,
907
+ checkpointed: t.checkpointed,
908
+ proposedCheckpoint: t.proposedCheckpoint
909
+ })),
910
+ this.p2pClient.getStatus().then((p2p)=>p2p.syncedToL2Block),
911
+ this.l1ToL2MessageSource.getL2Tips().then((t)=>({
912
+ proposed: t.proposed,
913
+ checkpointed: t.checkpointed
914
+ })),
915
+ this.l2BlockSource.getPendingChainValidationStatus(),
916
+ this.l2BlockSource.getProposedCheckpointData()
917
+ ]);
918
+ const [worldState, l2Tips, p2p, l1ToL2MessageSourceTips, pendingChainValidationStatus, proposedCheckpointData] = syncedBlocks;
919
+ const result = worldState.hash === l2Tips.proposed.hash && p2p.hash === l2Tips.proposed.hash && l1ToL2MessageSourceTips.proposed.hash === l2Tips.proposed.hash && l1ToL2MessageSourceTips.checkpointed.block.hash === l2Tips.checkpointed.block.hash && l1ToL2MessageSourceTips.checkpointed.checkpoint.hash === l2Tips.checkpointed.checkpoint.hash;
920
+ if (!result) {
921
+ this.log.debug(`Sequencer sync check failed`, {
922
+ worldState,
923
+ l2BlockSource: l2Tips.proposed,
924
+ p2p,
925
+ l1ToL2MessageSourceTips
926
+ });
927
+ return undefined;
928
+ }
929
+ const blockNumber = worldState.number;
930
+ const blockData = await this.l2BlockSource.getBlockData({
931
+ number: blockNumber
932
+ });
933
+ if (!blockData) {
934
+ this.log.warn(`Sequencer sync check failed: failed to get L2 block data ${blockNumber} from the archiver`, {
935
+ blockNumber,
936
+ l2Tips,
937
+ syncedL2Slot,
938
+ ...args
939
+ });
940
+ return undefined;
941
+ }
942
+ // Refuse to build a checkpoint on top of a proposed block whose enclosing checkpoint was never
943
+ // proposed. Under pipelining we may have received and reexecuted such a block locally — advancing
944
+ // our world-state tip past the checkpointed tip — while the proposing node never published the
945
+ // matching proposed checkpoint (e.g. it crashed before assembling it). Building on this orphan block
946
+ // would fork the chain off a tip no other node can follow. The archiver prunes these orphan blocks
947
+ // once their build slot ends; this guard is the correctness barrier during the grace window before.
948
+ if (blockData.checkpointNumber > l2Tips.checkpointed.checkpoint.number && (l2Tips.proposedCheckpoint.checkpoint.number !== blockData.checkpointNumber || proposedCheckpointData?.checkpointNumber !== blockData.checkpointNumber)) {
949
+ const logCtx = {
950
+ blockCheckpointNumber: blockData.checkpointNumber,
951
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
952
+ proposedCheckpointTipNumber: l2Tips.proposedCheckpoint.checkpoint.number,
953
+ proposedCheckpointDataNumber: proposedCheckpointData?.checkpointNumber,
954
+ blockNumber: blockData.header.getBlockNumber(),
955
+ blockSlot: blockData.header.getSlot(),
956
+ syncedL2Slot,
957
+ ...args
378
958
  };
379
- const [publicProcessorDuration, [processedTxs, failedTxs]] = await elapsed(()=>processor.process(pendingTxs, limits, validators));
380
- if (!opts.validateOnly && failedTxs.length > 0) {
381
- const failedTxData = failedTxs.map((fail)=>fail.tx);
382
- const failedTxHashes = await Tx.getHashes(failedTxData);
383
- this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
384
- await this.p2pClient.deleteTxs(failedTxHashes);
385
- }
386
- if (!opts.validateOnly && // We check for minTxCount only if we are proposing a block, not if we are validating it
387
- !this.isFlushing && // And we skip the check when flushing, since we want all pending txs to go out, no matter if too few
388
- this.minTxsPerBlock !== undefined && processedTxs.length < this.minTxsPerBlock) {
389
- this.log.warn(`Block ${blockNumber} has too few txs to be proposed (got ${processedTxs.length} but required ${this.minTxsPerBlock})`, {
390
- slot,
391
- blockNumber,
392
- processedTxCount: processedTxs.length
393
- });
394
- throw new Error(`Block has too few successful txs to be proposed`);
959
+ // Under pipelining the block proposal for a checkpoint leads its checkpoint proposal by up to one
960
+ // slot, so a world-state tip sitting in an as-yet-unproposed checkpoint is the expected steady state
961
+ // until that checkpoint is due. Only treat it as abnormal — and warn — once the checkpoint is overdue
962
+ // by the same deadline the archiver uses to prune the orphan block (see pruneOrphanProposedBlocks).
963
+ // Before then this is normal pipelining and we wait it out quietly.
964
+ if (this.isProposedCheckpointOverdue(blockData.header.getSlot())) {
965
+ this.log.warn(`Sequencer sync check failed: proposed block has no matching proposed checkpoint`, logCtx);
966
+ } else {
967
+ this.log.debug(`Waiting for proposed checkpoint to catch up with reexecuted block`, logCtx);
395
968
  }
396
- const start = process.hrtime.bigint();
397
- await blockBuilder.addTxs(processedTxs);
398
- const end = process.hrtime.bigint();
399
- const duration = Number(end - start) / 1_000;
400
- this.metrics.recordBlockBuilderTreeInsertions(duration);
401
- // All real transactions have been added, set the block as full and pad if needed
402
- const block = await blockBuilder.setBlockCompleted();
403
- // How much public gas was processed
404
- const publicGas = processedTxs.reduce((acc, tx)=>acc.add(tx.gasUsed.publicGas), Gas.empty());
405
- return {
406
- block,
407
- publicGas,
408
- publicProcessorDuration,
409
- numMsgs: l1ToL2Messages.length,
410
- numTxs: processedTxs.length,
411
- numFailedTxs: failedTxs.length,
412
- blockBuildingTimer
413
- };
414
- } finally{
415
- // We create a fresh processor each time to reset any cached state (eg storage writes)
416
- // We wait a bit to close the forks since the processor may still be working on a dangling tx
417
- // which was interrupted due to the processingDeadline being hit.
418
- // eslint-disable-next-line @typescript-eslint/no-misused-promises
419
- setTimeout(async ()=>{
420
- try {
421
- await publicProcessorFork.close();
422
- await orchestratorFork.close();
423
- } catch (err) {
424
- // This can happen if the sequencer is stopped before we hit this timeout.
425
- this.log.warn(`Error closing forks for block processing`, err);
426
- }
427
- }, 5000);
969
+ return undefined;
428
970
  }
971
+ const hasProposedCheckpoint = l2Tips.proposedCheckpoint.checkpoint.number > l2Tips.checkpointed.checkpoint.number;
972
+ // The l2Tips and proposedCheckpointData reads above come from independent archiver snapshots
973
+ // (a JS-side tips cache vs. a direct store read on `#proposedCheckpoints`). A concurrent archiver
974
+ // write that mutates both can be observed split, leaving us with `hasProposedCheckpoint=true` but
975
+ // no proposedCheckpointData (or one whose number doesn't match the tip). Refuse to proceed in that
976
+ // window — the next checkSync tick will see a coherent snapshot.
977
+ if (hasProposedCheckpoint && (!proposedCheckpointData || proposedCheckpointData.checkpointNumber !== l2Tips.proposedCheckpoint.checkpoint.number)) {
978
+ this.log.warn(`Sequencer sync check failed: inconsistent proposed-checkpoint state`, {
979
+ proposedCheckpointTipNumber: l2Tips.proposedCheckpoint.checkpoint.number,
980
+ checkpointedTipNumber: l2Tips.checkpointed.checkpoint.number,
981
+ proposedCheckpointDataNumber: proposedCheckpointData?.checkpointNumber,
982
+ syncedL2Slot,
983
+ ...args
984
+ });
985
+ return undefined;
986
+ }
987
+ // Check that the proposed checkpoint is indeed the parent of the checkpoint we'll be building
988
+ // The checkpoint number to build is derived as blockData.checkpointNumber + 1
989
+ if (proposedCheckpointData && proposedCheckpointData.checkpointNumber !== blockData.checkpointNumber) {
990
+ this.log.warn(`Sequencer sync check failed: proposed checkpoint number mismatch`, {
991
+ proposedCheckpointNumber: proposedCheckpointData.checkpointNumber,
992
+ blockCheckpointNumber: blockData.checkpointNumber,
993
+ syncedL2Slot,
994
+ ...args
995
+ });
996
+ return undefined;
997
+ }
998
+ return {
999
+ blockData,
1000
+ blockNumber: blockData.header.getBlockNumber(),
1001
+ checkpointNumber: blockData.checkpointNumber,
1002
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
1003
+ archive: blockData.archive.root,
1004
+ hasProposedCheckpoint,
1005
+ proposedCheckpointData,
1006
+ syncedL2Slot,
1007
+ pendingChainValidationStatus
1008
+ };
429
1009
  }
430
1010
  /**
431
- * @notice Build and propose a block to the chain
432
- *
433
- * @dev MUST throw instead of exiting early to ensure that world-state
434
- * is being rolled back if the block is dropped.
435
- *
436
- * @param pendingTxs - Iterable of pending transactions to construct the block from
437
- * @param proposalHeader - The partial header constructed for the proposal
438
- */ async buildBlockAndEnqueuePublish(pendingTxs, proposalHeader) {
439
- await this.publisher.validateBlockForSubmission(proposalHeader);
440
- const newGlobalVariables = proposalHeader.globalVariables;
441
- const blockNumber = newGlobalVariables.blockNumber.toNumber();
442
- const slot = newGlobalVariables.slotNumber.toBigInt();
443
- // this.metrics.recordNewBlock(blockNumber, validTxs.length);
444
- const workTimer = new Timer();
445
- this.setState(SequencerState.CREATING_BLOCK, slot);
1011
+ * Whether the enclosing checkpoint of a reexecuted block is overdue: past the deadline by which a
1012
+ * well-behaved proposer should have published it. Mirrors the archiver's orphan-prune deadline (the
1013
+ * start of the slot after the block's build slot, plus a grace period) so the sequencer only warns
1014
+ * about a missing proposed checkpoint once the archiver itself would prune the orphan block. The grace
1015
+ * is derived from the block build duration the same way the archiver defaults it at node wiring.
1016
+ */ isProposedCheckpointOverdue(blockSlot) {
1017
+ const expectedBySlot = SlotNumber(Number(blockSlot) - PROPOSER_PIPELINING_SLOT_OFFSET + 1);
1018
+ const graceSeconds = this.config.blockDurationMs !== undefined ? Math.ceil(this.config.blockDurationMs / 1000) : MIN_EXECUTION_TIME;
1019
+ const expectedByTime = getTimestampForSlot(expectedBySlot, this.l1Constants) + BigInt(graceSeconds);
1020
+ return BigInt(this.dateProvider.nowInSeconds()) >= expectedByTime;
1021
+ }
1022
+ /**
1023
+ * Checks if we are the proposer for the next slot.
1024
+ * @returns True if we can propose, and the proposer address (undefined if anyone can propose)
1025
+ */ async checkCanPropose(targetSlot) {
1026
+ let proposer;
446
1027
  try {
447
- const buildBlockRes = await this.buildBlock(pendingTxs, newGlobalVariables);
448
- const { publicGas, block, publicProcessorDuration, numTxs, numMsgs, blockBuildingTimer } = buildBlockRes;
449
- this.metrics.recordBuiltBlock(workTimer.ms(), publicGas.l2Gas);
450
- // TODO(@PhilWindle) We should probably periodically check for things like another
451
- // block being published before ours instead of just waiting on our block
452
- await this.publisher.validateBlockForSubmission(block.header);
453
- const blockStats = {
454
- eventName: 'l2-block-built',
455
- creator: this.publisher.getSenderAddress().toString(),
456
- duration: workTimer.ms(),
457
- publicProcessDuration: publicProcessorDuration,
458
- rollupCircuitsDuration: blockBuildingTimer.ms(),
459
- ...block.getStats()
460
- };
461
- const blockHash = await block.hash();
462
- const txHashes = block.body.txEffects.map((tx)=>tx.txHash);
463
- this.log.info(`Built block ${block.number} for slot ${slot} with ${numTxs} txs and ${numMsgs} messages. ${publicGas.l2Gas / workTimer.s()} mana/s`, {
464
- blockHash,
465
- globalVariables: block.header.globalVariables.toInspect(),
466
- txHashes,
467
- ...blockStats
468
- });
469
- this.log.debug('Collecting attestations');
470
- const stopCollectingAttestationsTimer = this.metrics.startCollectingAttestationsTimer();
471
- const attestations = await this.collectAttestations(block, txHashes);
472
- if (attestations !== undefined) {
473
- this.log.verbose(`Collected ${attestations.length} attestations`, {
474
- blockHash,
475
- blockNumber
476
- });
1028
+ proposer = await this.epochCache.getProposerAttesterAddressInSlot(targetSlot);
1029
+ } catch (e) {
1030
+ if (e instanceof NoCommitteeError) {
1031
+ if (this.lastSlotForNoCommitteeWarning !== targetSlot) {
1032
+ this.lastSlotForNoCommitteeWarning = targetSlot;
1033
+ this.log.warn(`Cannot propose at target slot ${targetSlot} since the committee does not exist on L1`);
1034
+ }
1035
+ return [
1036
+ false,
1037
+ undefined
1038
+ ];
477
1039
  }
478
- stopCollectingAttestationsTimer();
479
- return this.enqueuePublishL2Block(block, attestations, txHashes);
480
- } catch (err) {
481
- this.metrics.recordFailedBlock();
482
- throw err;
1040
+ this.log.error(`Error getting proposer for target slot ${targetSlot}`, e);
1041
+ return [
1042
+ false,
1043
+ undefined
1044
+ ];
483
1045
  }
484
- }
485
- async collectAttestations(block, txHashes) {
486
- // TODO(https://github.com/AztecProtocol/aztec-packages/issues/7962): inefficient to have a round trip in here - this should be cached
487
- const committee = await this.publisher.getCurrentEpochCommittee();
488
- if (committee.length === 0) {
489
- this.log.verbose(`Attesting committee is empty`);
490
- return undefined;
491
- } else {
492
- this.log.debug(`Attesting committee length is ${committee.length}`);
493
- }
494
- if (!this.validatorClient) {
495
- const msg = 'Missing validator client: Cannot collect attestations';
496
- this.log.error(msg);
497
- throw new Error(msg);
498
- }
499
- const numberOfRequiredAttestations = Math.floor(committee.length * 2 / 3) + 1;
500
- const slotNumber = block.header.globalVariables.slotNumber.toBigInt();
501
- this.setState(SequencerState.COLLECTING_ATTESTATIONS, slotNumber);
502
- this.log.debug('Creating block proposal for validators');
503
- const proposal = await this.validatorClient.createBlockProposal(block.header, block.archive.root, txHashes);
504
- if (!proposal) {
505
- const msg = `Failed to create block proposal`;
506
- throw new Error(msg);
507
- }
508
- this.log.debug('Broadcasting block proposal to validators');
509
- this.validatorClient.broadcastBlockProposal(proposal);
510
- const attestationTimeAllowed = this.enforceTimeTable ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_BLOCK) : this.aztecSlotDuration;
511
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
512
- const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline);
513
- // note: the smart contract requires that the signatures are provided in the order of the committee
514
- return orderAttestations(attestations, committee);
1046
+ // If proposer is undefined, then the committee is empty and anyone may propose
1047
+ if (proposer === undefined) {
1048
+ return [
1049
+ true,
1050
+ undefined
1051
+ ];
1052
+ }
1053
+ // In fisherman mode, just return the current proposer
1054
+ if (this.config.fishermanMode) {
1055
+ return [
1056
+ true,
1057
+ proposer
1058
+ ];
1059
+ }
1060
+ const validatorAddresses = this.validatorClient.getValidatorAddresses();
1061
+ const weAreProposer = validatorAddresses.some((addr)=>addr.equals(proposer));
1062
+ if (!weAreProposer) {
1063
+ this.log.debug(`Cannot propose at target slot ${targetSlot} since we are not a proposer`, {
1064
+ targetSlot,
1065
+ validatorAddresses,
1066
+ proposer
1067
+ });
1068
+ return [
1069
+ false,
1070
+ proposer
1071
+ ];
1072
+ }
1073
+ this.log.info(`We are the proposer for pipeline slot ${targetSlot}`, {
1074
+ targetSlot,
1075
+ proposer
1076
+ });
1077
+ return [
1078
+ true,
1079
+ proposer
1080
+ ];
515
1081
  }
516
1082
  /**
517
- * Publishes the L2Block to the rollup contract.
518
- * @param block - The L2Block to be published.
519
- */ async enqueuePublishL2Block(block, attestations, txHashes) {
520
- // Publishes new block to the network and awaits the tx to be mined
521
- this.setState(SequencerState.PUBLISHING_BLOCK, block.header.globalVariables.slotNumber.toBigInt());
522
- // Time out tx at the end of the slot
523
- const slot = block.header.globalVariables.slotNumber.toNumber();
524
- const txTimeoutAt = new Date((this.getSlotStartTimestamp(slot) + this.aztecSlotDuration) * 1000);
525
- const enqueued = await this.publisher.enqueueProposeL2Block(block, attestations, txHashes, {
526
- txTimeoutAt
1083
+ * Tries to vote on slashing actions and governance when the sync check fails but we're past the max time for initializing a proposal.
1084
+ * This allows the sequencer to participate in governance/slashing votes even when it cannot build blocks.
1085
+ */ async tryVoteWhenSyncFails(args) {
1086
+ const { slot, targetSlot } = args;
1087
+ // Prevent duplicate attempts in the same slot
1088
+ if (this.lastSlotForFallbackVote === slot) {
1089
+ this.log.trace(`Already attempted to vote in slot ${slot} (skipping)`);
1090
+ return;
1091
+ }
1092
+ // Check if we're past the max time for initializing a proposal
1093
+ const secondsIntoSlot = this.getSecondsIntoSlot(slot);
1094
+ const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_CHECKPOINT);
1095
+ // If we haven't exceeded the time limit for initializing a proposal, don't proceed with voting
1096
+ // We use INITIALIZING_PROPOSAL time limit because if we're past that, we can't build a block anyway
1097
+ if (maxAllowedTime === undefined || secondsIntoSlot <= maxAllowedTime) {
1098
+ this.log.trace(`Not attempting to vote since there is still time for block building`, {
1099
+ secondsIntoSlot,
1100
+ maxAllowedTime
1101
+ });
1102
+ return;
1103
+ }
1104
+ this.log.trace(`Sync for slot ${slot} failed, checking for voting opportunities`, {
1105
+ secondsIntoSlot,
1106
+ maxAllowedTime
1107
+ });
1108
+ // Check if we're a proposer or proposal is open
1109
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
1110
+ if (!canPropose) {
1111
+ this.log.trace(`Cannot vote in slot ${slot} since we are not a proposer`, {
1112
+ slot,
1113
+ proposer
1114
+ });
1115
+ return;
1116
+ }
1117
+ // Mark this slot as attempted
1118
+ this.lastSlotForFallbackVote = slot;
1119
+ // Get a publisher for voting
1120
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
1121
+ this.log.debug(`Attempting to vote despite sync failure at slot ${slot}`, {
1122
+ attestorAddress,
1123
+ slot
527
1124
  });
528
- if (!enqueued) {
529
- throw new Error(`Failed to enqueue publish of block ${block.number}`);
1125
+ // Enqueue governance and slashing votes (voter uses the target slot for L1 submission)
1126
+ const voter = new CheckpointVoter(targetSlot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
1127
+ const votesPromises = voter.enqueueVotes();
1128
+ const votes = await Promise.all(votesPromises);
1129
+ if (votes.every((p)=>!p)) {
1130
+ this.log.debug(`No votes to enqueue for slot ${slot}`);
1131
+ return;
530
1132
  }
1133
+ this.log.info(`Voting in slot ${slot} despite sync failure`, {
1134
+ slot
1135
+ });
1136
+ // Votes are EIP-712-signed for `targetSlot` (the pipelined slot in which the multicall is
1137
+ // expected to mine). Delay submission to the start of `targetSlot` so the tx mines in the
1138
+ // slot the votes were signed for. We fire-and-forget so we don't block the sequencer's
1139
+ // work loop while waiting for the target slot to start.
1140
+ void publisher.sendRequestsAt(targetSlot).catch((err)=>{
1141
+ this.log.error(`Failed to publish votes despite sync failure for slot ${slot}`, err, {
1142
+ slot
1143
+ });
1144
+ });
531
1145
  }
532
1146
  /**
533
- * Returns whether all dependencies have caught up.
534
- * We don't check against the previous block submitted since it may have been reorg'd out.
535
- * @returns Boolean indicating if our dependencies are synced to the latest block.
536
- */ async getChainTip() {
537
- const syncedBlocks = await Promise.all([
538
- this.worldState.status().then((s)=>{
539
- return {
540
- number: s.syncSummary.latestBlockNumber,
541
- hash: s.syncSummary.latestBlockHash
542
- };
543
- }),
544
- this.l2BlockSource.getL2Tips().then((t)=>t.latest),
545
- this.p2pClient.getStatus().then((p2p)=>p2p.syncedToL2Block),
546
- this.l1ToL2MessageSource.getBlockNumber()
547
- ]);
548
- const [worldState, l2BlockSource, p2p, l1ToL2MessageSource] = syncedBlocks;
549
- const result = // check that world state has caught up with archiver
550
- // note that the archiver reports undefined hash for the genesis block
551
- // because it doesn't have access to world state to compute it (facepalm)
552
- (l2BlockSource.hash === undefined || worldState.hash === l2BlockSource.hash) && // and p2p client and message source are at least at the same block
553
- // this should change to hashes once p2p client handles reorgs
554
- // and once we stop pretending that the l1tol2message source is not
555
- // just the archiver under a different name
556
- (!l2BlockSource.hash || p2p.hash === l2BlockSource.hash) && l1ToL2MessageSource === l2BlockSource.number;
557
- this.log.debug(`Sequencer sync check ${result ? 'succeeded' : 'failed'}`, {
558
- worldStateNumber: worldState.number,
559
- worldStateHash: worldState.hash,
560
- l2BlockSourceNumber: l2BlockSource.number,
561
- l2BlockSourceHash: l2BlockSource.hash,
562
- p2pNumber: p2p.number,
563
- p2pHash: p2p.hash,
564
- l1ToL2MessageSourceNumber: l1ToL2MessageSource
1147
+ * Tries to vote on slashing actions and governance proposals when escape hatch is open.
1148
+ * This allows the sequencer to participate in voting without performing checkpoint proposal work.
1149
+ */ async tryVoteWhenEscapeHatchOpen(args) {
1150
+ const { slot, targetSlot, proposer } = args;
1151
+ // Prevent duplicate attempts in the same slot
1152
+ if (this.lastSlotForFallbackVote === slot) {
1153
+ this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
1154
+ return;
1155
+ }
1156
+ // Mark this slot as attempted
1157
+ this.lastSlotForFallbackVote = slot;
1158
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
1159
+ this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, {
1160
+ slot,
1161
+ targetSlot,
1162
+ attestorAddress
565
1163
  });
566
- if (!result) {
567
- return undefined;
1164
+ // Under proposer pipelining, the multicall is expected to mine in `targetSlot` (slot + 1).
1165
+ // Governance and slashing votes are EIP-712-signed against the slot they will mine in, and the
1166
+ // L1 contract checks `msg.sender == getCurrentProposer()` using the mining slot. So we must
1167
+ // sign for `targetSlot` and delay submission to the start of `targetSlot`.
1168
+ const voter = new CheckpointVoter(targetSlot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
1169
+ const votesPromises = voter.enqueueVotes();
1170
+ const votes = await Promise.all(votesPromises);
1171
+ if (votes.every((p)=>!p)) {
1172
+ this.log.debug(`No votes to enqueue for slot ${slot} (escape hatch open)`);
1173
+ return;
568
1174
  }
569
- if (worldState.number >= INITIAL_L2_BLOCK_NUM) {
570
- const block = await this.l2BlockSource.getBlock(worldState.number);
571
- if (!block) {
572
- // this shouldn't really happen because a moment ago we checked that all components were in synch
573
- return undefined;
1175
+ this.log.info(`Voting in slot ${slot} (escape hatch open)`, {
1176
+ slot,
1177
+ targetSlot
1178
+ });
1179
+ // Votes are EIP-712-signed for `targetSlot`. Delay submission to the start of `targetSlot` so
1180
+ // the multicall mines in the slot the votes were signed for; otherwise the L1 contract reads
1181
+ // `signaler = getCurrentProposer()` against the wrong slot and signature verification fails
1182
+ // silently inside Multicall3. Fire-and-forget so we don't block the sequencer's work loop while
1183
+ // waiting for the target slot to start, mirroring tryVoteWhenSyncFails.
1184
+ void publisher.sendRequestsAt(targetSlot).catch((err)=>{
1185
+ this.log.error(`Failed to publish escape-hatch votes for slot ${slot}`, err, {
1186
+ slot,
1187
+ targetSlot
1188
+ });
1189
+ });
1190
+ }
1191
+ /**
1192
+ * Considers invalidating a block if the pending chain is invalid. Depends on how long the invalid block
1193
+ * has been there without being invalidated and whether the sequencer is in the committee or not. We always
1194
+ * have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
1195
+ * and if they fail, any sequencer will try as well.
1196
+ */ async considerInvalidatingCheckpoint(syncedTo, currentSlot) {
1197
+ const { pendingChainValidationStatus, syncedL2Slot } = syncedTo;
1198
+ if (pendingChainValidationStatus.valid) {
1199
+ return;
1200
+ }
1201
+ const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
1202
+ const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
1203
+ const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
1204
+ const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
1205
+ const { secondsBeforeInvalidatingBlockAsCommitteeMember, secondsBeforeInvalidatingBlockAsNonCommitteeMember } = this.config;
1206
+ const logData = {
1207
+ invalidL1Timestamp: invalidCheckpointTimestamp,
1208
+ syncedL2Slot,
1209
+ invalidCheckpoint: pendingChainValidationStatus.checkpoint,
1210
+ secondsBeforeInvalidatingBlockAsCommitteeMember,
1211
+ secondsBeforeInvalidatingBlockAsNonCommitteeMember,
1212
+ ourValidatorAddresses,
1213
+ currentSlot
1214
+ };
1215
+ const inCurrentCommittee = ()=>this.epochCache.getCommittee(currentSlot).then((c)=>c?.committee?.some((member)=>ourValidatorAddresses.some((addr)=>addr.equals(member))));
1216
+ const invalidateAsCommitteeMember = secondsBeforeInvalidatingBlockAsCommitteeMember !== undefined && secondsBeforeInvalidatingBlockAsCommitteeMember > 0 && timeSinceChainInvalid > secondsBeforeInvalidatingBlockAsCommitteeMember && await inCurrentCommittee();
1217
+ const invalidateAsNonCommitteeMember = secondsBeforeInvalidatingBlockAsNonCommitteeMember !== undefined && secondsBeforeInvalidatingBlockAsNonCommitteeMember > 0 && timeSinceChainInvalid > secondsBeforeInvalidatingBlockAsNonCommitteeMember;
1218
+ if (!invalidateAsCommitteeMember && !invalidateAsNonCommitteeMember) {
1219
+ this.log.debug(`Not invalidating pending chain`, logData);
1220
+ return;
1221
+ }
1222
+ let validatorToUse;
1223
+ if (invalidateAsCommitteeMember) {
1224
+ // When invalidating as a committee member, use first validator that's actually in the committee
1225
+ const { committee } = await this.epochCache.getCommittee(currentSlot);
1226
+ if (committee) {
1227
+ const committeeSet = new Set(committee.map((addr)=>addr.toString()));
1228
+ validatorToUse = ourValidatorAddresses.find((addr)=>committeeSet.has(addr.toString())) ?? ourValidatorAddresses[0];
1229
+ } else {
1230
+ validatorToUse = ourValidatorAddresses[0];
574
1231
  }
575
- return {
576
- blockNumber: block.number,
577
- archive: block.archive.root
578
- };
579
1232
  } else {
580
- const archive = new Fr((await this.worldState.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
581
- return {
582
- blockNumber: INITIAL_L2_BLOCK_NUM - 1,
583
- archive
584
- };
1233
+ // When invalidating as a non-committee member, use the first validator
1234
+ validatorToUse = ourValidatorAddresses[0];
1235
+ }
1236
+ const { publisher } = await this.publisherFactory.create(validatorToUse);
1237
+ const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(pendingChainValidationStatus);
1238
+ if (!invalidateCheckpoint) {
1239
+ this.log.warn(`Failed to simulate invalidate checkpoint`, logData);
1240
+ return;
1241
+ }
1242
+ this.log.info(invalidateAsCommitteeMember ? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member` : `Invalidating checkpoint ${invalidCheckpointNumber} as non-committee member`, logData);
1243
+ publisher.enqueueInvalidateCheckpoint(invalidateCheckpoint);
1244
+ if (!this.config.fishermanMode) {
1245
+ await publisher.sendRequests();
1246
+ } else {
1247
+ this.log.info('Invalidating checkpoint in fisherman mode, clearing pending requests');
1248
+ publisher.clearPendingRequests();
585
1249
  }
586
1250
  }
587
- getSlotStartTimestamp(slotNumber) {
588
- return Number(this.l1Constants.l1GenesisTime) + Number(slotNumber) * this.l1Constants.slotDuration;
1251
+ logStrategyComparison(epoch, publisher) {
1252
+ const feeAnalyzer = publisher.getL1FeeAnalyzer();
1253
+ if (!feeAnalyzer) {
1254
+ return;
1255
+ }
1256
+ const comparison = feeAnalyzer.getStrategyComparison();
1257
+ if (comparison.length === 0) {
1258
+ this.log.debug(`No strategy data available yet for epoch ${epoch}`);
1259
+ return;
1260
+ }
1261
+ this.log.info(`L1 Fee Strategy Performance Report - End of Epoch ${epoch}`, {
1262
+ epoch: Number(epoch),
1263
+ totalAnalyses: comparison[0]?.totalAnalyses,
1264
+ strategies: comparison.map((s)=>({
1265
+ id: s.strategyId,
1266
+ name: s.strategyName,
1267
+ inclusionRate: `${(s.inclusionRate * 100).toFixed(1)}%`,
1268
+ inclusionCount: `${s.inclusionCount}/${s.totalAnalyses}`,
1269
+ avgCostEth: s.avgEstimatedCostEth.toFixed(6),
1270
+ totalCostEth: s.totalEstimatedCostEth.toFixed(6),
1271
+ avgOverpaymentEth: s.avgOverpaymentEth.toFixed(6),
1272
+ totalOverpaymentEth: s.totalOverpaymentEth.toFixed(6),
1273
+ avgPriorityFeeDeltaGwei: s.avgPriorityFeeDeltaGwei.toFixed(2)
1274
+ }))
1275
+ });
1276
+ }
1277
+ getSlotStartBuildTimestamp(slotNumber) {
1278
+ return getSlotStartBuildTimestamp(slotNumber, this.l1Constants);
589
1279
  }
590
1280
  getSecondsIntoSlot(slotNumber) {
591
- const slotStartTimestamp = this.getSlotStartTimestamp(slotNumber);
1281
+ const slotStartTimestamp = this.getSlotStartBuildTimestamp(slotNumber);
592
1282
  return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
593
1283
  }
594
1284
  get aztecSlotDuration() {
595
1285
  return this.l1Constants.slotDuration;
596
1286
  }
597
- get coinbase() {
598
- return this._coinbase;
1287
+ get maxL2BlockGas() {
1288
+ return this.config.maxL2BlockGas;
1289
+ }
1290
+ getSlasherClient() {
1291
+ return this.slasherClient;
1292
+ }
1293
+ get tracer() {
1294
+ return this.metrics.tracer;
1295
+ }
1296
+ getValidatorAddresses() {
1297
+ return this.validatorClient?.getValidatorAddresses();
1298
+ }
1299
+ /** Updates the publisher factory's node keystore adapter after a keystore reload. */ updatePublisherNodeKeyStore(adapter) {
1300
+ this.publisherFactory.updateNodeKeyStore(adapter);
1301
+ }
1302
+ getConfig() {
1303
+ return this.config;
599
1304
  }
600
- get feeRecipient() {
601
- return this._feeRecipient;
1305
+ get l1PublishingTime() {
1306
+ return this.config.l1PublishingTime ?? this.l1Constants.ethereumSlotDuration;
602
1307
  }
603
1308
  }
604
- _ts_decorate([
605
- trackSpan('Sequencer.work')
606
- ], Sequencer.prototype, "work", null);
607
- _ts_decorate([
608
- trackSpan('Sequencer.buildBlockAndEnqueuePublish', (_validTxs, proposalHeader)=>({
609
- [Attributes.BLOCK_NUMBER]: proposalHeader.globalVariables.blockNumber.toNumber()
610
- }))
611
- ], Sequencer.prototype, "buildBlockAndEnqueuePublish", null);
612
- _ts_decorate([
613
- trackSpan('Sequencer.collectAttestations', (block, txHashes)=>({
614
- [Attributes.BLOCK_NUMBER]: block.number,
615
- [Attributes.BLOCK_ARCHIVE]: block.archive.toString(),
616
- [Attributes.BLOCK_TXS_COUNT]: txHashes.length
617
- }))
618
- ], Sequencer.prototype, "collectAttestations", null);
619
- _ts_decorate([
620
- trackSpan('Sequencer.enqueuePublishL2Block', (block)=>({
621
- [Attributes.BLOCK_NUMBER]: block.number
622
- }))
623
- ], Sequencer.prototype, "enqueuePublishL2Block", null);