@aztec/sequencer-client 0.0.1-commit.5daedc8 → 0.0.1-commit.6201a7b05

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 (136) hide show
  1. package/dest/client/sequencer-client.d.ts +26 -16
  2. package/dest/client/sequencer-client.d.ts.map +1 -1
  3. package/dest/client/sequencer-client.js +76 -36
  4. package/dest/config.d.ts +35 -9
  5. package/dest/config.d.ts.map +1 -1
  6. package/dest/config.js +113 -50
  7. package/dest/global_variable_builder/fee_predictor.d.ts +37 -0
  8. package/dest/global_variable_builder/fee_predictor.d.ts.map +1 -0
  9. package/dest/global_variable_builder/fee_predictor.js +128 -0
  10. package/dest/global_variable_builder/fee_provider.d.ts +21 -0
  11. package/dest/global_variable_builder/fee_provider.d.ts.map +1 -0
  12. package/dest/global_variable_builder/fee_provider.js +58 -0
  13. package/dest/global_variable_builder/global_builder.d.ts +25 -17
  14. package/dest/global_variable_builder/global_builder.d.ts.map +1 -1
  15. package/dest/global_variable_builder/global_builder.js +44 -68
  16. package/dest/global_variable_builder/index.d.ts +4 -2
  17. package/dest/global_variable_builder/index.d.ts.map +1 -1
  18. package/dest/global_variable_builder/index.js +2 -0
  19. package/dest/index.d.ts +2 -3
  20. package/dest/index.d.ts.map +1 -1
  21. package/dest/index.js +1 -2
  22. package/dest/publisher/config.d.ts +53 -20
  23. package/dest/publisher/config.d.ts.map +1 -1
  24. package/dest/publisher/config.js +124 -39
  25. package/dest/publisher/index.d.ts +2 -1
  26. package/dest/publisher/index.d.ts.map +1 -1
  27. package/dest/publisher/l1_tx_failed_store/factory.d.ts +11 -0
  28. package/dest/publisher/l1_tx_failed_store/factory.d.ts.map +1 -0
  29. package/dest/publisher/l1_tx_failed_store/factory.js +22 -0
  30. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts +58 -0
  31. package/dest/publisher/l1_tx_failed_store/failed_tx_store.d.ts.map +1 -0
  32. package/dest/publisher/l1_tx_failed_store/failed_tx_store.js +1 -0
  33. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +15 -0
  34. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -0
  35. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +34 -0
  36. package/dest/publisher/l1_tx_failed_store/index.d.ts +4 -0
  37. package/dest/publisher/l1_tx_failed_store/index.d.ts.map +1 -0
  38. package/dest/publisher/l1_tx_failed_store/index.js +2 -0
  39. package/dest/publisher/sequencer-publisher-factory.d.ts +15 -8
  40. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  41. package/dest/publisher/sequencer-publisher-factory.js +28 -4
  42. package/dest/publisher/sequencer-publisher-metrics.d.ts +3 -3
  43. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  44. package/dest/publisher/sequencer-publisher-metrics.js +23 -86
  45. package/dest/publisher/sequencer-publisher.d.ts +114 -80
  46. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  47. package/dest/publisher/sequencer-publisher.js +1010 -244
  48. package/dest/sequencer/chain_state_overrides.d.ts +25 -0
  49. package/dest/sequencer/chain_state_overrides.d.ts.map +1 -0
  50. package/dest/sequencer/chain_state_overrides.js +39 -0
  51. package/dest/sequencer/checkpoint_proposal_job.d.ts +138 -0
  52. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -0
  53. package/dest/sequencer/checkpoint_proposal_job.js +1665 -0
  54. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts +34 -0
  55. package/dest/sequencer/checkpoint_proposal_job_metrics.d.ts.map +1 -0
  56. package/dest/sequencer/checkpoint_proposal_job_metrics.js +72 -0
  57. package/dest/sequencer/checkpoint_voter.d.ts +34 -0
  58. package/dest/sequencer/checkpoint_voter.d.ts.map +1 -0
  59. package/dest/sequencer/checkpoint_voter.js +106 -0
  60. package/dest/sequencer/config.d.ts +3 -2
  61. package/dest/sequencer/config.d.ts.map +1 -1
  62. package/dest/sequencer/events.d.ts +52 -0
  63. package/dest/sequencer/events.d.ts.map +1 -0
  64. package/dest/sequencer/events.js +1 -0
  65. package/dest/sequencer/index.d.ts +4 -2
  66. package/dest/sequencer/index.d.ts.map +1 -1
  67. package/dest/sequencer/index.js +3 -1
  68. package/dest/sequencer/metrics.d.ts +42 -7
  69. package/dest/sequencer/metrics.d.ts.map +1 -1
  70. package/dest/sequencer/metrics.js +241 -72
  71. package/dest/sequencer/sequencer.d.ts +146 -135
  72. package/dest/sequencer/sequencer.d.ts.map +1 -1
  73. package/dest/sequencer/sequencer.js +841 -661
  74. package/dest/sequencer/timetable.d.ts +67 -16
  75. package/dest/sequencer/timetable.d.ts.map +1 -1
  76. package/dest/sequencer/timetable.js +158 -64
  77. package/dest/sequencer/types.d.ts +3 -0
  78. package/dest/sequencer/types.d.ts.map +1 -0
  79. package/dest/sequencer/types.js +1 -0
  80. package/dest/sequencer/utils.d.ts +14 -8
  81. package/dest/sequencer/utils.d.ts.map +1 -1
  82. package/dest/sequencer/utils.js +7 -4
  83. package/dest/test/index.d.ts +6 -7
  84. package/dest/test/index.d.ts.map +1 -1
  85. package/dest/test/mock_checkpoint_builder.d.ts +95 -0
  86. package/dest/test/mock_checkpoint_builder.d.ts.map +1 -0
  87. package/dest/test/mock_checkpoint_builder.js +231 -0
  88. package/dest/test/utils.d.ts +53 -0
  89. package/dest/test/utils.d.ts.map +1 -0
  90. package/dest/test/utils.js +105 -0
  91. package/package.json +31 -30
  92. package/src/client/sequencer-client.ts +102 -62
  93. package/src/config.ts +132 -59
  94. package/src/global_variable_builder/README.md +44 -0
  95. package/src/global_variable_builder/fee_predictor.ts +172 -0
  96. package/src/global_variable_builder/fee_provider.ts +75 -0
  97. package/src/global_variable_builder/global_builder.ts +64 -96
  98. package/src/global_variable_builder/index.ts +3 -1
  99. package/src/index.ts +1 -7
  100. package/src/publisher/config.ts +166 -51
  101. package/src/publisher/index.ts +3 -0
  102. package/src/publisher/l1_tx_failed_store/factory.ts +32 -0
  103. package/src/publisher/l1_tx_failed_store/failed_tx_store.ts +57 -0
  104. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +46 -0
  105. package/src/publisher/l1_tx_failed_store/index.ts +3 -0
  106. package/src/publisher/sequencer-publisher-factory.ts +43 -13
  107. package/src/publisher/sequencer-publisher-metrics.ts +19 -71
  108. package/src/publisher/sequencer-publisher.ts +763 -325
  109. package/src/sequencer/README.md +600 -0
  110. package/src/sequencer/chain_state_overrides.ts +87 -0
  111. package/src/sequencer/checkpoint_proposal_job.ts +1498 -0
  112. package/src/sequencer/checkpoint_proposal_job_metrics.ts +128 -0
  113. package/src/sequencer/checkpoint_voter.ts +119 -0
  114. package/src/sequencer/config.ts +2 -1
  115. package/src/sequencer/events.ts +32 -0
  116. package/src/sequencer/index.ts +3 -1
  117. package/src/sequencer/metrics.ts +302 -83
  118. package/src/sequencer/sequencer.ts +641 -863
  119. package/src/sequencer/timetable.ts +188 -81
  120. package/src/sequencer/types.ts +6 -0
  121. package/src/sequencer/utils.ts +18 -9
  122. package/src/test/index.ts +5 -6
  123. package/src/test/mock_checkpoint_builder.ts +323 -0
  124. package/src/test/utils.ts +185 -0
  125. package/dest/sequencer/block_builder.d.ts +0 -27
  126. package/dest/sequencer/block_builder.d.ts.map +0 -1
  127. package/dest/sequencer/block_builder.js +0 -134
  128. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  129. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  130. package/dest/tx_validator/nullifier_cache.js +0 -24
  131. package/dest/tx_validator/tx_validator_factory.d.ts +0 -17
  132. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  133. package/dest/tx_validator/tx_validator_factory.js +0 -53
  134. package/src/sequencer/block_builder.ts +0 -222
  135. package/src/tx_validator/nullifier_cache.ts +0 -30
  136. package/src/tx_validator/tx_validator_factory.ts +0 -132
