@aztec/sequencer-client 0.0.1-commit.d3ec352c → 0.0.1-commit.d6f2b3f94

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