@aztec-labs/sequencer-client 6.0.0-rc.2 → 6.0.0-rc.4

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 (78) hide show
  1. package/README.md +1 -1
  2. package/dest/client/sequencer-client.d.ts +1 -1
  3. package/dest/client/sequencer-client.d.ts.map +1 -1
  4. package/dest/client/sequencer-client.js +7 -2
  5. package/dest/config.d.ts +2 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +5 -0
  8. package/dest/index.d.ts +2 -2
  9. package/dest/index.d.ts.map +1 -1
  10. package/dest/index.js +1 -1
  11. package/dest/publisher/config.d.ts +7 -4
  12. package/dest/publisher/config.d.ts.map +1 -1
  13. package/dest/publisher/config.js +12 -10
  14. package/dest/publisher/gas_constants.d.ts +39 -0
  15. package/dest/publisher/gas_constants.d.ts.map +1 -0
  16. package/dest/publisher/gas_constants.js +42 -0
  17. package/dest/publisher/index.d.ts +2 -1
  18. package/dest/publisher/index.d.ts.map +1 -1
  19. package/dest/publisher/index.js +1 -0
  20. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts +1 -1
  21. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.d.ts.map +1 -1
  22. package/dest/publisher/l1_tx_failed_store/file_store_failed_tx_store.js +1 -0
  23. package/dest/publisher/publisher-manager-metrics.d.ts +19 -0
  24. package/dest/publisher/publisher-manager-metrics.d.ts.map +1 -0
  25. package/dest/publisher/publisher-manager-metrics.js +67 -0
  26. package/dest/publisher/sequencer-publisher-factory.d.ts +8 -4
  27. package/dest/publisher/sequencer-publisher-factory.d.ts.map +1 -1
  28. package/dest/publisher/sequencer-publisher-factory.js +16 -6
  29. package/dest/publisher/sequencer-publisher-metrics.d.ts +1 -3
  30. package/dest/publisher/sequencer-publisher-metrics.d.ts.map +1 -1
  31. package/dest/publisher/sequencer-publisher-metrics.js +0 -8
  32. package/dest/publisher/sequencer-publisher.d.ts +17 -4
  33. package/dest/publisher/sequencer-publisher.d.ts.map +1 -1
  34. package/dest/publisher/sequencer-publisher.js +168 -17
  35. package/dest/publisher/write_json.d.ts +1 -1
  36. package/dest/publisher/write_json.d.ts.map +1 -1
  37. package/dest/publisher/write_json.js +3 -1
  38. package/dest/sequencer/attestation_manipulation.d.ts +24 -0
  39. package/dest/sequencer/attestation_manipulation.d.ts.map +1 -0
  40. package/dest/sequencer/attestation_manipulation.js +72 -0
  41. package/dest/sequencer/automine/automine_factory.d.ts +1 -1
  42. package/dest/sequencer/automine/automine_factory.d.ts.map +1 -1
  43. package/dest/sequencer/automine/automine_factory.js +5 -1
  44. package/dest/sequencer/checkpoint_inbox_consumption.d.ts +135 -0
  45. package/dest/sequencer/checkpoint_inbox_consumption.d.ts.map +1 -0
  46. package/dest/sequencer/checkpoint_inbox_consumption.js +275 -0
  47. package/dest/sequencer/checkpoint_proposal_job.d.ts +27 -23
  48. package/dest/sequencer/checkpoint_proposal_job.d.ts.map +1 -1
  49. package/dest/sequencer/checkpoint_proposal_job.js +323 -527
  50. package/dest/sequencer/inbox_message_selection.d.ts +17 -16
  51. package/dest/sequencer/inbox_message_selection.d.ts.map +1 -1
  52. package/dest/sequencer/inbox_message_selection.js +20 -7
  53. package/dest/sequencer/metrics.d.ts +4 -4
  54. package/dest/sequencer/metrics.d.ts.map +1 -1
  55. package/dest/sequencer/metrics.js +6 -9
  56. package/dest/sequencer/sequencer.d.ts +9 -4
  57. package/dest/sequencer/sequencer.d.ts.map +1 -1
  58. package/dest/sequencer/sequencer.js +129 -38
  59. package/package.json +23 -23
  60. package/src/client/sequencer-client.ts +6 -1
  61. package/src/config.ts +7 -0
  62. package/src/index.ts +0 -3
  63. package/src/publisher/config.ts +20 -11
  64. package/src/publisher/gas_constants.ts +51 -0
  65. package/src/publisher/index.ts +1 -0
  66. package/src/publisher/l1_tx_failed_store/file_store_failed_tx_store.ts +1 -0
  67. package/src/publisher/publisher-manager-metrics.ts +76 -0
  68. package/src/publisher/sequencer-publisher-factory.ts +18 -7
  69. package/src/publisher/sequencer-publisher-metrics.ts +0 -12
  70. package/src/publisher/sequencer-publisher.ts +201 -24
  71. package/src/publisher/write_json.ts +3 -1
  72. package/src/sequencer/attestation_manipulation.ts +123 -0
  73. package/src/sequencer/automine/automine_factory.ts +4 -0
  74. package/src/sequencer/checkpoint_inbox_consumption.ts +340 -0
  75. package/src/sequencer/checkpoint_proposal_job.ts +434 -632
  76. package/src/sequencer/inbox_message_selection.ts +45 -24
  77. package/src/sequencer/metrics.ts +7 -9
  78. package/src/sequencer/sequencer.ts +116 -27
