@aztec/sequencer-client 4.0.0-nightly.20250907 → 4.0.0-nightly.20260108

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