@@ -1,45 +1,412 @@
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 { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB, INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
8
- import { FormattedViemError, NoCommitteeError } from '@aztec/ethereum';
9
- import { omit, pick } from '@aztec/foundation/collection';
10
- import { randomInt } from '@aztec/foundation/crypto';
373
+ var _dec, _dec1, _dec2, _dec3, _initProto;
374
+ import { getKzg } from '@aztec/blob-lib';
375
+ import { INITIAL_L2_BLOCK_NUM } from '@aztec/constants';
376
+ import { NoCommitteeError, SimulationOverridesBuilder } from '@aztec/ethereum/contracts';
377
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
378
+ import { merge, omit, pick } from '@aztec/foundation/collection';
379
+ import { Fr } from '@aztec/foundation/curves/bn254';
11
380
  import { EthAddress } from '@aztec/foundation/eth-address';
12
- import { Signature } from '@aztec/foundation/eth-signature';
13
- import { Fr } from '@aztec/foundation/fields';
14
381
  import { createLogger } from '@aztec/foundation/log';
15
382
  import { RunningPromise } from '@aztec/foundation/running-promise';
16
- import { Timer } from '@aztec/foundation/timer';
17
- import { unfreeze } from '@aztec/foundation/types';
18
- import { CommitteeAttestationsAndSigners, MaliciousCommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
19
- import { getSlotAtTimestamp, getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
20
- import { Gas } from '@aztec/stdlib/gas';
383
+ import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
21
384
  import { SequencerConfigSchema } from '@aztec/stdlib/interfaces/server';
22
- import { orderAttestations } from '@aztec/stdlib/p2p';
23
- import { CheckpointHeader } from '@aztec/stdlib/rollup';
24
385
  import { pickFromSchema } from '@aztec/stdlib/schemas';
25
386
  import { MerkleTreeId } from '@aztec/stdlib/trees';
26
- import { ContentCommitment } from '@aztec/stdlib/tx';
27
- import { AttestationTimeoutError } from '@aztec/stdlib/validators';
28
387
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
29
388
  import EventEmitter from 'node:events';
389
+ import { DefaultSequencerConfig } from '../config.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';
30
393
  import { SequencerInterruptedError, SequencerTooSlowError } from './errors.js';
31
394
  import { SequencerMetrics } from './metrics.js';
32
395
  import { SequencerTimetable } from './timetable.js';
33
396
  import { SequencerState } from './utils.js';
34
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
+ }));
35
403
  /**
36
404
  * Sequencer client
37
- * - Wins a period of time to become the sequencer (depending on finalized protocol).
38
- * - Chooses a set of txs from the tx pool to be in the rollup.
39
- * - Simulate the rollup of txs.
40
- * - Adds proof requests to the request pool (not for this milestone).
41
- * - Receives results to those proofs from the network (repeats as necessary) (not for this milestone).
42
- * - Publishes L1 tx(s) to the rollup contract via RollupPublisher.
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
43
410
  */ export class Sequencer extends EventEmitter {
44
411
  publisherFactory;
45
412
  validatorClient;
@@ -49,150 +416,187 @@ export { SequencerState };
49
416
  slasherClient;
50
417
  l2BlockSource;
51
418
  l1ToL2MessageSource;
52
- blockBuilder;
419
+ checkpointsBuilder;
53
420
  l1Constants;
54
421
  dateProvider;
55
422
  epochCache;
56
423
  rollupContract;
57
- config;
58
424
  telemetry;
59
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
+ }
60
450
  runningPromise;
61
- pollingIntervalMs;
62
- maxTxsPerBlock;
63
- minTxsPerBlock;
64
- maxL1TxInclusionTimeIntoSlot;
65
451
  state;
66
- maxBlockSizeInBytes;
67
- maxBlockGas;
452
+ stateSlotNumber;
453
+ stateEnteredAtMs;
68
454
  metrics;
69
- lastBlockPublished;
70
- governanceProposerPayload;
71
- /** The last slot for which we attempted to vote when sync failed, to prevent duplicate attempts. */ lastSlotForVoteWhenSyncFailed;
72
- /** The last slot for which we built a validation block in fisherman mode, to prevent duplicate attempts. */ lastSlotForValidationBlock;
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;
73
463
  /** The maximum number of seconds that the sequencer can be into a slot to transition to a particular state. */ timetable;