@@ -0,0 +1,340 @@
1
+ import { maxBigint, minBigint } from '@aztec-labs/foundation/bigint';
2
+ import type { BlockNumber, CheckpointNumber, SlotNumber } from '@aztec-labs/foundation/branded-types';
3
+ import type { Logger } from '@aztec-labs/foundation/log';
4
+ import { type DateProvider, executeTimeout } from '@aztec-labs/foundation/timer';
5
+ import type { MerkleTreeReadOperations } from '@aztec-labs/stdlib/interfaces/server';
6
+ import { type InboxMessagePosition, InboxMessagePrefixRef, type InboxMessageRange } from '@aztec-labs/stdlib/messaging';
7
+ import { MerkleTreeId } from '@aztec-labs/stdlib/trees';
8
+
9
+ import {
10
+ type EndpointResolution,
11
+ type InboxConsumptionCaps,
12
+ type InboxEndpointResolver,
13
+ type InboxSelectionPositions,
14
+ PROTOCOL_INBOX_CONSUMPTION_CAPS,
15
+ type StreamingMessageSource,
16
+ getEndpointUpperBound,
17
+ mustQueryEndpoint,
18
+ resolveEndpoint,
19
+ selectGreedyEnd,
20
+ selectSafeLocalEnd,
21
+ } from './inbox_message_selection.js';
22
+
23
+ /** Cap on the Inbox endpoint read a block makes near the checkpoint cap, well under a sub-slot. */
24
+ export const INBOX_ENDPOINT_READ_TIMEOUT_MS = 2_000;
25
+
26
+ /** What a block's streaming message selection decided. */
27
+ export type StreamingBundleSelection =
28
+ | {
29
+ /** Build the block over this range; the block signs `range.end` as its prefix reference. */
30
+ kind: 'consume';
31
+ range: InboxMessageRange;
32
+ }
33
+ | {
34
+ /** No checkpoint ending this way can be published; give up the slot without signing anything more. */
35
+ kind: 'abort';
36
+ reason: string;
37
+ context?: Record<string, unknown>;
38
+ };
39
+
40
+ /** What the forced tail block, built after the sub-slot schedule ran out, has to do to end on a live bucket end. */
41
+ export type ForcedEndpointDecision =
42
+ | {
43
+ /** Build one message-only block over this range, ending on the endpoint, before `deadline`. */
44
+ kind: 'consume';
45
+ range: InboxMessageRange;
46
+ deadline: Date;
47
+ }
48
+ | {
49
+ /** The cursor already sits on a live bucket end; the checkpoint publishes as it stands. */
50
+ kind: 'already-at-endpoint';
51
+ }
52
+ | {
53
+ /** No live bucket end is reachable; the checkpoint has to be abandoned. */
54
+ kind: 'abort';
55
+ reason: string;
56
+ context: Record<string, unknown>;
57
+ };
58
+
59
+ /** Collaborators of {@link CheckpointInboxConsumption}. */
60
+ export type CheckpointInboxConsumptionDeps = {
61
+ messageSource: StreamingMessageSource;
62
+ inbox: InboxEndpointResolver;
63
+ dateProvider: DateProvider;
64
+ log: Logger;
65
+ /** Fields prepended to every log line the consumption emits. */
66
+ logContext: { slot: SlotNumber; checkpointNumber: CheckpointNumber };
67
+ };
68
+
69
+ /** The inputs one selection attempt decides from, read once at its start. */
70
+ type SelectionSnapshot = InboxSelectionPositions & {
71
+ cursor: InboxMessagePosition;
72
+ caps: InboxConsumptionCaps;
73
+ };
74
+
75
+ /**
76
+ * Streaming Inbox consumption of one checkpoint: the cursor and every range decision made from it. Consumption starts
77
+ * from the parent checkpoint's consumed message prefix and advances one block at a time, greedily on the local log
78
+ * while the step stays clear of the checkpoint cap and against a live L1 bucket end once it does not.
79
+ *
80
+ * Invariants:
81
+ * - Nothing is cached across attempts: every selection re-derives from the current cursor and the current local view,
82
+ * so a block that fails to build and is retried is offered the same messages again.
83
+ * - Each selection reads the cursor and the local synced position once, at its start, and decides only from those.
84
+ * - Selections never modify the cursor. Only {@link commit} does, after a block built over the selected range, and it
85
+ * replaces the cursor rather than modifying the position in place. An endpoint lookup that lost its timeout race
86
+ * and keeps running therefore only ever reads a position that stays valid.
87
+ */
88
+ export class CheckpointInboxConsumption {
89
+ private constructor(
90
+ /** Cumulative Inbox message count consumed as of the parent checkpoint; the per-checkpoint cap origin. */
91
+ readonly checkpointStartTotalMsgCount: bigint,
92
+ /** The message prefix consumed so far (the parent checkpoint's until a block of this checkpoint builds). */
93
+ private cursor: InboxMessagePosition,
94
+ private readonly deps: CheckpointInboxConsumptionDeps,
95
+ ) {}
96
+
97
+ /**
98
+ * Starts consumption at the parent checkpoint's consumed message prefix. The parent's cumulative consumed total is
99
+ * the L1-to-L2 message tree leaf count of the fork this checkpoint builds on (compact indexing makes leaf count equal
100
+ * cumulative message count), and the local message log serves the prefix hash at that count. Genesis is the
101
+ * `total = 0` case with a zero hash.
102
+ */
103
+ static async start(
104
+ fork: Pick<MerkleTreeReadOperations, 'getTreeInfo'>,
105
+ deps: CheckpointInboxConsumptionDeps,
106
+ ): Promise<CheckpointInboxConsumption> {
107
+ const checkpointStartTotalMsgCount = (await fork.getTreeInfo(MerkleTreeId.L1_TO_L2_MESSAGE_TREE)).size;
108
+ const cursor = await deps.messageSource.getMessagePosition(checkpointStartTotalMsgCount);
109
+ if (cursor === undefined) {
110
+ throw new Error(
111
+ `Streaming inbox: cannot resolve the Inbox message prefix at cumulative total ${checkpointStartTotalMsgCount} ` +
112
+ `(checkpoint ${deps.logContext.checkpointNumber}); local Inbox view has not synced it`,
113
+ );
114
+ }
115
+ return new CheckpointInboxConsumption(checkpointStartTotalMsgCount, cursor, deps);
116
+ }
117
+
118
+ /** Cumulative chain total consumed through the cursor (not this checkpoint's delta). */
119
+ get consumedTotalMsgCount(): bigint {
120
+ return this.cursor.totalMessageCount;
121
+ }
122
+
123
+ /** Whether any block of this checkpoint has advanced the cursor past the checkpoint start. */
124
+ get hasConsumedInThisCheckpoint(): boolean {
125
+ return this.cursor.totalMessageCount > this.checkpointStartTotalMsgCount;
126
+ }
127
+
128
+ /**
129
+ * Selects the message range the next block consumes. Does not advance the cursor; the caller commits the range
130
+ * only after the block builds successfully.
131
+ *
132
+ * Selection is greedy on the local log: every message the archiver has observed, up to the per-block and
133
+ * checkpoint caps. A block consults L1 only when it is the checkpoint's final block, whose position must be a live
134
+ * L1 bucket end, or when its prospective end would pass the threshold one bucket below the cap and could leave the
135
+ * last legal endpoint behind. The lookup is bounded by the checkpoint cap on a non-final block, so a mandatory
136
+ * bucket beyond this block's own reach is not stranded by a nearer endpoint, and additionally by one block's
137
+ * capacity on the final block. A non-final block then ends at the further of what the lookup allows and the safe
138
+ * local step, so consulting L1 never consumes less than staying below the threshold would have, and it may
139
+ * legitimately end inside a bucket. The final block instead ends exactly on the resolved boundary, so whenever the
140
+ * last live boundary within reach sits behind the safe local step it consumes fewer messages than the local log
141
+ * alone would allow. Nothing is retained: the next attempt decides again.
142
+ *
143
+ * An endpoint that cannot be resolved on a non-final block (local lag, no live endpoint yet) leaves the block with
144
+ * that safe local step and is retried on the next block; on the final block it abandons the checkpoint. A local
145
+ * prefix that no longer matches the cursor means the blocks already signed were built on messages the local log
146
+ * has since replaced, which also abandons the checkpoint.
147
+ */
148
+ async selectRange(opts: { isFinalBlock: boolean; buildDeadline: number }): Promise<StreamingBundleSelection> {
149
+ const snapshot = await this.takeSnapshot();
150
+ const { cursor, cursorCount, localSyncedCount, checkpointStartCount, caps } = snapshot;
151
+ const greedyEnd = selectGreedyEnd(snapshot);
152
+
153
+ if (
154
+ !mustQueryEndpoint({ prospectiveEnd: greedyEnd, checkpointStartCount, isFinalBlock: opts.isFinalBlock, caps })
155
+ ) {
156
+ return this.readRange(cursor, greedyEnd);
157
+ }
158
+
159
+ const upperBound = getEndpointUpperBound({ ...snapshot, isFinalBlock: opts.isFinalBlock });
160
+ const resolved = await this.resolveEndpointWithinDeadline(cursor, upperBound, opts.buildDeadline);
161
+ const safeLocalEnd = selectSafeLocalEnd(snapshot);
162
+ if (!resolved.ok) {
163
+ if (resolved.reason === 'local_prefix_changed') {
164
+ return { kind: 'abort', reason: 'inbox_prefix_reorged', context: { upperBound } };
165
+ }
166
+ if (opts.isFinalBlock) {
167
+ return {
168
+ kind: 'abort',
169
+ reason: 'inbox_completion_unresolved',
170
+ context: { cause: resolved.reason, upperBound, endpointTotal: resolved.endpointTotal, localSyncedCount },
171
+ };
172
+ }
173
+ this.deps.log.warn(`Streaming Inbox endpoint not resolvable yet, taking the safe local step`, {
174
+ ...this.deps.logContext,
175
+ cause: resolved.reason,
176
+ cursorTotalMsgCount: cursorCount,
177
+ localSyncedCount,
178
+ upperBound,
179
+ endpointTotal: resolved.endpointTotal,
180
+ safeLocalEnd,
181
+ });
182
+ return this.readRange(cursor, safeLocalEnd);
183
+ }
184
+
185
+ const endpointTotal = resolved.endpoint.totalMessageCount;
186
+ const endpointEnd = minBigint(cursorCount + BigInt(caps.perBlockCap), endpointTotal);
187
+ // The final block has to land on the endpoint, so it takes it even when the safe local step reaches further; any
188
+ // other block takes the further of the two, so consulting L1 never consumes less than staying below the
189
+ // threshold would have.
190
+ const end = opts.isFinalBlock ? endpointEnd : maxBigint(safeLocalEnd, endpointEnd);
191
+ this.deps.log.verbose(`Streaming Inbox resolved endpoint ${endpointTotal}, consuming through ${end}`, {
192
+ ...this.deps.logContext,
193
+ cursorTotalMsgCount: cursorCount,
194
+ localSyncedCount,
195
+ upperBound,
196
+ endpointTotalMsgCount: endpointTotal,
197
+ bucketSeq: resolved.bucketSeq,
198
+ end,
199
+ });
200
+ // An end short of or past the endpoint needs its own read, so the signed hash is the one at `end` and never the
201
+ // endpoint's; landing exactly on the endpoint reuses the snapshot the resolver already read and checked against
202
+ // the cursor's hash.
203
+ return end === endpointTotal ? { kind: 'consume', range: resolved.range } : this.readRange(cursor, end);
204
+ }
205
+
206
+ /**
207
+ * Decides the forced tail block that ends the checkpoint at a live L1 bucket end after the sub-slot schedule ran out
208
+ * mid-checkpoint, resolving the endpoint the way the checkpoint's final block would. Does not advance the cursor.
209
+ * The deadline is taken from `getDeadline` only once the local view has been read, so it reflects the time the
210
+ * lookup actually starts at.
211
+ */
212
+ async resolveForcedEndpoint(opts: {
213
+ blockNumber: BlockNumber;
214
+ getDeadline: () => { deadline: Date; pastLastBlockBuildTime: boolean };
215
+ }): Promise<ForcedEndpointDecision> {
216
+ const snapshot = await this.takeSnapshot();
217
+ const { cursor, cursorCount, localSyncedCount } = snapshot;
218
+ const upperBound = getEndpointUpperBound({ ...snapshot, isFinalBlock: true });
219
+ const { deadline, pastLastBlockBuildTime } = opts.getDeadline();
220
+ this.deps.log.warn(
221
+ `Ending checkpoint ${this.deps.logContext.checkpointNumber} with a forced Inbox endpoint block`,
222
+ {
223
+ ...this.deps.logContext,
224
+ blockNumber: opts.blockNumber,
225
+ cursorTotalMsgCount: cursorCount,
226
+ upperBound,
227
+ deadline: deadline.toISOString(),
228
+ pastLastBlockBuildTime,
229
+ },
230
+ );
231
+
232
+ const resolved = await this.resolveEndpointWithinDeadline(cursor, upperBound, deadline.getTime() / 1000);
233
+ if (!resolved.ok) {
234
+ return {
235
+ kind: 'abort',
236
+ reason: resolved.reason === 'local_prefix_changed' ? 'inbox_prefix_reorged' : 'inbox_completion_unresolved',
237
+ context: { cause: resolved.reason, upperBound, endpointTotal: resolved.endpointTotal, localSyncedCount },
238
+ };
239
+ }
240
+ if (resolved.endpoint.totalMessageCount === cursorCount) {
241
+ this.deps.log.verbose(
242
+ `Checkpoint ${this.deps.logContext.checkpointNumber} already ends at a live Inbox bucket end`,
243
+ { ...this.deps.logContext, cursorTotalMsgCount: cursorCount },
244
+ );
245
+ return { kind: 'already-at-endpoint' };
246
+ }
247
+ return { kind: 'consume', range: resolved.range, deadline };
248
+ }
249
+
250
+ /**
251
+ * Advances the cursor to `range.end` after a block built over `range`, and returns the prefix reference that block
252
+ * signs. A block that consumed nothing re-signs the cursor's prefix. Throws if the range does not start at the
253
+ * cursor, which would mean it was not selected from the current cursor.
254
+ */
255
+ commit(range: InboxMessageRange): InboxMessagePrefixRef {
256
+ if (
257
+ range.start.totalMessageCount !== this.cursor.totalMessageCount ||
258
+ !range.start.rollingHash.equals(this.cursor.rollingHash)
259
+ ) {
260
+ throw new Error(
261
+ `Streaming inbox: cannot commit a range starting at message total ${range.start.totalMessageCount} ` +
262
+ `with the cursor at ${this.cursor.totalMessageCount} (checkpoint ${this.deps.logContext.checkpointNumber})`,
263
+ );
264
+ }
265
+ this.cursor = range.end;
266
+ return InboxMessagePrefixRef.fromPosition(this.cursor);
267
+ }
268
+
269
+ /** The consumption fields reported when a checkpoint is abandoned. */
270
+ toLogContext(): { checkpointStartTotalMsgCount: bigint; consumedTotalMsgCount: bigint; inboxRollingHash: string } {
271
+ return {
272
+ checkpointStartTotalMsgCount: this.checkpointStartTotalMsgCount,
273
+ consumedTotalMsgCount: this.cursor.totalMessageCount,
274
+ inboxRollingHash: this.cursor.rollingHash.toString(),
275
+ };
276
+ }
277
+
278
+ private async takeSnapshot(): Promise<SelectionSnapshot> {
279
+ const cursor = this.cursor;
280
+ const localSyncedCount = (await this.deps.messageSource.getSyncedMessagePosition()).totalMessageCount;
281
+ return {
282
+ cursor,
283
+ cursorCount: cursor.totalMessageCount,
284
+ localSyncedCount,
285
+ checkpointStartCount: this.checkpointStartTotalMsgCount,
286
+ caps: PROTOCOL_INBOX_CONSUMPTION_CAPS,
287
+ };
288
+ }
289
+
290
+ /**
291
+ * Reads the messages from the cursor to `end` together with the positions at both ends from one snapshot of the
292
+ * local log, and checks that the log still starts where the cursor says: the blocks signed so far were built on
293
+ * that prefix, so a changed prefix (a content-changing L1 reorg) means the checkpoint cannot continue. A range the
294
+ * log can no longer serve whole is the same condition.
295
+ */
296
+ private async readRange(cursor: InboxMessagePosition, end: bigint): Promise<StreamingBundleSelection> {
297
+ let range: InboxMessageRange;
298
+ try {
299
+ range = await this.deps.messageSource.getL1ToL2MessageRange(cursor.totalMessageCount, end);
300
+ } catch (err) {
301
+ return {
302
+ kind: 'abort',
303
+ reason: 'inbox_range_unavailable',
304
+ context: { end, error: err instanceof Error ? err.message : String(err) },
305
+ };
306
+ }
307
+ if (!range.start.rollingHash.equals(cursor.rollingHash)) {
308
+ return {
309
+ kind: 'abort',
310
+ reason: 'inbox_prefix_reorged',
311
+ context: { end, localPrefixHash: range.start.rollingHash.toString() },
312
+ };
313
+ }
314
+ return { kind: 'consume', range };
315
+ }
316
+
317
+ /**
318
+ * Runs the single Inbox endpoint query of an endpoint block within the block's build deadline. The lookup gets at
319
+ * least a millisecond even past the deadline, and any failure, a timeout included, reads as no live endpoint.
320
+ */
321
+ private resolveEndpointWithinDeadline(
322
+ cursor: InboxMessagePosition,
323
+ upperBound: bigint,
324
+ buildDeadline: number,
325
+ ): Promise<EndpointResolution> {
326
+ const remainingMs = buildDeadline * 1000 - this.deps.dateProvider.now();
327
+ const timeoutMs = Math.max(1, Math.min(INBOX_ENDPOINT_READ_TIMEOUT_MS, remainingMs));
328
+ return executeTimeout(
329
+ () => resolveEndpoint({ inbox: this.deps.inbox, messageSource: this.deps.messageSource, cursor, upperBound }),
330
+ timeoutMs,
331
+ `Inbox endpoint lookup at or before message total ${upperBound}`,
332
+ ).catch((err): EndpointResolution => {
333
+ this.deps.log.warn(`Inbox endpoint lookup failed, treating the endpoint as unresolved: ${err}`, {
334
+ ...this.deps.logContext,
335
+ upperBound,
336
+ });
337
+ return { ok: false, reason: 'no_live_endpoint', upperBound };
338
+ });
339
+ }
340
+ }