@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
@@ -0,0 +1,1070 @@
1
+ function _ts_add_disposable_resource(env, value, async) {
2
+ if (value !== null && value !== void 0) {
3
+ if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
+ var dispose, inner;
5
+ if (async) {
6
+ if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
+ dispose = value[Symbol.asyncDispose];
8
+ }
9
+ if (dispose === void 0) {
10
+ if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
+ dispose = value[Symbol.dispose];
12
+ if (async) inner = dispose;
13
+ }
14
+ if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
+ if (inner) dispose = function() {
16
+ try {
17
+ inner.call(this);
18
+ } catch (e) {
19
+ return Promise.reject(e);
20
+ }
21
+ };
22
+ env.stack.push({
23
+ value: value,
24
+ dispose: dispose,
25
+ async: async
26
+ });
27
+ } else if (async) {
28
+ env.stack.push({
29
+ async: true
30
+ });
31
+ }
32
+ return value;
33
+ }
34
+ function _ts_dispose_resources(env) {
35
+ var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
36
+ var e = new Error(message);
37
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
38
+ };
39
+ return (_ts_dispose_resources = function _ts_dispose_resources(env) {
40
+ function fail(e) {
41
+ env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
42
+ env.hasError = true;
43
+ }
44
+ var r, s = 0;
45
+ function next() {
46
+ while(r = env.stack.pop()){
47
+ try {
48
+ if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
49
+ if (r.dispose) {
50
+ var result = r.dispose.call(r.value);
51
+ if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
52
+ fail(e);
53
+ return next();
54
+ });
55
+ } else s |= 1;
56
+ } catch (e) {
57
+ fail(e);
58
+ }
59
+ }
60
+ if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
61
+ if (env.hasError) throw env.error;
62
+ }
63
+ return next();
64
+ })(env);
65
+ }
66
+ function applyDecs2203RFactory() {
67
+ function createAddInitializerMethod(initializers, decoratorFinishedRef) {
68
+ return function addInitializer(initializer) {
69
+ assertNotFinished(decoratorFinishedRef, "addInitializer");
70
+ assertCallable(initializer, "An initializer");
71
+ initializers.push(initializer);
72
+ };
73
+ }
74
+ function memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value) {
75
+ var kindStr;
76
+ switch(kind){
77
+ case 1:
78
+ kindStr = "accessor";
79
+ break;
80
+ case 2:
81
+ kindStr = "method";
82
+ break;
83
+ case 3:
84
+ kindStr = "getter";
85
+ break;
86
+ case 4:
87
+ kindStr = "setter";
88
+ break;
89
+ default:
90
+ kindStr = "field";
91
+ }
92
+ var ctx = {
93
+ kind: kindStr,
94
+ name: isPrivate ? "#" + name : name,
95
+ static: isStatic,
96
+ private: isPrivate,
97
+ metadata: metadata
98
+ };
99
+ var decoratorFinishedRef = {
100
+ v: false
101
+ };
102
+ ctx.addInitializer = createAddInitializerMethod(initializers, decoratorFinishedRef);
103
+ var get, set;
104
+ if (kind === 0) {
105
+ if (isPrivate) {
106
+ get = desc.get;
107
+ set = desc.set;
108
+ } else {
109
+ get = function() {
110
+ return this[name];
111
+ };
112
+ set = function(v) {
113
+ this[name] = v;
114
+ };
115
+ }
116
+ } else if (kind === 2) {
117
+ get = function() {
118
+ return desc.value;
119
+ };
120
+ } else {
121
+ if (kind === 1 || kind === 3) {
122
+ get = function() {
123
+ return desc.get.call(this);
124
+ };
125
+ }
126
+ if (kind === 1 || kind === 4) {
127
+ set = function(v) {
128
+ desc.set.call(this, v);
129
+ };
130
+ }
131
+ }
132
+ ctx.access = get && set ? {
133
+ get: get,
134
+ set: set
135
+ } : get ? {
136
+ get: get
137
+ } : {
138
+ set: set
139
+ };
140
+ try {
141
+ return dec(value, ctx);
142
+ } finally{
143
+ decoratorFinishedRef.v = true;
144
+ }
145
+ }
146
+ function assertNotFinished(decoratorFinishedRef, fnName) {
147
+ if (decoratorFinishedRef.v) {
148
+ throw new Error("attempted to call " + fnName + " after decoration was finished");
149
+ }
150
+ }
151
+ function assertCallable(fn, hint) {
152
+ if (typeof fn !== "function") {
153
+ throw new TypeError(hint + " must be a function");
154
+ }
155
+ }
156
+ function assertValidReturnValue(kind, value) {
157
+ var type = typeof value;
158
+ if (kind === 1) {
159
+ if (type !== "object" || value === null) {
160
+ throw new TypeError("accessor decorators must return an object with get, set, or init properties or void 0");
161
+ }
162
+ if (value.get !== undefined) {
163
+ assertCallable(value.get, "accessor.get");
164
+ }
165
+ if (value.set !== undefined) {
166
+ assertCallable(value.set, "accessor.set");
167
+ }
168
+ if (value.init !== undefined) {
169
+ assertCallable(value.init, "accessor.init");
170
+ }
171
+ } else if (type !== "function") {
172
+ var hint;
173
+ if (kind === 0) {
174
+ hint = "field";
175
+ } else if (kind === 10) {
176
+ hint = "class";
177
+ } else {
178
+ hint = "method";
179
+ }
180
+ throw new TypeError(hint + " decorators must return a function or void 0");
181
+ }
182
+ }
183
+ function applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata) {
184
+ var decs = decInfo[0];
185
+ var desc, init, value;
186
+ if (isPrivate) {
187
+ if (kind === 0 || kind === 1) {
188
+ desc = {
189
+ get: decInfo[3],
190
+ set: decInfo[4]
191
+ };
192
+ } else if (kind === 3) {
193
+ desc = {
194
+ get: decInfo[3]
195
+ };
196
+ } else if (kind === 4) {
197
+ desc = {
198
+ set: decInfo[3]
199
+ };
200
+ } else {
201
+ desc = {
202
+ value: decInfo[3]
203
+ };
204
+ }
205
+ } else if (kind !== 0) {
206
+ desc = Object.getOwnPropertyDescriptor(base, name);
207
+ }
208
+ if (kind === 1) {
209
+ value = {
210
+ get: desc.get,
211
+ set: desc.set
212
+ };
213
+ } else if (kind === 2) {
214
+ value = desc.value;
215
+ } else if (kind === 3) {
216
+ value = desc.get;
217
+ } else if (kind === 4) {
218
+ value = desc.set;
219
+ }
220
+ var newValue, get, set;
221
+ if (typeof decs === "function") {
222
+ newValue = memberDec(decs, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
223
+ if (newValue !== void 0) {
224
+ assertValidReturnValue(kind, newValue);
225
+ if (kind === 0) {
226
+ init = newValue;
227
+ } else if (kind === 1) {
228
+ init = newValue.init;
229
+ get = newValue.get || value.get;
230
+ set = newValue.set || value.set;
231
+ value = {
232
+ get: get,
233
+ set: set
234
+ };
235
+ } else {
236
+ value = newValue;
237
+ }
238
+ }
239
+ } else {
240
+ for(var i = decs.length - 1; i >= 0; i--){
241
+ var dec = decs[i];
242
+ newValue = memberDec(dec, name, desc, initializers, kind, isStatic, isPrivate, metadata, value);
243
+ if (newValue !== void 0) {
244
+ assertValidReturnValue(kind, newValue);
245
+ var newInit;
246
+ if (kind === 0) {
247
+ newInit = newValue;
248
+ } else if (kind === 1) {
249
+ newInit = newValue.init;
250
+ get = newValue.get || value.get;
251
+ set = newValue.set || value.set;
252
+ value = {
253
+ get: get,
254
+ set: set
255
+ };
256
+ } else {
257
+ value = newValue;
258
+ }
259
+ if (newInit !== void 0) {
260
+ if (init === void 0) {
261
+ init = newInit;
262
+ } else if (typeof init === "function") {
263
+ init = [
264
+ init,
265
+ newInit
266
+ ];
267
+ } else {
268
+ init.push(newInit);
269
+ }
270
+ }
271
+ }
272
+ }
273
+ }
274
+ if (kind === 0 || kind === 1) {
275
+ if (init === void 0) {
276
+ init = function(instance, init) {
277
+ return init;
278
+ };
279
+ } else if (typeof init !== "function") {
280
+ var ownInitializers = init;
281
+ init = function(instance, init) {
282
+ var value = init;
283
+ for(var i = 0; i < ownInitializers.length; i++){
284
+ value = ownInitializers[i].call(instance, value);
285
+ }
286
+ return value;
287
+ };
288
+ } else {
289
+ var originalInitializer = init;
290
+ init = function(instance, init) {
291
+ return originalInitializer.call(instance, init);
292
+ };
293
+ }
294
+ ret.push(init);
295
+ }
296
+ if (kind !== 0) {
297
+ if (kind === 1) {
298
+ desc.get = value.get;
299
+ desc.set = value.set;
300
+ } else if (kind === 2) {
301
+ desc.value = value;
302
+ } else if (kind === 3) {
303
+ desc.get = value;
304
+ } else if (kind === 4) {
305
+ desc.set = value;
306
+ }
307
+ if (isPrivate) {
308
+ if (kind === 1) {
309
+ ret.push(function(instance, args) {
310
+ return value.get.call(instance, args);
311
+ });
312
+ ret.push(function(instance, args) {
313
+ return value.set.call(instance, args);
314
+ });
315
+ } else if (kind === 2) {
316
+ ret.push(value);
317
+ } else {
318
+ ret.push(function(instance, args) {
319
+ return value.call(instance, args);
320
+ });
321
+ }
322
+ } else {
323
+ Object.defineProperty(base, name, desc);
324
+ }
325
+ }
326
+ }
327
+ function applyMemberDecs(Class, decInfos, metadata) {
328
+ var ret = [];
329
+ var protoInitializers;
330
+ var staticInitializers;
331
+ var existingProtoNonFields = new Map();
332
+ var existingStaticNonFields = new Map();
333
+ for(var i = 0; i < decInfos.length; i++){
334
+ var decInfo = decInfos[i];
335
+ if (!Array.isArray(decInfo)) continue;
336
+ var kind = decInfo[1];
337
+ var name = decInfo[2];
338
+ var isPrivate = decInfo.length > 3;
339
+ var isStatic = kind >= 5;
340
+ var base;
341
+ var initializers;
342
+ if (isStatic) {
343
+ base = Class;
344
+ kind = kind - 5;
345
+ staticInitializers = staticInitializers || [];
346
+ initializers = staticInitializers;
347
+ } else {
348
+ base = Class.prototype;
349
+ protoInitializers = protoInitializers || [];
350
+ initializers = protoInitializers;
351
+ }
352
+ if (kind !== 0 && !isPrivate) {
353
+ var existingNonFields = isStatic ? existingStaticNonFields : existingProtoNonFields;
354
+ var existingKind = existingNonFields.get(name) || 0;
355
+ if (existingKind === true || existingKind === 3 && kind !== 4 || existingKind === 4 && kind !== 3) {
356
+ throw new Error("Attempted to decorate a public method/accessor that has the same name as a previously decorated public method/accessor. This is not currently supported by the decorators plugin. Property name was: " + name);
357
+ } else if (!existingKind && kind > 2) {
358
+ existingNonFields.set(name, kind);
359
+ } else {
360
+ existingNonFields.set(name, true);
361
+ }
362
+ }
363
+ applyMemberDec(ret, base, decInfo, name, kind, isStatic, isPrivate, initializers, metadata);
364
+ }
365
+ pushInitializers(ret, protoInitializers);
366
+ pushInitializers(ret, staticInitializers);
367
+ return ret;
368
+ }
369
+ function pushInitializers(ret, initializers) {
370
+ if (initializers) {
371
+ ret.push(function(instance) {
372
+ for(var i = 0; i < initializers.length; i++){
373
+ initializers[i].call(instance);
374
+ }
375
+ return instance;
376
+ });
377
+ }
378
+ }
379
+ function applyClassDecs(targetClass, classDecs, metadata) {
380
+ if (classDecs.length > 0) {
381
+ var initializers = [];
382
+ var newClass = targetClass;
383
+ var name = targetClass.name;
384
+ for(var i = classDecs.length - 1; i >= 0; i--){
385
+ var decoratorFinishedRef = {
386
+ v: false
387
+ };
388
+ try {
389
+ var nextNewClass = classDecs[i](newClass, {
390
+ kind: "class",
391
+ name: name,
392
+ addInitializer: createAddInitializerMethod(initializers, decoratorFinishedRef),
393
+ metadata
394
+ });
395
+ } finally{
396
+ decoratorFinishedRef.v = true;
397
+ }
398
+ if (nextNewClass !== undefined) {
399
+ assertValidReturnValue(10, nextNewClass);
400
+ newClass = nextNewClass;
401
+ }
402
+ }
403
+ return [
404
+ defineMetadata(newClass, metadata),
405
+ function() {
406
+ for(var i = 0; i < initializers.length; i++){
407
+ initializers[i].call(newClass);
408
+ }
409
+ }
410
+ ];
411
+ }
412
+ }
413
+ function defineMetadata(Class, metadata) {
414
+ return Object.defineProperty(Class, Symbol.metadata || Symbol.for("Symbol.metadata"), {
415
+ configurable: true,
416
+ enumerable: true,
417
+ value: metadata
418
+ });
419
+ }
420
+ return function applyDecs2203R(targetClass, memberDecs, classDecs, parentClass) {
421
+ if (parentClass !== void 0) {
422
+ var parentMetadata = parentClass[Symbol.metadata || Symbol.for("Symbol.metadata")];
423
+ }
424
+ var metadata = Object.create(parentMetadata === void 0 ? null : parentMetadata);
425
+ var e = applyMemberDecs(targetClass, memberDecs, metadata);
426
+ if (!classDecs.length) defineMetadata(targetClass, metadata);
427
+ return {
428
+ e: e,
429
+ get c () {
430
+ return applyClassDecs(targetClass, classDecs, metadata);
431
+ }
432
+ };
433
+ };
434
+ }
435
+ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
436
+ return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
437
+ }
438
+ var _dec, _dec1, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _initProto;
439
+ import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB } from '@aztec/constants';
440
+ import { BlockNumber } from '@aztec/foundation/branded-types';
441
+ import { randomInt } from '@aztec/foundation/crypto/random';
442
+ import { Signature } from '@aztec/foundation/eth-signature';
443
+ import { filter } from '@aztec/foundation/iterator';
444
+ import { sleep, sleepUntil } from '@aztec/foundation/sleep';
445
+ import { Timer } from '@aztec/foundation/timer';
446
+ import { unfreeze } from '@aztec/foundation/types';
447
+ import { CommitteeAttestationsAndSigners, MaliciousCommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
448
+ import { getSlotStartBuildTimestamp } from '@aztec/stdlib/epoch-helpers';
449
+ import { Gas } from '@aztec/stdlib/gas';
450
+ import { orderAttestations } from '@aztec/stdlib/p2p';
451
+ import { AttestationTimeoutError } from '@aztec/stdlib/validators';
452
+ import { Attributes, trackSpan } from '@aztec/telemetry-client';
453
+ import { CheckpointVoter } from './checkpoint_voter.js';
454
+ import { SequencerInterruptedError } from './errors.js';
455
+ import { SequencerState } from './utils.js';
456
+ /** How much time to sleep while waiting for min transactions to accumulate for a block */ const TXS_POLLING_MS = 500;
457
+ _dec = trackSpan('CheckpointProposalJob.execute'), _dec1 = trackSpan('CheckpointProposalJob.proposeCheckpoint', function() {
458
+ return {
459
+ // nullish operator needed for tests
460
+ [Attributes.COINBASE]: this.validatorClient.getCoinbaseForAttestor(this.attestorAddress)?.toString(),
461
+ [Attributes.SLOT_NUMBER]: this.slot
462
+ };
463
+ }), _dec2 = trackSpan('CheckpointProposalJob.buildBlocksForCheckpoint'), _dec3 = trackSpan('CheckpointProposalJob.waitUntilNextSubslot'), _dec4 = trackSpan('CheckpointProposalJob.buildSingleBlock'), _dec5 = trackSpan('CheckpointProposalJob.waitForMinTxs'), _dec6 = trackSpan('CheckpointProposalJob.waitForAttestations'), _dec7 = trackSpan('CheckpointProposalJob.waitUntilTimeInSlot');
464
+ /**
465
+ * Handles the execution of a checkpoint proposal after the initial preparation phase.
466
+ * This includes building blocks, collecting attestations, and publishing the checkpoint to L1,
467
+ * as well as enqueueing votes for slashing and governance proposals. This class is created from
468
+ * the Sequencer once the check for being the proposer for the slot has succeeded.
469
+ */ export class CheckpointProposalJob {
470
+ slot;
471
+ checkpointNumber;
472
+ syncedToBlockNumber;
473
+ proposer;
474
+ publisher;
475
+ attestorAddress;
476
+ invalidateBlock;
477
+ validatorClient;
478
+ globalsBuilder;
479
+ p2pClient;
480
+ worldState;
481
+ l1ToL2MessageSource;
482
+ checkpointsBuilder;
483
+ l1Constants;
484
+ config;
485
+ timetable;
486
+ slasherClient;
487
+ epochCache;
488
+ dateProvider;
489
+ metrics;
490
+ eventEmitter;
491
+ setStateFn;
492
+ log;
493
+ tracer;
494
+ static{
495
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
496
+ [
497
+ _dec,
498
+ 2,
499
+ "execute"
500
+ ],
501
+ [
502
+ _dec1,
503
+ 2,
504
+ "proposeCheckpoint"
505
+ ],
506
+ [
507
+ _dec2,
508
+ 2,
509
+ "buildBlocksForCheckpoint"
510
+ ],
511
+ [
512
+ _dec3,
513
+ 2,
514
+ "waitUntilNextSubslot"
515
+ ],
516
+ [
517
+ _dec4,
518
+ 2,
519
+ "buildSingleBlock"
520
+ ],
521
+ [
522
+ _dec5,
523
+ 2,
524
+ "waitForMinTxs"
525
+ ],
526
+ [
527
+ _dec6,
528
+ 2,
529
+ "waitForAttestations"
530
+ ],
531
+ [
532
+ _dec7,
533
+ 2,
534
+ "waitUntilTimeInSlot"
535
+ ]
536
+ ], []));
537
+ }
538
+ constructor(slot, checkpointNumber, syncedToBlockNumber, // TODO(palla/mbps): Can we remove the proposer in favor of attestorAddress? Need to check fisherman-node flows.
539
+ proposer, publisher, attestorAddress, invalidateBlock, validatorClient, globalsBuilder, p2pClient, worldState, l1ToL2MessageSource, checkpointsBuilder, l1Constants, config, timetable, slasherClient, epochCache, dateProvider, metrics, eventEmitter, setStateFn, log, tracer){
540
+ this.slot = slot;
541
+ this.checkpointNumber = checkpointNumber;
542
+ this.syncedToBlockNumber = syncedToBlockNumber;
543
+ this.proposer = proposer;
544
+ this.publisher = publisher;
545
+ this.attestorAddress = attestorAddress;
546
+ this.invalidateBlock = invalidateBlock;
547
+ this.validatorClient = validatorClient;
548
+ this.globalsBuilder = globalsBuilder;
549
+ this.p2pClient = p2pClient;
550
+ this.worldState = worldState;
551
+ this.l1ToL2MessageSource = l1ToL2MessageSource;
552
+ this.checkpointsBuilder = checkpointsBuilder;
553
+ this.l1Constants = l1Constants;
554
+ this.config = config;
555
+ this.timetable = timetable;
556
+ this.slasherClient = slasherClient;
557
+ this.epochCache = epochCache;
558
+ this.dateProvider = dateProvider;
559
+ this.metrics = metrics;
560
+ this.eventEmitter = eventEmitter;
561
+ this.setStateFn = setStateFn;
562
+ this.log = log;
563
+ this.tracer = tracer;
564
+ _initProto(this);
565
+ }
566
+ /**
567
+ * Executes the checkpoint proposal job.
568
+ * Returns the published checkpoint if successful, undefined otherwise.
569
+ */ async execute() {
570
+ // Enqueue governance and slashing votes (returns promises that will be awaited later)
571
+ // In fisherman mode, we simulate slashing but don't actually publish to L1
572
+ // These are constant for the whole slot, so we only enqueue them once
573
+ const votesPromises = new CheckpointVoter(this.slot, this.publisher, this.attestorAddress, this.validatorClient, this.slasherClient, this.l1Constants, this.config, this.metrics, this.log).enqueueVotes();
574
+ // Build and propose the checkpoint. This will enqueue the request on the publisher if a checkpoint is built.
575
+ const checkpoint = await this.proposeCheckpoint();
576
+ // Wait until the voting promises have resolved, so all requests are enqueued (not sent)
577
+ await Promise.all(votesPromises);
578
+ if (checkpoint) {
579
+ this.metrics.recordBlockProposalSuccess();
580
+ }
581
+ // Do not post anything to L1 if we are fishermen, but do perform L1 fee analysis
582
+ if (this.config.fishermanMode) {
583
+ await this.handleCheckpointEndAsFisherman(checkpoint);
584
+ return;
585
+ }
586
+ // Then send everything to L1
587
+ const l1Response = await this.publisher.sendRequests();
588
+ const proposedAction = l1Response?.successfulActions.find((a)=>a === 'propose');
589
+ if (proposedAction) {
590
+ this.eventEmitter.emit('checkpoint-published', {
591
+ checkpoint: this.checkpointNumber,
592
+ slot: this.slot
593
+ });
594
+ const coinbase = checkpoint?.header.coinbase;
595
+ await this.metrics.incFilledSlot(this.publisher.getSenderAddress().toString(), coinbase);
596
+ return checkpoint;
597
+ } else if (checkpoint) {
598
+ this.eventEmitter.emit('checkpoint-publish-failed', {
599
+ ...l1Response,
600
+ slot: this.slot
601
+ });
602
+ return undefined;
603
+ }
604
+ }
605
+ async proposeCheckpoint() {
606
+ try {
607
+ const env = {
608
+ stack: [],
609
+ error: void 0,
610
+ hasError: false
611
+ };
612
+ try {
613
+ // Get operator configured coinbase and fee recipient for this attestor
614
+ const coinbase = this.validatorClient.getCoinbaseForAttestor(this.attestorAddress);
615
+ const feeRecipient = this.validatorClient.getFeeRecipientForAttestor(this.attestorAddress);
616
+ // Start the checkpoint
617
+ this.setStateFn(SequencerState.INITIALIZING_CHECKPOINT, this.slot);
618
+ this.metrics.incOpenSlot(this.slot, this.proposer?.toString() ?? 'unknown');
619
+ // Enqueues block invalidation (constant for the whole slot)
620
+ if (this.invalidateBlock && !this.config.skipInvalidateBlockAsProposer) {
621
+ this.publisher.enqueueInvalidateBlock(this.invalidateBlock);
622
+ }
623
+ // Create checkpoint builder for the slot
624
+ const checkpointGlobalVariables = await this.globalsBuilder.buildCheckpointGlobalVariables(coinbase, feeRecipient, this.slot);
625
+ // Collect L1 to L2 messages for the checkpoint
626
+ const l1ToL2Messages = await this.l1ToL2MessageSource.getL1ToL2Messages(this.checkpointNumber);
627
+ const fork = _ts_add_disposable_resource(env, await this.worldState.fork(this.syncedToBlockNumber, {
628
+ closeDelayMs: 12_000
629
+ }), false);
630
+ // Create checkpoint builder for the entire slot
631
+ const checkpointBuilder = await this.checkpointsBuilder.startCheckpoint(this.checkpointNumber, checkpointGlobalVariables, l1ToL2Messages, fork);
632
+ // Options for the validator client when creating block and checkpoint proposals
633
+ const blockProposalOptions = {
634
+ publishFullTxs: !!this.config.publishTxsWithProposals,
635
+ broadcastInvalidBlockProposal: this.config.broadcastInvalidBlockProposal
636
+ };
637
+ // Main loop: build blocks for the checkpoint
638
+ const { blocksInCheckpoint, pendingBroadcast } = await this.buildBlocksForCheckpoint(checkpointBuilder, checkpointGlobalVariables.timestamp, blockProposalOptions);
639
+ if (blocksInCheckpoint.length === 0) {
640
+ this.log.warn(`No blocks were built for slot ${this.slot}`, {
641
+ slot: this.slot
642
+ });
643
+ this.eventEmitter.emit('checkpoint-empty', {
644
+ slot: this.slot
645
+ });
646
+ return undefined;
647
+ }
648
+ // Assemble and broadcast the checkpoint proposal, including the last block that was not
649
+ // broadcasted yet, and wait to collect the committee attestations.
650
+ this.setStateFn(SequencerState.ASSEMBLING_CHECKPOINT, this.slot);
651
+ const checkpoint = await checkpointBuilder.completeCheckpoint();
652
+ // Do not collect attestations nor publish to L1 in fisherman mode
653
+ if (this.config.fishermanMode) {
654
+ this.log.info(`Built checkpoint for slot ${this.slot} with ${blocksInCheckpoint.length} blocks. ` + `Skipping proposal in fisherman mode.`, {
655
+ slot: this.slot,
656
+ checkpoint: checkpoint.header.toInspect(),
657
+ blocksBuilt: blocksInCheckpoint.length
658
+ });
659
+ this.metrics.recordCheckpointSuccess();
660
+ return checkpoint;
661
+ }
662
+ // TODO(palla/mbps): Wire this to the new p2p API once available, including the pendingBroadcast.block
663
+ const proposal = await this.validatorClient.createCheckpointProposal(checkpoint.header, checkpoint.archive.root, pendingBroadcast?.txs ?? [], this.proposer, blockProposalOptions);
664
+ const blockProposedAt = this.dateProvider.now();
665
+ await this.p2pClient.broadcastProposal(proposal);
666
+ this.setStateFn(SequencerState.COLLECTING_ATTESTATIONS, this.slot);
667
+ const attestations = await this.waitForAttestations(proposal);
668
+ const blockAttestedAt = this.dateProvider.now();
669
+ this.metrics.recordBlockAttestationDelay(blockAttestedAt - blockProposedAt);
670
+ // Proposer must sign over the attestations before pushing them to L1
671
+ const signer = this.proposer ?? this.publisher.getSenderAddress();
672
+ const attestationsSignature = await this.validatorClient.signAttestationsAndSigners(attestations, signer);
673
+ // Enqueue publishing the checkpoint to L1
674
+ this.setStateFn(SequencerState.PUBLISHING_CHECKPOINT, this.slot);
675
+ const aztecSlotDuration = this.l1Constants.slotDuration;
676
+ const slotStartBuildTimestamp = this.getSlotStartBuildTimestamp();
677
+ const txTimeoutAt = new Date((slotStartBuildTimestamp + aztecSlotDuration) * 1000);
678
+ await this.publisher.enqueueProposeCheckpoint(checkpoint, attestations, attestationsSignature, {
679
+ txTimeoutAt,
680
+ forcePendingBlockNumber: this.invalidateBlock?.forcePendingBlockNumber
681
+ });
682
+ return checkpoint;
683
+ } catch (e) {
684
+ env.error = e;
685
+ env.hasError = true;
686
+ } finally{
687
+ _ts_dispose_resources(env);
688
+ }
689
+ } catch (err) {
690
+ this.log.error(`Error building checkpoint at slot ${this.slot}`, err);
691
+ return undefined;
692
+ }
693
+ }
694
+ /**
695
+ * Builds blocks for a checkpoint within the current slot.
696
+ */ async buildBlocksForCheckpoint(checkpointBuilder, timestamp, blockProposalOptions) {
697
+ const blocksInCheckpoint = [];
698
+ const txHashesAlreadyIncluded = new Set();
699
+ const initialBlockNumber = BlockNumber(this.syncedToBlockNumber + 1);
700
+ // Last block in the checkpoint will usually be flagged as pending broadcast, so we send it along with the checkpoint proposal
701
+ let pendingBroadcast = undefined;
702
+ while(true){
703
+ const blocksBuilt = blocksInCheckpoint.length;
704
+ const indexWithinCheckpoint = blocksBuilt;
705
+ const blockNumber = BlockNumber(initialBlockNumber + blocksBuilt);
706
+ const secondsIntoSlot = this.getSecondsIntoSlot();
707
+ const timingInfo = this.timetable.canStartNextBlock(secondsIntoSlot);
708
+ if (!timingInfo.canStart) {
709
+ this.log.debug(`Not enough time left in slot to start another block`, {
710
+ slot: this.slot,
711
+ blocksBuilt,
712
+ secondsIntoSlot
713
+ });
714
+ break;
715
+ }
716
+ const buildResult = await this.buildSingleBlock(checkpointBuilder, {
717
+ // Create all blocks with the same timestamp
718
+ blockTimestamp: timestamp,
719
+ // Create an empty block if we haven't already and this is the last one
720
+ forceCreate: timingInfo.isLastBlock && blocksBuilt === 0 && this.config.buildCheckpointIfEmpty,
721
+ // Build deadline is only set if we are enforcing the timetable
722
+ buildDeadline: timingInfo.deadline ? new Date((this.getSlotStartBuildTimestamp() + timingInfo.deadline) * 1000) : undefined,
723
+ blockNumber,
724
+ indexWithinCheckpoint,
725
+ txHashesAlreadyIncluded
726
+ });
727
+ if (!buildResult && timingInfo.isLastBlock) {
728
+ break;
729
+ } else if (!buildResult && timingInfo.deadline !== undefined) {
730
+ // But if there is still time for more blocks, wait until the next subslot and try again
731
+ await this.waitUntilNextSubslot(timingInfo.deadline);
732
+ continue;
733
+ } else if (!buildResult) {
734
+ break;
735
+ } else if ('error' in buildResult) {
736
+ // If there was an error building the block, just exit the loop and give up the rest of the slot
737
+ if (!(buildResult.error instanceof SequencerInterruptedError)) {
738
+ this.log.warn(`Halting block building for slot ${this.slot}`, {
739
+ slot: this.slot,
740
+ blocksBuilt,
741
+ error: buildResult.error
742
+ });
743
+ }
744
+ break;
745
+ }
746
+ const { block, usedTxs } = buildResult;
747
+ blocksInCheckpoint.push(block);
748
+ // Sync the proposed block to the archiver to make it available
749
+ // Note that the checkpoint builder uses its own fork so it should not need to wait for this syncing
750
+ // Eventually we should refactor the checkpoint builder to not need a separate long-lived fork
751
+ await this.syncProposedBlockToArchiver(block);
752
+ // If this is the last block, exit the loop now so we start collecting attestations
753
+ if (timingInfo.isLastBlock) {
754
+ this.log.verbose(`Completed final block ${blockNumber} for slot ${this.slot}`, {
755
+ slot: this.slot,
756
+ blockNumber,
757
+ blocksBuilt
758
+ });
759
+ pendingBroadcast = {
760
+ block,
761
+ txs: usedTxs
762
+ };
763
+ break;
764
+ }
765
+ // For non-last blocks, broadcast the block proposal (unless we're in fisherman mode)
766
+ // If the block is the last one, we'll broadcast it along with the checkpoint at the end of the loop
767
+ if (!this.config.fishermanMode) {
768
+ // TODO(palla/mbps): Wire this to the new p2p API once available
769
+ const proposal = await this.validatorClient.createBlockProposal(block.header.globalVariables.blockNumber, (await checkpointBuilder.getCheckpoint()).header, block.archive.root, usedTxs, this.proposer, blockProposalOptions);
770
+ await this.p2pClient.broadcastProposal(proposal);
771
+ }
772
+ // Wait until the next block's start time
773
+ await this.waitUntilNextSubslot(timingInfo.deadline);
774
+ }
775
+ this.log.verbose(`Block building loop completed for slot ${this.slot}`, {
776
+ slot: this.slot,
777
+ blocksBuilt: blocksInCheckpoint.length
778
+ });
779
+ return {
780
+ blocksInCheckpoint,
781
+ pendingBroadcast
782
+ };
783
+ }
784
+ /** Sleeps until it is time to produce the next block in the slot */ async waitUntilNextSubslot(nextSubslotStart) {
785
+ this.setStateFn(SequencerState.WAITING_UNTIL_NEXT_BLOCK, this.slot);
786
+ this.log.verbose(`Waiting until time for the next block at ${nextSubslotStart}s into slot`, {
787
+ slot: this.slot
788
+ });
789
+ await this.waitUntilTimeInSlot(nextSubslotStart);
790
+ }
791
+ /** Builds a single block. Called from the main block building loop. */ async buildSingleBlock(checkpointBuilder, opts) {
792
+ const { blockTimestamp, forceCreate, blockNumber, indexWithinCheckpoint, buildDeadline, txHashesAlreadyIncluded } = opts;
793
+ this.log.verbose(`Preparing block ${blockNumber} index ${indexWithinCheckpoint} at checkpoint ${this.checkpointNumber} for slot ${this.slot}`, {
794
+ ...checkpointBuilder.getConstantData(),
795
+ ...opts
796
+ });
797
+ try {
798
+ // Wait until we have enough txs to build the block
799
+ const minTxs = this.config.minTxsPerBlock;
800
+ const { availableTxs, canStartBuilding } = await this.waitForMinTxs(opts);
801
+ if (!canStartBuilding) {
802
+ this.log.warn(`Not enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (got ${availableTxs} txs but needs ${minTxs})`, {
803
+ blockNumber,
804
+ slot: this.slot,
805
+ indexWithinCheckpoint
806
+ });
807
+ this.eventEmitter.emit('block-tx-count-check-failed', {
808
+ minTxs,
809
+ availableTxs,
810
+ slot: this.slot
811
+ });
812
+ this.metrics.recordBlockProposalFailed('insufficient_txs');
813
+ return undefined;
814
+ }
815
+ // Create iterator to pending txs. We filter out txs already included in previous blocks in the checkpoint
816
+ // just in case p2p failed to sync the provisional block and didn't get to remove those txs from the mempool yet.
817
+ const pendingTxs = filter(this.p2pClient.iteratePendingTxs(), (tx)=>!txHashesAlreadyIncluded.has(tx.txHash.toString()));
818
+ this.log.debug(`Building block ${blockNumber} at index ${indexWithinCheckpoint} for slot ${this.slot} with ${availableTxs} available txs`, {
819
+ slot: this.slot,
820
+ blockNumber,
821
+ indexWithinCheckpoint
822
+ });
823
+ this.setStateFn(SequencerState.CREATING_BLOCK, this.slot);
824
+ const blockBuilderOptions = {
825
+ maxTransactions: this.config.maxTxsPerBlock,
826
+ maxBlockSize: this.config.maxBlockSizeInBytes,
827
+ maxBlockGas: new Gas(this.config.maxDABlockGas, this.config.maxL2BlockGas),
828
+ maxBlobFields: BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB,
829
+ deadline: buildDeadline
830
+ };
831
+ // Actually build the block by executing txs
832
+ const workTimer = new Timer();
833
+ const { publicGas, block, publicProcessorDuration, numTxs, blockBuildingTimer, usedTxs, failedTxs } = await checkpointBuilder.buildBlock(pendingTxs, blockNumber, blockTimestamp, blockBuilderOptions);
834
+ const blockBuildDuration = workTimer.ms();
835
+ // If any txs failed during execution, drop them from the mempool so we don't pick them up again
836
+ await this.dropFailedTxsFromP2P(failedTxs);
837
+ // Check if we have created a block with enough txs. If there were invalid txs in the pool, or if execution took
838
+ // too long, then we may not get to minTxsPerBlock after executing public functions.
839
+ const minValidTxs = this.config.minValidTxsPerBlock ?? minTxs;
840
+ if (!forceCreate && numTxs < minValidTxs) {
841
+ this.log.warn(`Block ${blockNumber} at index ${indexWithinCheckpoint} on slot ${this.slot} has too few valid txs to be proposed (got ${numTxs} but required ${minValidTxs})`, {
842
+ slot: this.slot,
843
+ blockNumber,
844
+ numTxs,
845
+ indexWithinCheckpoint
846
+ });
847
+ this.eventEmitter.emit('block-tx-count-check-failed', {
848
+ minTxs: minValidTxs,
849
+ availableTxs: numTxs,
850
+ slot: this.slot
851
+ });
852
+ this.metrics.recordBlockProposalFailed('insufficient_valid_txs');
853
+ return undefined;
854
+ }
855
+ // Block creation succeeded, emit stats and metrics
856
+ const blockStats = {
857
+ eventName: 'l2-block-built',
858
+ duration: blockBuildDuration,
859
+ publicProcessDuration: publicProcessorDuration,
860
+ rollupCircuitsDuration: blockBuildingTimer.ms(),
861
+ ...block.getStats()
862
+ };
863
+ const blockHash = await block.hash();
864
+ const txHashes = block.body.txEffects.map((tx)=>tx.txHash);
865
+ const manaPerSec = publicGas.l2Gas / (blockBuildDuration / 1000);
866
+ this.log.info(`Built block ${block.number} at checkpoint ${this.checkpointNumber} for slot ${this.slot} with ${numTxs} txs`, {
867
+ blockHash,
868
+ txHashes,
869
+ manaPerSec,
870
+ ...blockStats
871
+ });
872
+ this.eventEmitter.emit('block-proposed', {
873
+ blockNumber: block.number,
874
+ slot: this.slot
875
+ });
876
+ this.metrics.recordBuiltBlock(blockBuildDuration, publicGas.l2Gas);
877
+ return {
878
+ block,
879
+ usedTxs
880
+ };
881
+ } catch (err) {
882
+ this.eventEmitter.emit('block-build-failed', {
883
+ reason: err.message,
884
+ slot: this.slot
885
+ });
886
+ this.log.error(`Error building block`, err, {
887
+ blockNumber,
888
+ slot: this.slot
889
+ });
890
+ this.metrics.recordBlockProposalFailed(err.name || 'unknown_error');
891
+ this.metrics.recordFailedBlock();
892
+ return {
893
+ error: err
894
+ };
895
+ }
896
+ }
897
+ /** Waits until minTxs are available on the pool for building a block. */ async waitForMinTxs(opts) {
898
+ const minTxs = this.config.minTxsPerBlock;
899
+ const { indexWithinCheckpoint, blockNumber, buildDeadline, forceCreate } = opts;
900
+ // Deadline is undefined if we are not enforcing the timetable, meaning we'll exit immediately when out of time
901
+ const startBuildingDeadline = buildDeadline ? new Date(buildDeadline.getTime() - this.timetable.minExecutionTime * 1000) : undefined;
902
+ let availableTxs = await this.p2pClient.getPendingTxCount();
903
+ while(!forceCreate && availableTxs < minTxs){
904
+ // If we're past deadline, or we have no deadline, give up
905
+ const now = this.dateProvider.nowAsDate();
906
+ if (startBuildingDeadline === undefined || now >= startBuildingDeadline) {
907
+ return {
908
+ canStartBuilding: false,
909
+ availableTxs: availableTxs
910
+ };
911
+ }
912
+ // Wait a bit before checking again
913
+ this.setStateFn(SequencerState.WAITING_FOR_TXS, this.slot);
914
+ this.log.verbose(`Waiting for enough txs to build block ${blockNumber} at index ${indexWithinCheckpoint} in slot ${this.slot} (have ${availableTxs} but need ${minTxs})`, {
915
+ blockNumber,
916
+ slot: this.slot,
917
+ indexWithinCheckpoint
918
+ });
919
+ await sleep(TXS_POLLING_MS);
920
+ availableTxs = await this.p2pClient.getPendingTxCount();
921
+ }
922
+ return {
923
+ canStartBuilding: true,
924
+ availableTxs
925
+ };
926
+ }
927
+ /**
928
+ * Waits for enough attestations to be collected via p2p.
929
+ * This is run after all blocks for the checkpoint have been built.
930
+ */ async waitForAttestations(proposal) {
931
+ if (this.config.fishermanMode) {
932
+ this.log.debug('Skipping attestation collection in fisherman mode');
933
+ return CommitteeAttestationsAndSigners.empty();
934
+ }
935
+ const slotNumber = proposal.slotNumber;
936
+ const { committee, seed, epoch } = await this.epochCache.getCommittee(slotNumber);
937
+ if (!committee) {
938
+ throw new Error('No committee when collecting attestations');
939
+ } else if (committee.length === 0) {
940
+ this.log.verbose(`Attesting committee is empty`);
941
+ return CommitteeAttestationsAndSigners.empty();
942
+ } else {
943
+ this.log.debug(`Attesting committee length is ${committee.length}`, {
944
+ committee
945
+ });
946
+ }
947
+ const numberOfRequiredAttestations = Math.floor(committee.length * 2 / 3) + 1;
948
+ if (this.config.skipCollectingAttestations) {
949
+ this.log.warn('Skipping attestation collection as per config (attesting with own keys only)');
950
+ const attestations = await this.validatorClient?.collectOwnAttestations(proposal);
951
+ return new CommitteeAttestationsAndSigners(orderAttestations(attestations ?? [], committee));
952
+ }
953
+ const attestationTimeAllowed = this.config.enforceTimeTable ? this.timetable.getMaxAllowedTime(SequencerState.PUBLISHING_CHECKPOINT) : this.l1Constants.slotDuration;
954
+ const attestationDeadline = new Date(this.dateProvider.now() + attestationTimeAllowed * 1000);
955
+ this.metrics.recordRequiredAttestations(numberOfRequiredAttestations, attestationTimeAllowed);
956
+ const collectAttestationsTimer = new Timer();
957
+ let collectedAttestationsCount = 0;
958
+ try {
959
+ const attestations = await this.validatorClient.collectAttestations(proposal, numberOfRequiredAttestations, attestationDeadline);
960
+ collectedAttestationsCount = attestations.length;
961
+ // Rollup contract requires that the signatures are provided in the order of the committee
962
+ const sorted = orderAttestations(attestations, committee);
963
+ // Manipulate the attestations if we've been configured to do so
964
+ if (this.config.injectFakeAttestation || this.config.shuffleAttestationOrdering) {
965
+ const checkpoint = proposal.payload.header;
966
+ return this.manipulateAttestations(checkpoint, epoch, seed, committee, sorted);
967
+ }
968
+ return new CommitteeAttestationsAndSigners(sorted);
969
+ } catch (err) {
970
+ if (err && err instanceof AttestationTimeoutError) {
971
+ collectedAttestationsCount = err.collectedCount;
972
+ }
973
+ throw err;
974
+ } finally{
975
+ this.metrics.recordCollectedAttestations(collectedAttestationsCount, collectAttestationsTimer.ms());
976
+ }
977
+ }
978
+ /** Breaks the attestations before publishing based on attack configs */ manipulateAttestations(checkpoint, epoch, seed, committee, attestations) {
979
+ // Compute the proposer index in the committee, since we dont want to tweak it.
980
+ // Otherwise, the L1 rollup contract will reject the block outright.
981
+ const { slotNumber } = checkpoint;
982
+ const proposerIndex = Number(this.epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)));
983
+ if (this.config.injectFakeAttestation) {
984
+ // Find non-empty attestations that are not from the proposer
985
+ const nonProposerIndices = [];
986
+ for(let i = 0; i < attestations.length; i++){
987
+ if (!attestations[i].signature.isEmpty() && i !== proposerIndex) {
988
+ nonProposerIndices.push(i);
989
+ }
990
+ }
991
+ if (nonProposerIndices.length > 0) {
992
+ const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
993
+ this.log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
994
+ unfreeze(attestations[targetIndex]).signature = Signature.random();
995
+ }
996
+ return new CommitteeAttestationsAndSigners(attestations);
997
+ }
998
+ if (this.config.shuffleAttestationOrdering) {
999
+ this.log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
1000
+ const shuffled = [
1001
+ ...attestations
1002
+ ];
1003
+ const [i, j] = [
1004
+ (proposerIndex + 1) % shuffled.length,
1005
+ (proposerIndex + 2) % shuffled.length
1006
+ ];
1007
+ const valueI = shuffled[i];
1008
+ const valueJ = shuffled[j];
1009
+ shuffled[i] = valueJ;
1010
+ shuffled[j] = valueI;
1011
+ const signers = new CommitteeAttestationsAndSigners(attestations).getSigners();
1012
+ return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers);
1013
+ }
1014
+ return new CommitteeAttestationsAndSigners(attestations);
1015
+ }
1016
+ async dropFailedTxsFromP2P(failedTxs) {
1017
+ if (failedTxs.length === 0) {
1018
+ return;
1019
+ }
1020
+ const failedTxData = failedTxs.map((fail)=>fail.tx);
1021
+ const failedTxHashes = failedTxData.map((tx)=>tx.getTxHash());
1022
+ this.log.verbose(`Dropping failed txs ${failedTxHashes.join(', ')}`);
1023
+ await this.p2pClient.deleteTxs(failedTxHashes);
1024
+ }
1025
+ /**
1026
+ * Placeholder for pushing block to archiver and waiting for sync.
1027
+ * To be implemented when archiver and world-state support proposed blocks.
1028
+ */ async syncProposedBlockToArchiver(block) {
1029
+ this.log.debug(`Syncing proposed block ${block.number}`, {
1030
+ blockNumber: block.number,
1031
+ slot: block.header.globalVariables.slotNumber
1032
+ });
1033
+ // TODO(palla/mbps): Implement actual sync to archiver and world-state
1034
+ await Promise.resolve();
1035
+ }
1036
+ /** Runs fee analysis and logs checkpoint outcome as fisherman */ async handleCheckpointEndAsFisherman(checkpoint) {
1037
+ // Perform L1 fee analysis before clearing requests
1038
+ // The callback is invoked asynchronously after the next block is mined
1039
+ const feeAnalysis = await this.publisher.analyzeL1Fees(this.slot, (analysis)=>this.metrics.recordFishermanFeeAnalysis(analysis));
1040
+ if (checkpoint) {
1041
+ this.log.info(`Validation checkpoint building SUCCEEDED for slot ${this.slot}`, {
1042
+ ...checkpoint.toCheckpointInfo(),
1043
+ ...checkpoint.getStats(),
1044
+ feeAnalysisId: feeAnalysis?.id
1045
+ });
1046
+ } else {
1047
+ this.log.warn(`Validation block building FAILED for slot ${this.slot}`, {
1048
+ slot: this.slot,
1049
+ feeAnalysisId: feeAnalysis?.id
1050
+ });
1051
+ this.metrics.recordBlockProposalFailed('block_build_failed');
1052
+ }
1053
+ this.publisher.clearPendingRequests();
1054
+ }
1055
+ /** Waits until a specific time within the current slot */ async waitUntilTimeInSlot(targetSecondsIntoSlot) {
1056
+ const slotStartTimestamp = this.getSlotStartBuildTimestamp();
1057
+ const targetTimestamp = slotStartTimestamp + targetSecondsIntoSlot;
1058
+ await sleepUntil(new Date(targetTimestamp * 1000), this.dateProvider.nowAsDate());
1059
+ }
1060
+ getSlotStartBuildTimestamp() {
1061
+ return getSlotStartBuildTimestamp(this.slot, this.l1Constants);
1062
+ }
1063
+ getSecondsIntoSlot() {
1064
+ const slotStartTimestamp = this.getSlotStartBuildTimestamp();
1065
+ return Number((this.dateProvider.now() / 1000 - slotStartTimestamp).toFixed(3));
1066
+ }
1067
+ getPublisher() {
1068
+ return this.publisher;
1069
+ }
1070
+ }