74
- enforceTimeTable;
75
- // This shouldn't be here as this gets re-created each time we build/propose a block.
76
- // But we have a number of tests that abuse/rely on this class having a permanent publisher.
77
- // As long as those tests only configure a single publisher they will continue to work.
78
- // This will get re-assigned every time the sequencer goes to build a new block to a publisher that is valid
79
- // for the block proposer.
80
- publisher;
81
- constructor(publisherFactory, validatorClient, globalsBuilder, p2pClient, worldState, slasherClient, l2BlockSource, l1ToL2MessageSource, blockBuilder, l1Constants, dateProvider, epochCache, rollupContract, config, telemetry = getTelemetryClient(), log = createLogger('sequencer')){
82
- 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.blockBuilder = blockBuilder, this.l1Constants = l1Constants, this.dateProvider = dateProvider, this.epochCache = epochCache, this.rollupContract = rollupContract, this.config = config, this.telemetry = telemetry, this.log = log, this.pollingIntervalMs = 1000, this.maxTxsPerBlock = 32, this.minTxsPerBlock = 1, this.maxL1TxInclusionTimeIntoSlot = 0, this.state = SequencerState.STOPPED, this.maxBlockSizeInBytes = 1024 * 1024, this.maxBlockGas = new Gas(100e9, 100e9), this.enforceTimeTable = false;
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');
83
469
  // Add [FISHERMAN] prefix to logger if in fisherman mode
84
- if (this.config.fishermanMode) {
470
+ if (config.fishermanMode) {
85
471
  this.log = log.createChild('[FISHERMAN]');
86
472
  }
473
+ this.signatureContext = {
474
+ chainId: config.l1ChainId,
475
+ rollupAddress: config.l1Contracts.rollupAddress
476
+ };
87
477
  this.metrics = new SequencerMetrics(telemetry, this.rollupContract, 'Sequencer');
88
- // Initialize config
89
- this.updateConfig(this.config);
90
- }
91
- get tracer() {
92
- return this.metrics.tracer;
93
- }
94
- getValidatorAddresses() {
95
- return this.validatorClient?.getValidatorAddresses();
96
- }
97
- getConfig() {
98
- return this.config;
99
- }
100
- /**
101
- * Updates sequencer config by the defined values in the config on input.
102
- * @param config - New parameters.
103
- */ updateConfig(config) {
104
- this.log.info(`Sequencer config set`, omit(pickFromSchema(config, SequencerConfigSchema), 'txPublicSetupAllowList'));
105
- if (config.transactionPollingIntervalMS !== undefined) {
106
- this.pollingIntervalMs = config.transactionPollingIntervalMS;
107
- }
108
- if (config.maxTxsPerBlock !== undefined) {
109
- this.maxTxsPerBlock = config.maxTxsPerBlock;
110
- }
111
- if (config.minTxsPerBlock !== undefined) {
112
- this.minTxsPerBlock = config.minTxsPerBlock;
113
- }
114
- if (config.maxDABlockGas !== undefined) {
115
- this.maxBlockGas = new Gas(config.maxDABlockGas, this.maxBlockGas.l2Gas);
116
- }
117
- if (config.maxL2BlockGas !== undefined) {
118
- this.maxBlockGas = new Gas(this.maxBlockGas.daGas, config.maxL2BlockGas);
119
- }
120
- if (config.maxBlockSizeInBytes !== undefined) {
121
- this.maxBlockSizeInBytes = config.maxBlockSizeInBytes;
122
- }
123
- if (config.governanceProposerPayload) {
124
- this.governanceProposerPayload = config.governanceProposerPayload;
125
- }
126
- if (config.maxL1TxInclusionTimeIntoSlot !== undefined) {
127
- this.maxL1TxInclusionTimeIntoSlot = config.maxL1TxInclusionTimeIntoSlot;
128
- }
129
- if (config.enforceTimeTable !== undefined) {
130
- this.enforceTimeTable = config.enforceTimeTable;
131
- }
132
- this.setTimeTable();
133
- // TODO: Just read everything from the config object as needed instead of copying everything into local vars.
134
- // Update all values on this.config that are populated in the config object.
135
- Object.assign(this.config, config);
478
+ this.checkpointProposalJobMetrics = new CheckpointProposalJobMetrics(telemetry);
479
+ this.updateConfig(config);
136
480
  }
137
- setTimeTable() {
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;
138
486
  this.timetable = new SequencerTimetable({
139
487
  ethereumSlotDuration: this.l1Constants.ethereumSlotDuration,
140
488
  aztecSlotDuration: this.aztecSlotDuration,
141
- maxL1TxInclusionTimeIntoSlot: this.maxL1TxInclusionTimeIntoSlot,
142
- attestationPropagationTime: this.config.attestationPropagationTime,
143
- enforce: this.enforceTimeTable
489
+ l1PublishingTime: this.l1PublishingTime,
490
+ p2pPropagationTime,
491
+ blockDurationMs: this.config.blockDurationMs,
492
+ enforce: this.config.enforceTimeTable,
493
+ pipelining: this.epochCache.isProposerPipeliningEnabled()
144
494
  }, this.metrics, this.log);
145
495
  }
146
- async init() {
147
- this.publisher = (await this.publisherFactory.create(undefined)).publisher;
496
+ /** Initializes the sequencer (precomputes tables). Takes about 3s. */ init() {
497
+ getKzg();
148
498
  }
149
- /**
150
- * Starts the sequencer and moves to IDLE state.
151
- */ start() {
152
- this.runningPromise = new RunningPromise(this.safeWork.bind(this), this.log, this.pollingIntervalMs);
499
+ /** Starts the sequencer and moves to IDLE state. */ start() {
500
+ this.runningPromise = new RunningPromise(this.safeWork.bind(this), this.log, this.config.sequencerPollingIntervalMS);
153
501
  this.setState(SequencerState.IDLE, undefined, {
154
502
  force: true
155
503
  });
156
504
  this.runningPromise.start();
157
505
  this.log.info('Started sequencer');
158
506
  }
159
- /**
160
- * Stops the sequencer from processing txs and moves to STOPPED state.
161
- */ async stop() {
507
+ /** Triggers an immediate run of the sequencer, bypassing the polling interval. */ trigger() {
508
+ return this.runningPromise?.trigger();
509
+ }
510
+ /** Stops the sequencer from building blocks and moves to STOPPED state. */ async stop() {
162
511
  this.log.info(`Stopping sequencer`);
163
512
  this.setState(SequencerState.STOPPING, undefined, {
164
513
  force: true
165
514
  });
166
- this.publisher?.interrupt();
515
+ await this.publisherFactory.stopAll();
167
516
  await this.runningPromise?.stop();
517
+ await this.lastCheckpointProposalJob?.awaitPendingSubmission();
168
518
  this.setState(SequencerState.STOPPED, undefined, {
169
519
  force: true
170
520
  });
171
521
  this.log.info('Stopped sequencer');
172
522
  }
173
- /**
174
- * Returns the current state of the sequencer.
175
- * @returns An object with a state entry with one of SequencerState.
176
- */ status() {
523
+ /** Main sequencer loop with a try/catch */ async safeWork() {
524
+ try {
525
+ await this.work();
526
+ } catch (err) {
527
+ this.emit('checkpoint-error', {
528
+ error: err
529
+ });
530
+ if (err instanceof SequencerTooSlowError) {
531
+ // Log as warn only if we had to abort halfway through the block proposal
532
+ const logLvl = [
533
+ SequencerState.INITIALIZING_CHECKPOINT,
534
+ SequencerState.PROPOSER_CHECK
535
+ ].includes(err.proposedState) ? 'debug' : 'warn';
536
+ this.log[logLvl](err.message, {
537
+ now: this.dateProvider.nowInSeconds()
538
+ });
539
+ } else {
540
+ // Re-throw other errors
541
+ throw err;
542
+ }
543
+ } finally{
544
+ this.setState(SequencerState.IDLE, undefined);
545
+ }
546
+ }
547
+ /** Returns the current state of the sequencer. */ status() {
177
548
  return {
178
549
  state: this.state
179
550
  };
180
551
  }
181
552
  /**
182
- * @notice Performs most of the sequencer duties:
183
- * - Checks if we are up to date
184
- * - If we are and we are the sequencer, collect txs and build a block
185
- * - Collect attestations for the block
186
- * - Submit block
187
- * - If our block for some reason is not included, revert the state
553
+ * Main sequencer loop:
554
+ * - Checks if we are up to date
555
+ * - If we are and we are the sequencer, collect txs and build blocks
556
+ * - Build multiple blocks per slot when configured
557
+ * - Collect attestations for the final block
558
+ * - Submit checkpoint
188
559
  */ async work() {
189
560
  this.setState(SequencerState.SYNCHRONIZING, undefined);
190
- const { slot, ts, now } = this.epochCache.getEpochAndSlotInNextL1Slot();
191
- // Check we have not already published a block for this slot (cheapest check)
192
- if (this.lastBlockPublished && this.lastBlockPublished.header.getSlot() >= slot) {
193
- this.log.debug(`Cannot propose block at next L2 slot ${slot} since that slot was taken by our own block ${this.lastBlockPublished.number}`);
561
+ const { slot, ts, nowSeconds, epoch } = this.epochCache.getEpochAndSlotInNextL1Slot();
562
+ const { slot: targetSlot, epoch: targetEpoch } = this.epochCache.getTargetEpochAndSlotInNextL1Slot();
563
+ // Check if we are synced and it's our slot, grab a publisher, check previous block invalidation, etc
564
+ const checkpointProposalJob = await this.prepareCheckpointProposal(slot, targetSlot, epoch, targetEpoch, ts, nowSeconds);
565
+ if (!checkpointProposalJob) {
194
566
  return;
195
567
  }
568
+ // Track the job so we can await its pending L1 submission during shutdown
569
+ this.lastCheckpointProposalJob = checkpointProposalJob;
570
+ // Execute the checkpoint proposal job
571
+ const checkpoint = await checkpointProposalJob.execute();
572
+ // Update last checkpoint proposed (currently unused)
573
+ if (checkpoint) {
574
+ this.lastCheckpointProposed = checkpoint;
575
+ }
576
+ // Log fee strategy comparison if on fisherman (uses target epoch since we mirror the proposer's perspective)
577
+ if (this.config.fishermanMode && (this.lastEpochForStrategyComparison === undefined || targetEpoch > this.lastEpochForStrategyComparison)) {
578
+ this.logStrategyComparison(targetEpoch, checkpointProposalJob.getPublisher());
579
+ this.lastEpochForStrategyComparison = targetEpoch;
580
+ }
581
+ return checkpoint;
582
+ }
583
+ /**
584
+ * Prepares the checkpoint proposal by performing all necessary checks and setup.
585
+ * This is the initial step in the main loop.
586
+ * @returns CheckpointProposalJob if successful, undefined if we are not yet synced or are not the proposer.
587
+ */ async prepareCheckpointProposal(slot, targetSlot, epoch, targetEpoch, ts, nowSeconds) {
588
+ // Check we have not already processed this target slot (cheapest check)
589
+ // We only check this if enforce timetable is set, since we want to keep processing the same slot if we are not
590
+ // running against actual time (eg when we use sandbox-style automining)
591
+ if (this.lastSlotForCheckpointProposalJob && this.lastSlotForCheckpointProposalJob >= targetSlot && this.config.enforceTimeTable) {
592
+ this.log.trace(`Target slot ${targetSlot} has already been processed`);
593
+ return undefined;
594
+ }
595
+ // But if we have already proposed for this slot, then we definitely have to skip it, automining or not
596
+ if (this.lastCheckpointProposed && this.lastCheckpointProposed.header.slotNumber >= targetSlot) {
597
+ this.log.trace(`Slot ${targetSlot} has already been published as checkpoint ${this.lastCheckpointProposed.number}`);
598
+ return undefined;
599
+ }
196
600
  // Check all components are synced to latest as seen by the archiver (queries all subsystems)
197
601
  const syncedTo = await this.checkSync({
198
602
  ts,
@@ -201,238 +605,165 @@ export { SequencerState };
201
605
  if (!syncedTo) {
202
606
  await this.tryVoteWhenSyncFails({
203
607
  slot,
608
+ targetSlot,
204
609
  ts
205
610
  });
206
- return;
611
+ return undefined;
207
612
  }
208
- const chainTipArchive = syncedTo.archive;
209
- const newBlockNumber = syncedTo.blockNumber + 1;
210
- const syncLogData = {
211
- now,
212
- syncedToL1Ts: syncedTo.l1Timestamp,
213
- syncedToL2Slot: getSlotAtTimestamp(syncedTo.l1Timestamp, this.l1Constants),
214
- nextL2Slot: slot,
215
- nextL2SlotTs: ts,
216
- l1SlotDuration: this.l1Constants.ethereumSlotDuration,
217
- newBlockNumber,
613
+ // If escape hatch is open for the target epoch, do not start checkpoint proposal work and do not attempt invalidations.
614
+ // Still perform governance/slashing voting (as proposer) once per slot.
615
+ // When pipelining, we check the target epoch (slot+1's epoch) since that's the epoch we're building for.
616
+ const isEscapeHatchOpen = await this.epochCache.isEscapeHatchOpen(targetEpoch);
617
+ if (isEscapeHatchOpen) {
618
+ this.setState(SequencerState.PROPOSER_CHECK, slot);
619
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
620
+ if (canPropose) {
621
+ await this.tryVoteWhenEscapeHatchOpen({
622
+ slot,
623
+ proposer
624
+ });
625
+ } else {
626
+ this.log.trace(`Escape hatch open but we are not proposer, skipping vote-only actions`, {
627
+ slot,
628
+ epoch,
629
+ proposer
630
+ });
631
+ }
632
+ return undefined;
633
+ }
634
+ // Next checkpoint follows from the last synced one
635
+ const checkpointNumber = CheckpointNumber(syncedTo.checkpointNumber + 1);
636
+ const logCtx = {
637
+ nowSeconds,
638
+ syncedToL2Slot: syncedTo.syncedL2Slot,
639
+ slot,
640
+ targetSlot,
641
+ slotTs: ts,
642
+ checkpointNumber,
218
643
  isPendingChainValid: pick(syncedTo.pendingChainValidationStatus, 'valid', 'reason', 'invalidIndex')
219
644
  };
220
- // Check that we are a proposer for the next slot
645
+ // Check that we are a proposer for the target slot.
221
646
  this.setState(SequencerState.PROPOSER_CHECK, slot);
222
- const [canPropose, proposer] = await this.checkCanPropose(slot);
223
- // If we are not a proposer check if we should invalidate a invalid block, and bail
647
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
648
+ // If we are not a proposer check if we should invalidate an invalid checkpoint, and bail
224
649
  if (!canPropose) {
225
- await this.considerInvalidatingBlock(syncedTo, slot);
226
- return;
650
+ await this.considerInvalidatingCheckpoint(syncedTo, slot);
651
+ return undefined;
227
652
  }
228
- // In fisherman mode, check if we've already validated this slot to prevent duplicate attempts
229
- if (this.config.fishermanMode) {
230
- if (this.lastSlotForValidationBlock === slot) {
231
- this.log.trace(`Already validated block building for slot ${slot} (skipping)`, {
232
- slot
233
- });
234
- return;
235
- }
236
- this.log.debug(`Building validation block for slot ${slot} (actual proposer: ${proposer?.toString() ?? 'none'})`, {
237
- slot,
238
- proposer: proposer?.toString()
239
- });
240
- // Mark this slot as being validated
241
- this.lastSlotForValidationBlock = slot;
242
- }
243
- // Check that the slot is not taken by a block already (should never happen, since only us can propose for this slot)
244
- if (syncedTo.block && syncedTo.block.header.getSlot() >= slot) {
245
- this.log.warn(`Cannot propose block at next L2 slot ${slot} since that slot was taken by block ${syncedTo.blockNumber}`, {
246
- ...syncLogData,
247
- block: syncedTo.block.header.toInspect()
653
+ // Guard: don't exceed 1-deep pipeline. Without a proposed checkpoint, we can only build
654
+ // confirmed + 1. With a proposed checkpoint, we can build confirmed + 2.
655
+ const confirmedCkpt = syncedTo.checkpointedCheckpointNumber;
656
+ if (checkpointNumber > confirmedCkpt + 2) {
657
+ this.log.verbose(`Skipping slot ${targetSlot}: checkpoint ${checkpointNumber} exceeds max pipeline depth (confirmed=${confirmedCkpt})`);
658
+ return undefined;
659
+ }
660
+ // Check that the target slot is not taken by a block already (should never happen, since only us can propose for this slot)
661
+ if (syncedTo.blockData && syncedTo.blockData.header.getSlot() >= targetSlot) {
662
+ this.log.warn(`Cannot propose block at target slot ${targetSlot} since that slot was taken by block ${syncedTo.blockNumber}`, {
663
+ ...logCtx,
664
+ block: syncedTo.blockData.header.toInspect()
248
665
  });
249
- this.metrics.recordBlockProposalPrecheckFailed('slot_already_taken');
250
- return;
666
+ this.metrics.recordCheckpointPrecheckFailed('slot_already_taken');
667
+ return undefined;
251
668
  }
252
669
  // We now need to get ourselves a publisher.
253
670
  // The returned attestor will be the one we provided if we provided one.
254
671
  // Otherwise it will be a valid attestor for the returned publisher.
255
672
  // In fisherman mode, pass undefined to use the fisherman's own keystore instead of the actual proposer's
256
- const { attestorAddress, publisher } = await this.publisherFactory.create(this.config.fishermanMode ? undefined : proposer);
673
+ const proposerForPublisher = this.config.fishermanMode ? undefined : proposer;
674
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposerForPublisher);
257
675
  this.log.verbose(`Created publisher at address ${publisher.getSenderAddress()} for attestor ${attestorAddress}`);
258
- this.publisher = publisher;
259
676
  // In fisherman mode, set the actual proposer's address for simulations
260
- if (this.config.fishermanMode) {
261
- if (proposer) {
262
- publisher.setProposerAddressForSimulation(proposer);
263
- this.log.debug(`Set proposer address ${proposer} for simulation in fisherman mode`);
264
- }
677
+ if (this.config.fishermanMode && proposer) {
678
+ publisher.setProposerAddressForSimulation(proposer);
679
+ this.log.debug(`Set proposer address ${proposer} for simulation in fisherman mode`);
265
680
  }
266
- // Get proposer credentials
267
- const coinbase = this.validatorClient.getCoinbaseForAttestor(attestorAddress);
268
- const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(attestorAddress);
269
681
  // Prepare invalidation request if the pending chain is invalid (returns undefined if no need)
270
- const invalidateBlock = await publisher.simulateInvalidateBlock(syncedTo.pendingChainValidationStatus);
271
- // Check with the rollup if we can indeed propose at the next L2 slot. This check should not fail
272
- // if all the previous checks are good, but we do it just in case.
273
- const canProposeCheck = await publisher.canProposeAtNextEthBlock(chainTipArchive, proposer ?? EthAddress.ZERO, invalidateBlock);
682
+ let invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(syncedTo.pendingChainValidationStatus);
683
+ // Determine the correct archive and L1 state overrides for the canProposeAt check.
684
+ // The L1 contract reads archives[proposedCheckpointNumber] and compares it with the provided archive.
685
+ // When invalidating or pipelining, the local archive may differ from L1's, so we adjust accordingly.
686
+ let archiveForCheck = syncedTo.archive;
687
+ const l1SimulationOverridesBuilder = new SimulationOverridesBuilder();
688
+ if (this.epochCache.isProposerPipeliningEnabled() && syncedTo.hasProposedCheckpoint) {
689
+ // Parent checkpoint hasn't landed on L1 yet. Override both the proposed checkpoint number
690
+ // and the archive at that checkpoint so L1 simulation sees the correct chain tip.
691
+ const parentCheckpointNumber = CheckpointNumber(checkpointNumber - 1);
692
+ l1SimulationOverridesBuilder.forPendingCheckpoint(parentCheckpointNumber).withPendingArchive(syncedTo.archive);
693
+ this.metrics.recordPipelineDepth(syncedTo.checkpointNumber - syncedTo.checkpointedCheckpointNumber);
694
+ this.log.verbose(`Building on top of proposed checkpoint (pending=${syncedTo.proposedCheckpointData?.checkpointNumber})`);
695
+ // Clear the invalidation - the proposed checkpoint should handle it.
696
+ invalidateCheckpoint = undefined;
697
+ } else if (invalidateCheckpoint) {
698
+ // After invalidation, L1 will roll back to checkpoint N-1. The archive at N-1 already
699
+ // exists on L1, so we just pass the matching archive (the lastArchive of the invalid checkpoint).
700
+ archiveForCheck = invalidateCheckpoint.lastArchive;
701
+ l1SimulationOverridesBuilder.forPendingCheckpoint(invalidateCheckpoint.forcePendingCheckpointNumber);
702
+ this.metrics.recordPipelineDepth(0);
703
+ } else {
704
+ this.metrics.recordPipelineDepth(0);
705
+ }
706
+ const simulationOverridesPlan = l1SimulationOverridesBuilder.build();
707
+ const canProposeCheck = await publisher.canProposeAt(archiveForCheck, proposer ?? EthAddress.ZERO, simulationOverridesPlan);
274
708
  if (canProposeCheck === undefined) {
275
- this.log.warn(`Cannot propose block ${newBlockNumber} at slot ${slot} due to failed rollup contract check`, syncLogData);
709
+ this.log.warn(`Cannot propose checkpoint ${checkpointNumber} at slot ${slot} due to failed rollup contract check`, logCtx);
276
710
  this.emit('proposer-rollup-check-failed', {
277
- reason: 'Rollup contract check failed'
711
+ reason: 'Rollup contract check failed',
712
+ slot
278
713
  });
279
- this.metrics.recordBlockProposalPrecheckFailed('rollup_contract_check_failed');
280
- return;
281
- } else if (canProposeCheck.slot !== slot) {
282
- 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 ${slot} but got ${canProposeCheck.slot}.`, {
283
- ...syncLogData,
714
+ this.metrics.recordCheckpointPrecheckFailed('rollup_contract_check_failed');
715
+ return undefined;
716
+ }
717
+ if (canProposeCheck.slot !== targetSlot) {
718
+ 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}.`, {
719
+ ...logCtx,
284
720
  rollup: canProposeCheck,
285
- newBlockNumber,
286
- expectedSlot: slot
721
+ expectedSlot: targetSlot
287
722
  });
288
723
  this.emit('proposer-rollup-check-failed', {
289
- reason: 'Slot mismatch'
724
+ reason: 'Slot mismatch',
725
+ slot
290
726
  });
291
- this.metrics.recordBlockProposalPrecheckFailed('slot_mismatch');
292
- return;
293
- } else if (canProposeCheck.checkpointNumber !== BigInt(newBlockNumber)) {
294
- this.log.warn(`Cannot propose block due to block mismatch with rollup contract (this can be caused by a pending archiver sync). Expected block ${newBlockNumber} but got ${canProposeCheck.checkpointNumber}.`, {
295
- ...syncLogData,
727
+ this.metrics.recordCheckpointPrecheckFailed('slot_mismatch');
728
+ return undefined;
729
+ }
730
+ if (canProposeCheck.checkpointNumber !== checkpointNumber) {
731
+ 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}.`, {
732
+ ...logCtx,
296
733
  rollup: canProposeCheck,
297
- newBlockNumber,
298
734
  expectedSlot: slot
299
735
  });
300
736
  this.emit('proposer-rollup-check-failed', {
301
- reason: 'Block mismatch'
737
+ reason: 'Block mismatch',
738
+ slot
302
739
  });
303
- this.metrics.recordBlockProposalPrecheckFailed('block_number_mismatch');
304
- return;
305
- }
306
- this.log.debug(`Can propose block ${newBlockNumber} at slot ${slot} as ${proposer}`, {
307
- ...syncLogData
308
- });
309
- const newGlobalVariables = await this.globalsBuilder.buildGlobalVariables(newBlockNumber, coinbase, feeRecipient, slot);
310
- // Enqueue governance and slashing votes (returns promises that will be awaited later)
311
- // In fisherman mode, we simulate slashing but don't actually publish to L1
312
- const votesPromises = this.enqueueGovernanceAndSlashingVotes(publisher, attestorAddress, slot, newGlobalVariables.timestamp);
313
- // Enqueues block invalidation
314
- if (invalidateBlock && !this.config.skipInvalidateBlockAsProposer) {
315
- publisher.enqueueInvalidateBlock(invalidateBlock);
316
- }
317
- // Actual block building
318
- this.setState(SequencerState.INITIALIZING_PROPOSAL, slot);
319
- this.metrics.incOpenSlot(slot, proposer?.toString() ?? 'unknown');
320
- const block = await this.tryBuildBlockAndEnqueuePublish(slot, proposer, newBlockNumber, publisher, newGlobalVariables, chainTipArchive, invalidateBlock);
321
- // Wait until the voting promises have resolved, so all requests are enqueued
322
- await Promise.all(votesPromises);
323
- // In fisherman mode, we don't publish to L1
324
- if (this.config.fishermanMode) {
325
- // Clear pending requests
326
- publisher.clearPendingRequests();
327
- if (block) {
328
- this.log.info(`Validation block building SUCCEEDED for slot ${slot}`, {
329
- blockNumber: newBlockNumber,
330
- slot: Number(slot),
331
- archive: block.archive.toString(),
332
- txCount: block.body.txEffects.length
333
- });
334
- this.lastBlockPublished = block;
335
- this.metrics.recordBlockProposalSuccess();
336
- } else {
337
- // Block building failed in fisherman mode
338
- this.log.warn(`Validation block building FAILED for slot ${slot}`, {
339
- blockNumber: newBlockNumber,
340
- slot: Number(slot)
341
- });
342
- this.metrics.recordBlockProposalFailed('block_build_failed');
343
- }
344
- } else {
345
- // Normal mode: send the tx to L1
346
- const l1Response = await publisher.sendRequests();
347
- const proposedBlock = l1Response?.successfulActions.find((a)=>a === 'propose');
348
- if (proposedBlock) {
349
- this.lastBlockPublished = block;
350
- this.emit('block-published', {
351
- blockNumber: newBlockNumber,
352
- slot: Number(slot)
353
- });
354
- await this.metrics.incFilledSlot(publisher.getSenderAddress().toString(), coinbase);
355
- } else if (block) {
356
- this.emit('block-publish-failed', l1Response ?? {});
357
- }
740
+ this.metrics.recordCheckpointPrecheckFailed('block_number_mismatch');
741
+ return undefined;
358
742
  }
359
- this.setState(SequencerState.IDLE, undefined);
360
- }
361
- /** Tries building a block proposal, and if successful, enqueues it for publishing. */ async tryBuildBlockAndEnqueuePublish(slot, proposer, newBlockNumber, publisher, newGlobalVariables, chainTipArchive, invalidateBlock) {
362
- this.log.verbose(`Preparing proposal for block ${newBlockNumber} at slot ${slot}`, {
743
+ this.lastSlotForCheckpointProposalJob = targetSlot;
744
+ await this.p2pClient.prepareForSlot(targetSlot);
745
+ this.log.info(`Preparing checkpoint proposal ${checkpointNumber} for target slot ${targetSlot} during wall-clock slot ${slot}`, {
746
+ ...logCtx,
363
747
  proposer,
364
- publisher: publisher.getSenderAddress(),
365
- globalVariables: newGlobalVariables.toInspect(),
366
- chainTipArchive,
367
- blockNumber: newBlockNumber,
368
- slot
748
+ pipeliningEnabled: this.epochCache.isProposerPipeliningEnabled()
369
749
  });
370
- const proposalHeader = CheckpointHeader.from({
371
- ...newGlobalVariables,
372
- timestamp: newGlobalVariables.timestamp,
373
- lastArchiveRoot: chainTipArchive,
374
- blockHeadersHash: Fr.ZERO,
375
- contentCommitment: ContentCommitment.empty(),
376
- totalManaUsed: Fr.ZERO
377
- });
378
- let block;
379
- const pendingTxCount = await this.p2pClient.getPendingTxCount();
380
- if (pendingTxCount >= this.minTxsPerBlock) {
381
- // We don't fetch exactly maxTxsPerBlock txs here because we may not need all of them if we hit a limit before,
382
- // and also we may need to fetch more if we don't have enough valid txs.
383
- const pendingTxs = this.p2pClient.iteratePendingTxs();
384
- try {
385
- block = await this.buildBlockAndEnqueuePublish(pendingTxs, proposalHeader, newGlobalVariables, proposer, invalidateBlock, publisher);
386
- } catch (err) {
387
- this.emit('block-build-failed', {
388
- reason: err.message
389
- });
390
- if (err instanceof FormattedViemError) {
391
- this.log.verbose(`Unable to build/enqueue block ${err.message}`);
392
- } else {
393
- this.log.error(`Error building/enqueuing block`, err, {
394
- blockNumber: newBlockNumber,
395
- slot
396
- });
397
- }
398
- this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
399
- }
400
- } else {
401
- this.log.verbose(`Not enough txs to build block ${newBlockNumber} at slot ${slot} (got ${pendingTxCount} txs, need ${this.minTxsPerBlock})`, {
402
- chainTipArchive,
403
- blockNumber: newBlockNumber,
404
- slot
405
- });
406
- this.emit('tx-count-check-failed', {
407
- minTxs: this.minTxsPerBlock,
408
- availableTxs: pendingTxCount
409
- });
410
- this.metrics.recordBlockProposalFailed('insufficient_txs');
411
- }
412
- return block;
750
+ // Create and return the checkpoint proposal job
751
+ return this.createCheckpointProposalJob(slot, targetSlot, targetEpoch, checkpointNumber, syncedTo.blockNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, syncedTo.proposedCheckpointData);
413
752
  }
414
- async safeWork() {
415
- try {
416
- await this.work();
417
- } catch (err) {
418
- if (err instanceof SequencerTooSlowError) {
419
- // Log as warn only if we had to abort halfway through the block proposal
420
- const logLvl = [
421
- SequencerState.INITIALIZING_PROPOSAL,
422
- SequencerState.PROPOSER_CHECK
423
- ].includes(err.proposedState) ? 'debug' : 'warn';
424
- this.log[logLvl](err.message, {
425
- now: this.dateProvider.nowInSeconds()
426
- });
427
- } else {
428
- // Re-throw other errors
429
- throw err;
430
- }
431
- } finally{
432
- this.setState(SequencerState.IDLE, undefined);
433
- }
753
+ createCheckpointProposalJob(slot, targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, proposer, publisher, attestorAddress, invalidateCheckpoint, proposedCheckpointData) {
754
+ return new CheckpointProposalJob(slot, targetSlot, targetEpoch, checkpointNumber, syncedToBlockNumber, 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, this.setState.bind(this), this.tracer, this.log.getBindings(), proposedCheckpointData);
434
755
  }
435
- setState(proposedState, slotNumber, opts = {}) {
756
+ /**
757
+ * Returns the current sequencer state.
758
+ */ getState() {
759
+ return this.state;
760
+ }
761
+ /**
762
+ * Internal helper for setting the sequencer state and checks if we have enough time left in the slot to transition to the new state.
763
+ * @param proposedState - The new state to transition to.
764
+ * @param slotNumber - The current slot number.
765
+ * @param force - Whether to force the transition even if the sequencer is stopped.
766
+ */ setState(proposedState, slotNumber, opts = {}) {
436
767
  if (this.state === SequencerState.STOPPING && proposedState !== SequencerState.STOPPED && !opts.force) {
437
768
  this.log.warn(`Cannot set sequencer to ${proposedState} as it is stopping.`);
438
769
  throw new SequencerInterruptedError();
@@ -446,247 +777,52 @@ export { SequencerState };
446
777
  secondsIntoSlot = this.getSecondsIntoSlot(slotNumber);
447
778
  this.timetable.assertTimeLeft(proposedState, secondsIntoSlot);
448
779
  }
780
+ const oldState = this.state;
781
+ const oldStateSlotNumber = this.stateSlotNumber;
782
+ const stateChanged = proposedState !== oldState;
783
+ const transitionAtMs = performance.now();
784
+ const stateDurationMs = transitionAtMs - this.stateEnteredAtMs;
449
785
  const boringStates = [
450
786
  SequencerState.IDLE,
451
787
  SequencerState.SYNCHRONIZING
452
788
  ];
453
- const logLevel = boringStates.includes(proposedState) && boringStates.includes(this.state) ? 'trace' : 'debug';
454
- this.log[logLevel](`Transitioning from ${this.state} to ${proposedState}`, {
789
+ const logLevel = boringStates.includes(proposedState) && boringStates.includes(oldState) ? 'trace' : 'debug';
790
+ this.stateLog[logLevel](`Transitioning from ${oldState} to ${proposedState}`, {
791
+ oldState,
792
+ newState: proposedState,
455
793
  slotNumber,
456
- secondsIntoSlot
794
+ stateSlotNumber: oldStateSlotNumber,
795
+ secondsIntoSlot,
796
+ ...stateChanged && {
797
+ stateDurationMs: Math.ceil(stateDurationMs)
798
+ }
457
799
  });
458
800
  this.emit('state-changed', {
459
- oldState: this.state,
801
+ oldState,
460
802
  newState: proposedState,
461
803
  secondsIntoSlot,
462
- slotNumber
804
+ slot: slotNumber
463
805
  });
464
- this.state = proposedState;
465
- }
466
- async dropFailedTxsFromP2P(failedTxs) {
467
- if (failedTxs.length === 0) {
468
- return;
469
- }
470
- const failedTxData = failedTxs.map((fail)=>fail.tx);
471
- const failedTxHashes = failedTxData.map((tx)=>tx.getTxHash());
472
- this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
473
- await this.p2pClient.deleteTxs(failedTxHashes);
474
- }
475
- getBlockBuilderOptions(slot) {
476
- // Deadline for processing depends on whether we're proposing a block
477
- const secondsIntoSlot = this.getSecondsIntoSlot(slot);
478
- const processingEndTimeWithinSlot = this.timetable.getBlockProposalExecTimeEnd(secondsIntoSlot);
479
- // Deadline is only set if enforceTimeTable is enabled.
480
- const deadline = this.enforceTimeTable ? new Date((this.getSlotStartBuildTimestamp(slot) + processingEndTimeWithinSlot) * 1000) : undefined;
481
- return {
482
- maxTransactions: this.maxTxsPerBlock,
483
- maxBlockSize: this.maxBlockSizeInBytes,
484
- maxBlockGas: this.maxBlockGas,
485
- maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
486
- deadline
487
- };
488
- }
489
- /**
490
- * @notice Build and propose a block to the chain
491
- *
492
- * @dev MUST throw instead of exiting early to ensure that world-state
493
- * is being rolled back if the block is dropped.
494
- *
495
- * @param pendingTxs - Iterable of pending transactions to construct the block from
496
- * @param proposalHeader - The partial header constructed for the proposal
497
- * @param newGlobalVariables - The global variables for the new block
498
- * @param proposerAddress - The address of the proposer
499
- */ async buildBlockAndEnqueuePublish(pendingTxs, proposalHeader, newGlobalVariables, proposerAddress, invalidateBlock, publisher) {
500
- await publisher.validateBlockHeader(proposalHeader, invalidateBlock);
501
- const blockNumber = newGlobalVariables.blockNumber;
502
- const slot = proposalHeader.slotNumber;
503
- const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(blockNumber);
504
- const workTimer = new Timer();
505
- this.setState(SequencerState.CREATING_BLOCK, slot);
506
- try {
507
- const blockBuilderOptions = this.getBlockBuilderOptions(slot);
508
- const buildBlockRes = await this.blockBuilder.buildBlock(pendingTxs, l1ToL2Messages, newGlobalVariables, blockBuilderOptions);
509
- const { publicGas, block, publicProcessorDuration, numTxs, numMsgs, blockBuildingTimer, usedTxs, failedTxs } = buildBlockRes;
510
- const blockBuildDuration = workTimer.ms();
511
- await this.dropFailedTxsFromP2P(failedTxs);
512
- const minTxsPerBlock = this.minTxsPerBlock;
513
- if (numTxs < minTxsPerBlock) {
514
- this.log.warn(`Block ${blockNumber} has too few txs to be proposed (got ${numTxs} but required ${minTxsPerBlock})`, {
515
- slot,
516
- blockNumber,
517
- numTxs
518
- });
519
- throw new Error(`Block has too few successful txs to be proposed`);
520
- }
521
- // TODO(@PhilWindle) We should probably periodically check for things like another
522
- // block being published before ours instead of just waiting on our block
523
- await publisher.validateBlockHeader(block.getCheckpointHeader(), invalidateBlock);
524
- const blockStats = {
525
- eventName: 'l2-block-built',
526
- creator: proposerAddress?.toString() ?? publisher.getSenderAddress().toString(),
527
- duration: workTimer.ms(),
528
- publicProcessDuration: publicProcessorDuration,
529
- rollupCircuitsDuration: blockBuildingTimer.ms(),
530
- ...block.getStats()
531
- };
532
- const blockHash = await block.hash();
533
- const txHashes = block.body.txEffects.map((tx)=>tx.txHash);
534
- this.log.info(`Built block ${block.number} for slot ${slot} with ${numTxs} txs and ${numMsgs} messages. ${publicGas.l2Gas / workTimer.s()} mana/s`, {
535
- blockHash,
536
- globalVariables: block.header.globalVariables.toInspect(),
537
- txHashes,
538
- ...blockStats
539
- });
540
- // In fisherman mode, skip attestation collection
541
- let attestationsAndSigners;
542
- if (this.config.fishermanMode) {
543
- this.log.debug('Skipping attestation collection');
544
- attestationsAndSigners = CommitteeAttestationsAndSigners.empty();
545
- } else {
546
- this.log.debug('Collecting attestations');
547
- attestationsAndSigners = await this.collectAttestations(block, usedTxs, proposerAddress);
548
- this.log.verbose(`Collected ${attestationsAndSigners.attestations.length} attestations for block ${blockNumber} at slot ${slot}`, {
549
- blockHash,
550
- blockNumber,
551
- slot
552
- });
553
- }
554
- // In fisherman mode, skip attestation signing
555
- const attestationsAndSignersSignature = this.config.fishermanMode || !this.validatorClient ? Signature.empty() : await this.validatorClient.signAttestationsAndSigners(attestationsAndSigners, proposerAddress ?? publisher.getSenderAddress());
556
- await this.enqueuePublishL2Block(block, attestationsAndSigners, attestationsAndSignersSignature, invalidateBlock, publisher);
557
- this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
558
- return block;
559
- } catch (err) {
560
- this.metrics.recordFailedBlock();
561
- throw err;
562
- }
563
- }
564
- async collectAttestations(block, txs, proposerAddress) {
565
- const { committee, seed, epoch } = await this.epochCache.getCommittee(block.slot);
566
- // We checked above that the committee is defined, so this should never happen.
567
- if (!committee) {
568
- throw new Error('No committee when collecting attestations');
569
- }
570
- if (committee.length === 0) {
571
- this.log.verbose(`Attesting committee is empty`);
572
- return CommitteeAttestationsAndSigners.empty();
573
- } else {
574
- this.log.debug(`Attesting committee length is ${committee.length}`);
575
- }
576
- if (!this.validatorClient) {
577
- throw new Error('Missing validator client: Cannot collect attestations');
578
- }
579
- const numberOfRequiredAttestations = Math.floor(committee.length * 2 / 3) + 1;
580
- const slotNumber = block.header.globalVariables.slotNumber;
581
- this.setState(SequencerState.COLLECTING_ATTESTATIONS, slotNumber);
582
- this.log.debug('Creating block proposal for validators');
583
- const blockProposalOptions = {
584
- publishFullTxs: !!this.config.publishTxsWithProposals,
585
- broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
586
- };
587
- const proposal = await this.validatorClient.createBlockProposal(block.header.globalVariables.blockNumber, block.getCheckpointHeader(), block.archive.root, txs, proposerAddress, blockProposalOptions);
588
- if (!proposal) {
589
- throw new Error(`Failed to create block proposal`);
590
- }
591
- if (this.config.skipCollectingAttestations) {
592
- this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
593
- const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
594
- return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
595
- }
596
- this.log.debug('Broadcasting block proposal to validators');
597
- await this.validatorClient.broadcastBlockProposal(proposal);
598
- const attestationTimeAllowed = this.enforceTimeTable ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_BLOCK) : this.aztecSlotDuration;
599
- this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
600
- const timer = new Timer();
601
- let collectedAttestationsCount = 0;
602
- try {
603
- const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
604
- const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline);
605
- collectedAttestationsCount = attestations.length;
606
- // note: the smart contract requires that the signatures are provided in the order of the committee
607
- const sorted = orderAttestations(attestations, committee);
608
- // manipulate the attestations if we've been configured to do so
609
- if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
610
- return this.manipulateAttestations(block, epoch, seed, committee, sorted);
611
- }
612
- return new CommitteeAttestationsAndSigners(sorted);
613
- } catch (err) {
614
- if (err && err instanceof AttestationTimeoutError) {
615
- collectedAttestationsCount = err.collectedCount;
616
- }
617
- throw err;
618
- } finally{
619
- this.metrics.recordCollectedAttestations(collectedAttestationsCount, timer.ms());
620
- }
621
- }
622
- /** Breaks the attestations before publishing based on attack configs */ manipulateAttestations(block, epoch, seed, committee, attestations) {
623
- // Compute the proposer index in the committee, since we dont want to tweak it.
624
- // Otherwise, the L1 rollup contract will reject the block outright.
625
- const proposerIndex = Number(this.epochCache.computeProposerIndex(block.slot, epoch, seed, BigInt(committee.length)));
626
- if (this.config.injectFakeAttestation) {
627
- // Find non-empty attestations that are not from the proposer
628
- const nonProposerIndices = [];
629
- for(let i = 0; i < attestations.length; i++){
630
- if (!attestations[i].signature.isEmpty() && i !== proposerIndex) {
631
- nonProposerIndices.push(i);
632
- }
633
- }
634
- if (nonProposerIndices.length > 0) {
635
- const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
636
- this.log.warn(`Injecting fake attestation in block ${block.number} at index ${targetIndex}`);
637
- unfreeze(attestations[targetIndex]).signature = Signature.random();
638
- }
639
- return new CommitteeAttestationsAndSigners(attestations);
640
- }
641
- if (this.config.shuffleAttestationOrdering) {
642
- this.log.warn(`Shuffling attestation ordering in block ${block.number} (proposer index ${proposerIndex})`);
643
- const shuffled = [
644
- ...attestations
645
- ];
646
- const [i, j] = [
647
- (proposerIndex + 1) % shuffled.length,
648
- (proposerIndex + 2) % shuffled.length
649
- ];
650
- const valueI = shuffled[i];
651
- const valueJ = shuffled[j];
652
- shuffled[i] = valueJ;
653
- shuffled[j] = valueI;
654
- const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
655
- return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
656
- }
657
- return new CommitteeAttestationsAndSigners(attestations);
658
- }
659
- /**
660
- * Publishes the L2Block to the rollup contract.
661
- * @param block - The L2Block to be published.
662
- */ async enqueuePublishL2Block(block, attestationsAndSigners, attestationsAndSignersSignature, invalidateBlock, publisher) {
663
- // Publishes new block to the network and awaits the tx to be mined
664
- this.setState(SequencerState.PUBLISHING_BLOCK, block.header.globalVariables.slotNumber);
665
- // Time out tx at the end of the slot
666
- const slot = block.header.globalVariables.slotNumber;
667
- const txTimeoutAt = new Date((this.getSlotStartBuildTimestamp(slot) + this.aztecSlotDuration) * 1000);
668
- const enqueued = await publisher.enqueueProposeL2Block(block, attestationsAndSigners, attestationsAndSignersSignature, {
669
- txTimeoutAt,
670
- forcePendingBlockNumber: invalidateBlock?.forcePendingBlockNumber
671
- });
672
- if (!enqueued) {
673
- throw new Error(`Failed to enqueue publish of block ${block.number}`);
806
+ if (stateChanged) {
807
+ this.metrics.recordStateDuration(stateDurationMs, oldState);
808
+ this.stateEnteredAtMs = transitionAtMs;
809
+ this.stateSlotNumber = slotNumber;
674
810
  }
811
+ this.state = proposedState;
675
812
  }
676
813
  /**
677
814
  * Returns whether all dependencies have caught up.
678
815
  * We don't check against the previous block submitted since it may have been reorg'd out.
679
816
  */ async checkSync(args) {
680
- // Check that the archiver and dependencies have synced to the previous L1 slot at least
681
- // TODO(#14766): Archiver reports L1 timestamp based on L1 blocks seen, which means that a missed L1 block will
682
- // cause the archiver L1 timestamp to fall behind, and cause this sequencer to start processing one L1 slot later.
683
- const l1Timestamp = await this.l2BlockSource.getL1Timestamp();
684
- const { slot, ts } = args;
685
- if (l1Timestamp === undefined || l1Timestamp + BigInt(this.l1Constants.ethereumSlotDuration) < ts) {
817
+ // Check that the archiver has fully synced the L2 slot before the one we want to propose in.
818
+ // The archiver reports sync progress via L1 block timestamps and synced checkpoint slots.
819
+ // See getSyncedL2SlotNumber for how missed L1 blocks are handled.
820
+ const syncedL2Slot = await this.l2BlockSource.getSyncedL2SlotNumber();
821
+ const { slot } = args;
822
+ if (syncedL2Slot === undefined || syncedL2Slot + 1 < slot) {
686
823
  this.log.debug(`Cannot propose block at next L2 slot ${slot} due to pending sync from L1`, {
687
824
  slot,
688
- ts,
689
- l1Timestamp
825
+ syncedL2Slot
690
826
  });
691
827
  return undefined;
692
828
  }
@@ -695,21 +831,30 @@ export { SequencerState };
695
831
  number: syncSummary.latestBlockNumber,
696
832
  hash: syncSummary.latestBlockHash
697
833
  })),
698
- this.l2BlockSource.getL2Tips().then((t)=>t.latest),
834
+ this.l2BlockSource.getL2Tips().then((t)=>({
835
+ proposed: t.proposed,
836
+ checkpointed: t.checkpointed,
837
+ proposedCheckpoint: t.proposedCheckpoint
838
+ })),
699
839
  this.p2pClient.getStatus().then((p2p)=>p2p.syncedToL2Block),
700
- this.l1ToL2MessageSource.getL2Tips().then((t)=>t.latest),
701
- this.l2BlockSource.getPendingChainValidationStatus()
840
+ this.l1ToL2MessageSource.getL2Tips().then((t)=>({
841
+ proposed: t.proposed,
842
+ checkpointed: t.checkpointed
843
+ })),
844
+ this.l2BlockSource.getPendingChainValidationStatus(),
845
+ this.l2BlockSource.getLastProposedCheckpoint()
702
846
  ]);
703
- const [worldState, l2BlockSource, p2p, l1ToL2MessageSource, pendingChainValidationStatus] = syncedBlocks;
704
- // The archiver reports 'undefined' hash for the genesis block
705
- // because it doesn't have access to world state to compute it (facepalm)
706
- const result = l2BlockSource.hash === undefined ? worldState.number === 0 && p2p.number === 0 && l1ToL2MessageSource.number === 0 : worldState.hash === l2BlockSource.hash && p2p.hash === l2BlockSource.hash && l1ToL2MessageSource.hash === l2BlockSource.hash;
847
+ const [worldState, l2Tips, p2p, l1ToL2MessageSourceTips, pendingChainValidationStatus, proposedCheckpointData] = syncedBlocks;
848
+ // Handle zero as a special case, since the block hash won't match across services if we're changing the prefilled data for the genesis block,
849
+ // as the world state can compute the new genesis block hash, but other components use the hardcoded constant.
850
+ // TODO(palla/mbps): Fix the above. All components should be able to handle dynamic genesis block hashes.
851
+ const result = l2Tips.proposed.number === 0 && l2Tips.checkpointed.block.number === 0 && l2Tips.checkpointed.checkpoint.number === 0 && worldState.number === 0 && p2p.number === 0 && l1ToL2MessageSourceTips.proposed.number === 0 && l1ToL2MessageSourceTips.checkpointed.block.number === 0 && l1ToL2MessageSourceTips.checkpointed.checkpoint.number === 0 || 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;
707
852
  if (!result) {
708
853
  this.log.debug(`Sequencer sync check failed`, {
709
854
  worldState,
710
- l2BlockSource,
855
+ l2BlockSource: l2Tips.proposed,
711
856
  p2p,
712
- l1ToL2MessageSource
857
+ l1ToL2MessageSourceTips
713
858
  });
714
859
  return undefined;
715
860
  }
@@ -718,88 +863,53 @@ export { SequencerState };
718
863
  if (blockNumber < INITIAL_L2_BLOCK_NUM) {
719
864
  const archive = new Fr((await this.worldState.getCommitted().getTreeInfo(MerkleTreeId.ARCHIVE)).root);
720
865
  return {
721
- blockNumber: INITIAL_L2_BLOCK_NUM - 1,
866
+ checkpointNumber: CheckpointNumber.ZERO,
867
+ checkpointedCheckpointNumber: CheckpointNumber.ZERO,
868
+ blockNumber: BlockNumber.ZERO,
722
869
  archive,
723
- l1Timestamp,
870
+ hasProposedCheckpoint: false,
871
+ syncedL2Slot,
724
872
  pendingChainValidationStatus
725
873
  };
726
874
  }
727
- const block = await this.l2BlockSource.getBlock(blockNumber);
728
- if (!block) {
875
+ const blockData = await this.l2BlockSource.getBlockData(blockNumber);
876
+ if (!blockData) {
729
877
  // this shouldn't really happen because a moment ago we checked that all components were in sync
730
- this.log.error(`Failed to get L2 block ${blockNumber} from the archiver with all components in sync`);
878
+ this.log.error(`Failed to get L2 block data ${blockNumber} from the archiver with all components in sync`);
731
879
  return undefined;
732
880
  }
881
+ const hasProposedCheckpoint = l2Tips.proposedCheckpoint.checkpoint.number > l2Tips.checkpointed.checkpoint.number;
733
882
  return {
734
- block,
735
- blockNumber: block.number,
736
- archive: block.archive.root,
737
- l1Timestamp,
883
+ blockData,
884
+ blockNumber: blockData.header.getBlockNumber(),
885
+ checkpointNumber: blockData.checkpointNumber,
886
+ checkpointedCheckpointNumber: l2Tips.checkpointed.checkpoint.number,
887
+ archive: blockData.archive.root,
888
+ hasProposedCheckpoint,
889
+ proposedCheckpointData,
890
+ syncedL2Slot,
738
891
  pendingChainValidationStatus
739
892
  };
740
893
  }
741
894
  /**
742
- * Enqueues governance and slashing votes with the publisher. Does not block.
743
- * @param publisher - The publisher to enqueue votes with
744
- * @param attestorAddress - The attestor address to use for signing
745
- * @param slot - The slot number
746
- * @param timestamp - The timestamp for the votes
747
- * @param context - Optional context for logging (e.g., block number)
748
- * @returns A tuple of [governanceEnqueued, slashingEnqueued]
749
- */ enqueueGovernanceAndSlashingVotes(publisher, attestorAddress, slot, timestamp) {
750
- try {
751
- const signerFn = (msg)=>this.validatorClient.signWithAddress(attestorAddress, msg).then((s)=>s.toString());
752
- const enqueueGovernancePromise = this.governanceProposerPayload && !this.governanceProposerPayload.isZero() ? publisher.enqueueGovernanceCastSignal(this.governanceProposerPayload, slot, timestamp, attestorAddress, signerFn).catch((err)=>{
753
- this.log.error(`Error enqueuing governance vote`, err, {
754
- slot
755
- });
756
- return false;
757
- }) : undefined;
758
- const enqueueSlashingPromise = this.slasherClient ? this.slasherClient.getProposerActions(slot).then((actions)=>{
759
- // Record metrics for fisherman mode
760
- if (this.config.fishermanMode && actions.length > 0) {
761
- this.log.debug(`Fisherman mode: simulating ${actions.length} slashing action(s) for slot ${slot}`, {
762
- slot,
763
- actionCount: actions.length
764
- });
765
- this.metrics.recordSlashingAttempt(actions.length);
766
- }
767
- // Enqueue the actions to fully simulate L1 tx building (they won't be sent in fisherman mode)
768
- return publisher.enqueueSlashingActions(actions, slot, timestamp, attestorAddress, signerFn);
769
- }).catch((err)=>{
770
- this.log.error(`Error enqueuing slashing actions`, err, {
771
- slot
772
- });
773
- return false;
774
- }) : undefined;
775
- return [
776
- enqueueGovernancePromise,
777
- enqueueSlashingPromise
778
- ];
779
- } catch (err) {
780
- this.log.error(`Error enqueueing governance and slashing votes`, err);
781
- return [
782
- undefined,
783
- undefined
784
- ];
785
- }
786
- }
787
- /**
788
895
  * Checks if we are the proposer for the next slot.
789
896
  * @returns True if we can propose, and the proposer address (undefined if anyone can propose)
790
- */ async checkCanPropose(slot) {
897
+ */ async checkCanPropose(targetSlot) {
791
898
  let proposer;
792
899
  try {
793
- proposer = await this.epochCache.getProposerAttesterAddressInSlot(slot);
900
+ proposer = await this.epochCache.getProposerAttesterAddressInSlot(targetSlot);
794
901
  } catch (e) {
795
902
  if (e instanceof NoCommitteeError) {
796
- this.log.warn(`Cannot propose at next L2 slot ${slot} since the committee does not exist on L1`);
903
+ if (this.lastSlotForNoCommitteeWarning !== targetSlot) {
904
+ this.lastSlotForNoCommitteeWarning = targetSlot;
905
+ this.log.warn(`Cannot propose at target slot ${targetSlot} since the committee does not exist on L1`);
906
+ }
797
907
  return [
798
908
  false,
799
909
  undefined
800
910
  ];
801
911
  }
802
- this.log.error(`Error getting proposer for slot ${slot}`, e);
912
+ this.log.error(`Error getting proposer for target slot ${targetSlot}`, e);
803
913
  return [
804
914
  false,
805
915
  undefined
@@ -822,7 +932,8 @@ export { SequencerState };
822
932
  const validatorAddresses = this.validatorClient.getValidatorAddresses();
823
933
  const weAreProposer = validatorAddresses.some((addr)=>addr.equals(proposer));
824
934
  if (!weAreProposer) {
825
- this.log.debug(`Cannot propose at slot ${slot} since we are not a proposer`, {
935
+ this.log.debug(`Cannot propose at target slot ${targetSlot} since we are not a proposer`, {
936
+ targetSlot,
826
937
  validatorAddresses,
827
938
  proposer
828
939
  });
@@ -831,6 +942,10 @@ export { SequencerState };
831
942
  proposer
832
943
  ];
833
944
  }
945
+ this.log.info(`We are the proposer for pipeline slot ${targetSlot}`, {
946
+ targetSlot,
947
+ proposer
948
+ });
834
949
  return [
835
950
  true,
836
951
  proposer
@@ -840,49 +955,50 @@ export { SequencerState };
840
955
  * Tries to vote on slashing actions and governance when the sync check fails but we're past the max time for initializing a proposal.
841
956
  * This allows the sequencer to participate in governance/slashing votes even when it cannot build blocks.
842
957
  */ async tryVoteWhenSyncFails(args) {
843
- const { slot, ts } = args;
958
+ const { slot, targetSlot } = args;
844
959
  // Prevent duplicate attempts in the same slot
845
- if (this.lastSlotForVoteWhenSyncFailed === slot) {
846
- this.log.debug(`Already attempted to vote in slot ${slot} (skipping)`);
960
+ if (this.lastSlotForFallbackVote === slot) {
961
+ this.log.trace(`Already attempted to vote in slot ${slot} (skipping)`);
847
962
  return;
848
963
  }
849
964
  // Check if we're past the max time for initializing a proposal
850
965
  const secondsIntoSlot = this.getSecondsIntoSlot(slot);
851
- const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_PROPOSAL);
966
+ const maxAllowedTime = this.timetable.getMaxAllowedTime(SequencerState.INITIALIZING_CHECKPOINT);
852
967
  // If we haven't exceeded the time limit for initializing a proposal, don't proceed with voting
853
968
  // We use INITIALIZING_PROPOSAL time limit because if we're past that, we can't build a block anyway
854
969
  if (maxAllowedTime === undefined || secondsIntoSlot <= maxAllowedTime) {
855
- this.log.trace(`Not attempting to vote since there is still for block building`, {
970
+ this.log.trace(`Not attempting to vote since there is still time for block building`, {
856
971
  secondsIntoSlot,
857
972
  maxAllowedTime
858
973
  });
859
974
  return;
860
975
  }
861
- this.log.debug(`Sync for slot ${slot} failed, checking for voting opportunities`, {
976
+ this.log.trace(`Sync for slot ${slot} failed, checking for voting opportunities`, {
862
977
  secondsIntoSlot,
863
978
  maxAllowedTime
864
979
  });
865
980
  // Check if we're a proposer or proposal is open
866
- const [canPropose, proposer] = await this.checkCanPropose(slot);
981
+ const [canPropose, proposer] = await this.checkCanPropose(targetSlot);
867
982
  if (!canPropose) {
868
- this.log.debug(`Cannot vote in slot ${slot} since we are not a proposer`, {
983
+ this.log.trace(`Cannot vote in slot ${slot} since we are not a proposer`, {
869
984
  slot,
870
985
  proposer
871
986
  });
872
987
  return;
873
988
  }
874
989
  // Mark this slot as attempted
875
- this.lastSlotForVoteWhenSyncFailed = slot;
990
+ this.lastSlotForFallbackVote = slot;
876
991
  // Get a publisher for voting
877
992
  const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
878
993
  this.log.debug(`Attempting to vote despite sync failure at slot ${slot}`, {
879
994
  attestorAddress,
880
995
  slot
881
996
  });
882
- // Enqueue governance and slashing votes using the shared helper method
883
- const votesPromises = this.enqueueGovernanceAndSlashingVotes(publisher, attestorAddress, slot, ts);
884
- await Promise.all(votesPromises);
885
- if (votesPromises.every((p)=>!p)) {
997
+ // Enqueue governance and slashing votes (voter uses the target slot for L1 submission)
998
+ const voter = new CheckpointVoter(targetSlot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
999
+ const votesPromises = voter.enqueueVotes();
1000
+ const votes = await Promise.all(votesPromises);
1001
+ if (votes.every((p)=>!p)) {
886
1002
  this.log.debug(`No votes to enqueue for slot ${slot}`);
887
1003
  return;
888
1004
  }
@@ -892,25 +1008,53 @@ export { SequencerState };
892
1008
  await publisher.sendRequests();
893
1009
  }
894
1010
  /**
1011
+ * Tries to vote on slashing actions and governance proposals when escape hatch is open.
1012
+ * This allows the sequencer to participate in voting without performing checkpoint proposal work.
1013
+ */ async tryVoteWhenEscapeHatchOpen(args) {
1014
+ const { slot, proposer } = args;
1015
+ // Prevent duplicate attempts in the same slot
1016
+ if (this.lastSlotForFallbackVote === slot) {
1017
+ this.log.trace(`Already attempted to vote in slot ${slot} (escape hatch open, skipping)`);
1018
+ return;
1019
+ }
1020
+ // Mark this slot as attempted
1021
+ this.lastSlotForFallbackVote = slot;
1022
+ const { attestorAddress, publisher } = await this.publisherFactory.create(proposer);
1023
+ this.log.debug(`Escape hatch open for slot ${slot}, attempting vote-only actions`, {
1024
+ slot,
1025
+ attestorAddress
1026
+ });
1027
+ const voter = new CheckpointVoter(slot, publisher, attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log);
1028
+ const votesPromises = voter.enqueueVotes();
1029
+ const votes = await Promise.all(votesPromises);
1030
+ if (votes.every((p)=>!p)) {
1031
+ this.log.debug(`No votes to enqueue for slot ${slot} (escape hatch open)`);
1032
+ return;
1033
+ }
1034
+ this.log.info(`Voting in slot ${slot} (escape hatch open)`, {
1035
+ slot
1036
+ });
1037
+ await publisher.sendRequests();
1038
+ }
1039
+ /**
895
1040
  * Considers invalidating a block if the pending chain is invalid. Depends on how long the invalid block
896
1041
  * has been there without being invalidated and whether the sequencer is in the committee or not. We always
897
1042
  * have the proposer try to invalidate, but if they fail, the sequencers in the committee are expected to try,
898
1043
  * and if they fail, any sequencer will try as well.
899
- */ async considerInvalidatingBlock(syncedTo, currentSlot) {
900
- const { pendingChainValidationStatus, l1Timestamp } = syncedTo;
1044
+ */ async considerInvalidatingCheckpoint(syncedTo, currentSlot) {
1045
+ const { pendingChainValidationStatus, syncedL2Slot } = syncedTo;
901
1046
  if (pendingChainValidationStatus.valid) {
902
1047
  return;
903
1048
  }
904
- const { publisher } = await this.publisherFactory.create(undefined);
905
- const invalidBlockNumber = pendingChainValidationStatus.block.blockNumber;
906
- const invalidBlockTimestamp = pendingChainValidationStatus.block.timestamp;
907
- const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidBlockTimestamp);
1049
+ const invalidCheckpointNumber = pendingChainValidationStatus.checkpoint.checkpointNumber;
1050
+ const invalidCheckpointTimestamp = pendingChainValidationStatus.checkpoint.timestamp;
1051
+ const timeSinceChainInvalid = this.dateProvider.nowInSeconds() - Number(invalidCheckpointTimestamp);
908
1052
  const ourValidatorAddresses = this.validatorClient.getValidatorAddresses();
909
1053
  const { secondsBeforeInvalidatingBlockAsCommitteeMember, secondsBeforeInvalidatingBlockAsNonCommitteeMember } = this.config;
910
1054
  const logData = {
911
- invalidL1Timestamp: invalidBlockTimestamp,
912
- l1Timestamp,
913
- invalidBlock: pendingChainValidationStatus.block,
1055
+ invalidL1Timestamp: invalidCheckpointTimestamp,
1056
+ syncedL2Slot,
1057
+ invalidCheckpoint: pendingChainValidationStatus.checkpoint,
914
1058
  secondsBeforeInvalidatingBlockAsCommitteeMember,
915
1059
  secondsBeforeInvalidatingBlockAsNonCommitteeMember,
916
1060
  ourValidatorAddresses,
@@ -923,20 +1067,61 @@ export { SequencerState };
923
1067
  this.log.debug(`Not invalidating pending chain`, logData);
924
1068
  return;
925
1069
  }
926
- const invalidateBlock = await publisher.simulateInvalidateBlock(pendingChainValidationStatus);
927
- if (!invalidateBlock) {
928
- this.log.warn(`Failed to simulate invalidate block`, logData);
1070
+ let validatorToUse;
1071
+ if (invalidateAsCommitteeMember) {
1072
+ // When invalidating as a committee member, use first validator that's actually in the committee
1073
+ const { committee } = await this.epochCache.getCommittee(currentSlot);
1074
+ if (committee) {
1075
+ const committeeSet = new Set(committee.map((addr)=>addr.toString()));
1076
+ validatorToUse = ourValidatorAddresses.find((addr)=>committeeSet.has(addr.toString())) ?? ourValidatorAddresses[0];
1077
+ } else {
1078
+ validatorToUse = ourValidatorAddresses[0];
1079
+ }
1080
+ } else {
1081
+ // When invalidating as a non-committee member, use the first validator
1082
+ validatorToUse = ourValidatorAddresses[0];
1083
+ }
1084
+ const { publisher } = await this.publisherFactory.create(validatorToUse);
1085
+ const invalidateCheckpoint = await publisher.simulateInvalidateCheckpoint(pendingChainValidationStatus);
1086
+ if (!invalidateCheckpoint) {
1087
+ this.log.warn(`Failed to simulate invalidate checkpoint`, logData);
929
1088
  return;
930
1089
  }
931
- this.log.info(invalidateAsCommitteeMember ? `Invalidating block ${invalidBlockNumber} as committee member` : `Invalidating block ${invalidBlockNumber} as non-committee member`, logData);
932
- publisher.enqueueInvalidateBlock(invalidateBlock);
1090
+ this.log.info(invalidateAsCommitteeMember ? `Invalidating checkpoint ${invalidCheckpointNumber} as committee member` : `Invalidating checkpoint ${invalidCheckpointNumber} as non-committee member`, logData);
1091
+ publisher.enqueueInvalidateCheckpoint(invalidateCheckpoint);
933
1092
  if (!this.config.fishermanMode) {
934
1093
  await publisher.sendRequests();
935
1094
  } else {
936
- this.log.info('Invalidating block in fisherman mode, clearing pending requests');
1095
+ this.log.info('Invalidating checkpoint in fisherman mode, clearing pending requests');
937
1096
  publisher.clearPendingRequests();
938
1097
  }
939
1098
  }
1099
+ logStrategyComparison(epoch, publisher) {
1100
+ const feeAnalyzer = publisher.getL1FeeAnalyzer();
1101
+ if (!feeAnalyzer) {
1102
+ return;
1103
+ }
1104
+ const comparison = feeAnalyzer.getStrategyComparison();
1105
+ if (comparison.length === 0) {
1106
+ this.log.debug(`No strategy data available yet for epoch ${epoch}`);
1107
+ return;
1108
+ }
1109
+ this.log.info(`L1 Fee Strategy Performance Report - End of Epoch ${epoch}`, {
1110
+ epoch: Number(epoch),
1111
+ totalAnalyses: comparison[0]?.totalAnalyses,
1112
+ strategies: comparison.map((s)=>({
1113
+ id: s.strategyId,
1114
+ name: s.strategyName,
1115
+ inclusionRate: `${(s.inclusionRate * 100).toFixed(1)}%`,
1116
+ inclusionCount: `${s.inclusionCount}/${s.totalAnalyses}`,
1117
+ avgCostEth: s.avgEstimatedCostEth.toFixed(6),
1118
+ totalCostEth: s.totalEstimatedCostEth.toFixed(6),
1119
+ avgOverpaymentEth: s.avgOverpaymentEth.toFixed(6),
1120
+ totalOverpaymentEth: s.totalOverpaymentEth.toFixed(6),
1121
+ avgPriorityFeeDeltaGwei: s.avgPriorityFeeDeltaGwei.toFixed(2)
1122
+ }))
1123
+ });
1124
+ }
940
1125
  getSlotStartBuildTimestamp(slotNumber) {
941
1126
  return getSlotStartBuildTimestamp(slotNumber, this.l1Constants);
942
1127
  }
@@ -953,24 +1138,19 @@ export { SequencerState };
953
1138
  getSlasherClient() {
954
1139
  return this.slasherClient;
955
1140
  }
1141
+ get tracer() {
1142
+ return this.metrics.tracer;
1143
+ }
1144
+ getValidatorAddresses() {
1145
+ return this.validatorClient?.getValidatorAddresses();
1146
+ }
1147
+ /** Updates the publisher factory's node keystore adapter after a keystore reload. */ updatePublisherNodeKeyStore(adapter) {
1148
+ this.publisherFactory.updateNodeKeyStore(adapter);
1149
+ }
1150
+ getConfig() {
1151
+ return this.config;
1152
+ }
1153
+ get l1PublishingTime() {
1154
+ return this.config.l1PublishingTime ?? this.l1Constants.ethereumSlotDuration;
1155
+ }
956
1156
  }
957
- _ts_decorate([
958
- trackSpan('Sequencer.work')
959
- ], Sequencer.prototype, "safeWork", null);
960
- _ts_decorate([
961
- trackSpan('Sequencer.buildBlockAndEnqueuePublish', (_validTxs, _proposalHeader, newGlobalVariables)=>({
962
- [Attributes.BLOCK_NUMBER]: newGlobalVariables.blockNumber
963
- }))
964
- ], Sequencer.prototype, "buildBlockAndEnqueuePublish", null);
965
- _ts_decorate([
966
- trackSpan('Sequencer.collectAttestations', (block, txHashes)=>({
967
- [Attributes.BLOCK_NUMBER]: block.number,
968
- [Attributes.BLOCK_ARCHIVE]: block.archive.toString(),
969
- [Attributes.BLOCK_TXS_COUNT]: txHashes.length
970
- }))
971
- ], Sequencer.prototype, "collectAttestations", null);
972
- _ts_decorate([
973
- trackSpan('Sequencer.enqueuePublishL2Block', (block)=>({
974
- [Attributes.BLOCK_NUMBER]: block.number
975
- }))
976
- ], Sequencer.prototype, "enqueuePublishL2Block", null);