@aztec-labs/sequencer-client 6.0.0-rc.3 → 6.0.0

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
@@ -1,7 +1,7 @@
1
1
  import type { BlobClientInterface } from '@aztec-labs/blob-client/client';
2
2
  import type { EpochCache } from '@aztec-labs/epoch-cache';
3
3
  import type { GovernanceProposerContract, RollupContract } from '@aztec-labs/ethereum/contracts';
4
- import type { L1TxUtils } from '@aztec-labs/ethereum/l1-tx-utils';
4
+ import type { L1TxUtils, SendCostRequirement } from '@aztec-labs/ethereum/l1-tx-utils';
5
5
  import type { PublisherFilter, PublisherManager } from '@aztec-labs/ethereum/publisher-manager';
6
6
  import { SlotNumber } from '@aztec-labs/foundation/branded-types';
7
7
  import { EthAddress } from '@aztec-labs/foundation/eth-address';
@@ -58,10 +58,15 @@ export class SequencerPublisherFactory {
58
58
 
59
59
  /**
60
60
  * Creates a new SequencerPublisher instance.
61
- * @param _validatorAddress - The address of the validator that will be using the publisher.
61
+ * @param validatorAddress - The address of the validator that will be using the publisher.
62
+ * @param opts.requirement - Gas and blobs of the send the publisher is for. When set, only a publisher that can afford
63
+ * it is selected, and NoAffordablePublisherError is thrown if none can.
62
64
  * @returns A new SequencerPublisher instance.
63
65
  */
64
- public async create(validatorAddress?: EthAddress): Promise<AttestorPublisherPair> {
66
+ public async create(
67
+ validatorAddress?: EthAddress,
68
+ opts?: { requirement?: SendCostRequirement },
69
+ ): Promise<AttestorPublisherPair> {
65
70
  // If we have been given an attestor address we must only allow publishers permitted for that attestor
66
71
 
67
72
  const allowedPublishers = !validatorAddress ? [] : this.nodeKeyStore.getPublisherAddresses(validatorAddress);
@@ -72,14 +77,19 @@ export class SequencerPublisherFactory {
72
77
  return allowedPublishers.some(allowedPublisher => allowedPublisher.equals(publisherAddress));
73
78
  };
74
79
 
75
- const l1Publisher = await this.deps.publisherManager.getAvailablePublisher(filter);
80
+ const l1Publisher = await this.deps.publisherManager.getAvailablePublisher(filter, {
81
+ requirement: opts?.requirement,
82
+ });
76
83
  const attestorAddress =
77
84
  validatorAddress ?? this.nodeKeyStore.getAttestorForPublisher(l1Publisher.getSenderAddress());
78
85
 
79
86
  const rollup = this.deps.rollupContract;
80
87
  const slashingProposerContract = await rollup.getSlashingProposer();
81
88
 
82
- const getNextPublisher = async (excludeAddresses: EthAddress[]): Promise<L1TxUtils | undefined> => {
89
+ const getNextPublisher = async (
90
+ excludeAddresses: EthAddress[],
91
+ requirement?: SendCostRequirement,
92
+ ): Promise<L1TxUtils | undefined> => {
83
93
  const exclusionFilter: PublisherFilter<L1TxUtils> = (utils: L1TxUtils) => {
84
94
  if (excludeAddresses.some(addr => addr.equals(utils.getSenderAddress()))) {
85
95
  return false;
@@ -87,8 +97,9 @@ export class SequencerPublisherFactory {
87
97
  return filter(utils);
88
98
  };
89
99
  try {
90
- return await this.deps.publisherManager.getAvailablePublisher(exclusionFilter);
91
- } catch {
100
+ return await this.deps.publisherManager.getAvailablePublisher(exclusionFilter, { requirement });
101
+ } catch (err) {
102
+ this.logger.debug(`No replacement publisher available`, { err, requirement });
92
103
  return undefined;
93
104
  }
94
105
  };
@@ -2,7 +2,6 @@ import { createLogger } from '@aztec-labs/foundation/log';
2
2
  import type { L1PublishCheckpointStats, L1PublishStats } from '@aztec-labs/stdlib/stats';
3
3
  import {
4
4
  Attributes,
5
- type Gauge,
6
5
  type Histogram,
7
6
  Metrics,
8
7
  type TelemetryClient,
@@ -30,8 +29,6 @@ export class SequencerPublisherMetrics {
30
29
  private readonly blobTxSuccessCounter: UpDownCounter;
31
30
  private readonly blobTxFailureCounter: UpDownCounter;
32
31
 
33
- private senderBalance: Gauge;
34
-
35
32
  constructor(
36
33
  client: TelemetryClient,
37
34
  name = 'SequencerPublisher',
@@ -67,8 +64,6 @@ export class SequencerPublisherMetrics {
67
64
  this.blobTxFailureCounter = createUpDownCounterWithDefault(meter, Metrics.L1_PUBLISHER_BLOB_TX_FAILURE);
68
65
 
69
66
  this.txTotalFee = meter.createHistogram(Metrics.L1_PUBLISHER_TX_TOTAL_FEE);
70
-
71
- this.senderBalance = meter.createGauge(Metrics.L1_PUBLISHER_BALANCE);
72
67
  }
73
68
 
74
69
  recordFailedTx(txType: L1TxType) {
@@ -96,13 +91,6 @@ export class SequencerPublisherMetrics {
96
91
  }
97
92
  }
98
93
 
99
- recordSenderBalance(wei: bigint, senderAddress: string) {
100
- const eth = parseFloat(formatEther(wei, 'wei'));
101
- this.senderBalance.record(eth, {
102
- [Attributes.SENDER_ADDRESS]: senderAddress,
103
- });
104
- }
105
-
106
94
  private recordTx(txType: L1TxType, durationMs: number, stats: L1PublishStats) {
107
95
  const attributes = {
108
96
  [Attributes.L1_TX_TYPE]: txType,
@@ -20,14 +20,17 @@ import {
20
20
  import { type L1FeeAnalysisResult, L1FeeAnalyzer, captureWindowBlockFees } from '@aztec-labs/ethereum/l1-fee-analysis';
21
21
  import {
22
22
  AmsterdamForkDetector,
23
+ type FeesPerGas,
23
24
  type L1BlobInputs,
24
25
  type L1TxConfig,
25
26
  type L1TxRequest,
26
27
  L1TxTimeoutError,
27
28
  type L1TxUtils,
28
29
  MAX_L1_TX_LIMIT,
30
+ type SendCostRequirement,
29
31
  type TransactionStats,
30
32
  WEI_CONST,
33
+ computeSendCost,
31
34
  summarizeTransactionReceipt,
32
35
  } from '@aztec-labs/ethereum/l1-tx-utils';
33
36
  import {
@@ -66,6 +69,7 @@ import {
66
69
  type TransactionReceipt,
67
70
  type TypedDataDefinition,
68
71
  encodeFunctionData,
72
+ formatEther,
69
73
  keccak256,
70
74
  size,
71
75
  toHex,
@@ -140,6 +144,46 @@ type GovernanceSignalAction = Extract<Action, 'governance-signal'>;
140
144
  // Sorting for actions such that invalidations go before proposals, and proposals go before votes
141
145
  export const compareActions = (a: Action, b: Action) => Actions.indexOf(a) - Actions.indexOf(b);
142
146
 
147
+ /**
148
+ * Actions whose bundle must be affordable before it is sent. They are never dropped individually: an invalidation must
149
+ * land in the same tx as the proposal that builds on it, or the proposal reverts.
150
+ */
151
+ const REQUIRED_ACTIONS: readonly Action[] = [
152
+ 'invalidate-by-invalid-attestation',
153
+ 'invalidate-by-insufficient-attestations',
154
+ 'propose',
155
+ ];
156
+
157
+ /** Actions dropped from a bundle with required actions when the publisher cannot afford the whole bundle. */
158
+ const OPTIONAL_ACTIONS: readonly Action[] = ['governance-signal', 'vote-offenses', 'execute-slash'];
159
+
160
+ /** ETH cost of a bundle with required actions, checked against the publisher balance before sending it. */
161
+ type BundleCost = { requirement: SendCostRequirement; required: bigint };
162
+
163
+ /** Thrown before sending a bundle the current publisher cannot afford, so the send is never attempted. */
164
+ class BundleUnaffordableError extends Error {
165
+ public readonly required: bigint;
166
+ public readonly requirement: SendCostRequirement;
167
+
168
+ constructor(
169
+ public readonly publisher: EthAddress,
170
+ public readonly balance: bigint,
171
+ cost: BundleCost,
172
+ ) {
173
+ super(
174
+ `Publisher ${publisher} cannot afford the bundle: balance ${formatEther(balance)} ETH, ` +
175
+ `required ${formatEther(cost.required)} ETH (gas limit ${cost.requirement.gasLimit}, ` +
176
+ `${cost.requirement.blobCount} blobs)`,
177
+ );
178
+ this.name = 'BundleUnaffordableError';
179
+ this.required = cost.required;
180
+ this.requirement = cost.requirement;
181
+ }
182
+ }
183
+
184
+ /** Requests surviving bundle simulation, with the gas limit to send them with (undefined if simulation was skipped). */
185
+ type SimulatedBundle = { requests: RequestWithExpiry[]; droppedRequests: DroppedRequest[]; gasLimit?: bigint };
186
+
143
187
  export type InvalidateCheckpointRequest = {
144
188
  request: L1TxRequest;
145
189
  reason: 'invalid-attestation' | 'insufficient-attestations';
@@ -198,8 +242,14 @@ export class SequencerPublisher implements Disposable {
198
242
 
199
243
  private blobClient: BlobClientInterface;
200
244
 
201
- /** Optional callback to obtain a replacement publisher when the current one fails to send. */
202
- private getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
245
+ /**
246
+ * Optional callback to obtain a replacement publisher when the current one fails to send. With a requirement, only a
247
+ * publisher that can afford a send of that size is returned.
248
+ */
249
+ private getNextPublisher?: (
250
+ excludeAddresses: EthAddress[],
251
+ requirement?: SendCostRequirement,
252
+ ) => Promise<L1TxUtils | undefined>;
203
253
 
204
254
  /** L1 fee analyzer for fisherman mode */
205
255
  private l1FeeAnalyzer?: L1FeeAnalyzer;
@@ -241,7 +291,10 @@ export class SequencerPublisher implements Disposable {
241
291
  metrics: SequencerPublisherMetrics;
242
292
  lastActions: Partial<Record<Action, SlotNumber>>;
243
293
  log?: Logger;
244
- getNextPublisher?: (excludeAddresses: EthAddress[]) => Promise<L1TxUtils | undefined>;
294
+ getNextPublisher?: (
295
+ excludeAddresses: EthAddress[],
296
+ requirement?: SendCostRequirement,
297
+ ) => Promise<L1TxUtils | undefined>;
245
298
  },
246
299
  ) {
247
300
  this.log = deps.log ?? createLogger('sequencer:publisher');
@@ -582,16 +635,19 @@ export class SequencerPublisher implements Disposable {
582
635
  return undefined;
583
636
  }
584
637
 
585
- const { requests, droppedRequests, gasLimit } =
586
- bundleResult.kind === 'fallback'
587
- ? {
588
- requests: bundleResult.requests,
589
- droppedRequests: bundleResult.droppedRequests,
590
- gasLimit: MAX_L1_TX_LIMIT,
591
- }
592
- : bundleResult;
638
+ const simulated: SimulatedBundle = {
639
+ requests: bundleResult.requests,
640
+ droppedRequests: bundleResult.droppedRequests,
641
+ gasLimit: bundleResult.kind === 'fallback' ? undefined : bundleResult.gasLimit,
642
+ };
643
+ this.logDroppedInSim(simulated.droppedRequests);
593
644
 
594
- this.logDroppedInSim(droppedRequests);
645
+ const affordable = await this.dropOptionalActionsIfUnaffordable(simulated, currentL2Slot);
646
+ if (affordable === undefined) {
647
+ return undefined;
648
+ }
649
+ const { requests, droppedRequests, cost, feeDroppedActions } = affordable;
650
+ const gasLimit = affordable.gasLimit ?? MAX_L1_TX_LIMIT;
595
651
 
596
652
  // Compute blobConfig from survivors (not original validRequests) so that if the propose
597
653
  // entry was dropped by bundleSimulate we don't attach a blob-typed config to a non-blob tx.
@@ -602,12 +658,12 @@ export class SequencerPublisher implements Disposable {
602
658
  requests: requests.map(request => request.action),
603
659
  txConfig,
604
660
  });
605
- const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig, currentL2Slot);
661
+ const result = await this.forwardWithPublisherRotation(requests, txConfig, blobConfig, currentL2Slot, cost);
606
662
  if (result === undefined) {
607
663
  return undefined;
608
664
  }
609
665
  const { successfulActions = [], failedActions = [] } = this.callbackBundledTransactions(requests, result);
610
- const allFailedActions = [...failedActions, ...droppedRequests.map(d => d.request.action)];
666
+ const allFailedActions = [...failedActions, ...droppedRequests.map(d => d.request.action), ...feeDroppedActions];
611
667
  return {
612
668
  result,
613
669
  expiredActions,
@@ -657,18 +713,104 @@ export class SequencerPublisher implements Disposable {
657
713
  })();
658
714
  }
659
715
  return undefined;
660
- } finally {
661
- try {
662
- this.metrics.recordSenderBalance(
663
- await this.l1TxUtils.getSenderBalance(),
664
- this.l1TxUtils.getSenderAddress().toString(),
665
- );
666
- } catch (err) {
667
- this.log.warn(`Failed to record balance after sending tx: ${err}`);
668
- }
669
716
  }
670
717
  }
671
718
 
719
+ /**
720
+ * Bundles with a proposal or invalidation must be affordable before sending: if the publisher cannot pay for the whole
721
+ * bundle, drops the optional votes and re-simulates the rest, rather than losing the proposal to fees. Returns the
722
+ * bundle to send along with its cost (only set for bundles with required actions), or undefined if nothing survived.
723
+ */
724
+ private async dropOptionalActionsIfUnaffordable(
725
+ bundle: SimulatedBundle,
726
+ targetSlot: SlotNumber,
727
+ ): Promise<(SimulatedBundle & { cost?: BundleCost; feeDroppedActions: Action[] }) | undefined> {
728
+ const fees = bundle.requests.some(r => REQUIRED_ACTIONS.includes(r.action))
729
+ ? await this.tryGetFeesForCostCheck(bundle.requests)
730
+ : undefined;
731
+ if (!fees) {
732
+ return { ...bundle, feeDroppedActions: [] };
733
+ }
734
+
735
+ // Without a simulated gas limit the bundle is sent at the gas ceiling, so dropping votes would not change its cost.
736
+ const cost = this.computeBundleCost(bundle.requests, fees, bundle.gasLimit);
737
+ const optional = bundle.requests.filter(r => OPTIONAL_ACTIONS.includes(r.action));
738
+ if (
739
+ optional.length === 0 ||
740
+ bundle.gasLimit === undefined ||
741
+ (await this.checkAffordable(this.l1TxUtils, cost)).affordable
742
+ ) {
743
+ return { ...bundle, cost, feeDroppedActions: [] };
744
+ }
745
+
746
+ const feeDroppedActions = optional.map(r => r.action);
747
+ const remaining = bundle.requests.filter(r => !OPTIONAL_ACTIONS.includes(r.action));
748
+ this.log.warn(`Dropping optional actions since publisher cannot afford the full bundle`, {
749
+ droppedActions: feeDroppedActions,
750
+ remainingActions: remaining.map(r => r.action),
751
+ publisher: this.getSenderAddress().toString(),
752
+ required: cost.required,
753
+ gasLimit: cost.requirement.gasLimit,
754
+ blobCount: cost.requirement.blobCount,
755
+ slot: targetSlot,
756
+ });
757
+
758
+ const reduced = await this.bundleSimulator.simulate(remaining, targetSlot);
759
+ this.logDroppedInSim(reduced.droppedRequests);
760
+ if (reduced.kind === 'aborted') {
761
+ void this.backupDroppedInSim(reduced.droppedRequests, targetSlot).catch(err =>
762
+ this.log.error(`Failed to backup requests dropped in simulation`, err),
763
+ );
764
+ return undefined;
765
+ }
766
+
767
+ const gasLimit = reduced.kind === 'fallback' ? undefined : reduced.gasLimit;
768
+ return {
769
+ requests: reduced.requests,
770
+ droppedRequests: [...bundle.droppedRequests, ...reduced.droppedRequests],
771
+ gasLimit,
772
+ cost: reduced.requests.some(r => REQUIRED_ACTIONS.includes(r.action))
773
+ ? this.computeBundleCost(reduced.requests, fees, gasLimit)
774
+ : undefined,
775
+ feeDroppedActions,
776
+ };
777
+ }
778
+
779
+ /**
780
+ * Fetches the fees used to cost a bundle against the publisher balance. Returns undefined if they cannot be read, in
781
+ * which case the bundle is sent unchecked: the publisher already passed the affordability check at selection.
782
+ */
783
+ private async tryGetFeesForCostCheck(requests: RequestWithExpiry[]): Promise<FeesPerGas | undefined> {
784
+ const isBlobTx = requests.some(r => r.blobConfig);
785
+ try {
786
+ return await this.l1TxUtils.getFeesPerGas(undefined, isBlobTx, 0);
787
+ } catch (err) {
788
+ this.log.warn(`Failed to fetch L1 fees to check bundle affordability, sending unchecked`, { err });
789
+ return undefined;
790
+ }
791
+ }
792
+
793
+ /**
794
+ * Computes the worst-case ETH cost of a bundle: its gas limit times the max fee per gas, plus blob fees. When the
795
+ * bundle gas limit is unknown (eth_simulateV1 unavailable) the send uses the MAX_L1_TX_LIMIT ceiling, and L1 checks the
796
+ * sender balance against that limit before executing anything, so the bundle is costed at the ceiling too.
797
+ */
798
+ private computeBundleCost(requests: RequestWithExpiry[], fees: FeesPerGas, gasLimit: bigint | undefined): BundleCost {
799
+ const blobCount = requests.find(r => r.blobConfig)?.blobConfig?.blobs.length ?? 0;
800
+ const requirement: SendCostRequirement = { gasLimit: gasLimit ?? MAX_L1_TX_LIMIT, blobCount };
801
+ return { requirement, required: computeSendCost(fees, requirement) };
802
+ }
803
+
804
+ /** Checks whether the publisher holds the ETH the bundle needs and is not backed off for insufficient funds. */
805
+ private async checkAffordable(
806
+ publisher: L1TxUtils,
807
+ cost: BundleCost,
808
+ ): Promise<{ affordable: boolean; balance: bigint }> {
809
+ const balance = await publisher.getSenderBalance();
810
+ const affordable = balance >= cost.required && !publisher.isBackedOffForInsufficientFunds(balance);
811
+ return { affordable, balance };
812
+ }
813
+
672
814
  /** Logs entries dropped by bundle simulation as warnings on the publisher's logger. */
673
815
  private logDroppedInSim(dropped: DroppedRequest[]): void {
674
816
  for (const drop of dropped) {
@@ -727,6 +869,7 @@ export class SequencerPublisher implements Disposable {
727
869
  txConfig: RequestWithExpiry['gasConfig'],
728
870
  blobConfig: L1BlobInputs | undefined,
729
871
  targetSlot?: SlotNumber,
872
+ cost?: BundleCost,
730
873
  ) {
731
874
  if (!txConfig?.gasLimit) {
732
875
  throw new Error('gasLimit is required for bundled transactions');
@@ -746,6 +889,9 @@ export class SequencerPublisher implements Disposable {
746
889
  triedAddresses.push(currentPublisher.getSenderAddress());
747
890
 
748
891
  try {
892
+ if (cost) {
893
+ await this.assertCanAfford(currentPublisher, cost);
894
+ }
749
895
  const result = await Multicall3.forward(
750
896
  validRequests.map(r => r.request),
751
897
  currentPublisher,
@@ -766,6 +912,22 @@ export class SequencerPublisher implements Disposable {
766
912
  this.backupRevertFailure(validRequests, err, currentPublisher, targetSlot);
767
913
  return undefined;
768
914
  }
915
+ if (err instanceof BundleUnaffordableError) {
916
+ const nextPublisher = await this.getNextPublisher?.([...triedAddresses], err.requirement);
917
+ if (!nextPublisher) {
918
+ this.log.error(`No publisher can afford the bundle, not sending it`, err, {
919
+ actions: validRequests.map(r => r.action),
920
+ triedAddresses: triedAddresses.map(a => a.toString()),
921
+ required: err.required,
922
+ gasLimit: err.requirement.gasLimit,
923
+ blobCount: err.requirement.blobCount,
924
+ slot: targetSlot,
925
+ });
926
+ return undefined;
927
+ }
928
+ currentPublisher = nextPublisher;
929
+ continue;
930
+ }
769
931
  const viemError = formatViemError(err);
770
932
  if (!this.getNextPublisher) {
771
933
  this.log.error('Failed to publish bundled transactions', viemError);
@@ -776,7 +938,7 @@ export class SequencerPublisher implements Disposable {
776
938
  `Publisher ${currentPublisher.getSenderAddress()} failed to send, rotating to next publisher`,
777
939
  viemError,
778
940
  );
779
- const nextPublisher = await this.getNextPublisher([...triedAddresses]);
941
+ const nextPublisher = await this.getNextPublisher([...triedAddresses], cost?.requirement);
780
942
  if (!nextPublisher) {
781
943
  this.log.error(
782
944
  `All available publishers exhausted (tried ${triedAddresses.length}), failed to publish bundled transactions`,
@@ -791,6 +953,21 @@ export class SequencerPublisher implements Disposable {
791
953
  }
792
954
  }
793
955
 
956
+ /** Throws if the publisher cannot afford the bundle, so the rotation loop moves on to another publisher. */
957
+ private async assertCanAfford(publisher: L1TxUtils, cost: BundleCost): Promise<void> {
958
+ const { affordable, balance } = await this.checkAffordable(publisher, cost);
959
+ if (!affordable) {
960
+ this.log.warn(`Publisher cannot afford the bundle`, {
961
+ publisher: publisher.getSenderAddress().toString(),
962
+ balance,
963
+ required: cost.required,
964
+ gasLimit: cost.requirement.gasLimit,
965
+ blobCount: cost.requirement.blobCount,
966
+ });
967
+ throw new BundleUnaffordableError(publisher.getSenderAddress(), balance, cost);
968
+ }
969
+ }
970
+
794
971
  /** Backs up an on-chain revert failure to the failed tx store. */
795
972
  private backupRevertFailure(
796
973
  requests: RequestWithExpiry[],
@@ -1,13 +1,15 @@
1
1
  import { BatchedBlob, Blob, getEthBlobEvaluationInputs, getPrefixedEthBlobCommitments } from '@aztec-labs/blob-lib';
2
+ import { getEnv } from '@aztec-labs/foundation/config/env';
2
3
  import { Fr } from '@aztec-labs/foundation/curves/bn254';
3
4
  import { EthAddress } from '@aztec-labs/foundation/eth-address';
4
5
  import { getL1FixturePath } from '@aztec-labs/foundation/testing/files';
5
6
  import { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
6
7
  import { L2Block } from '@aztec-labs/stdlib/block';
7
8
  import { CheckpointHeader } from '@aztec-labs/stdlib/rollup';
9
+ import { Buffer } from 'buffer';
8
10
  import { writeFile } from 'fs/promises';
9
11
 
10
- const AZTEC_GENERATE_TEST_DATA = !!process.env.AZTEC_GENERATE_TEST_DATA;
12
+ const AZTEC_GENERATE_TEST_DATA = !!getEnv().AZTEC_GENERATE_TEST_DATA;
11
13
 
12
14
  /**
13
15
  * Creates a json object that can be used to test the solidity contract.
@@ -0,0 +1,123 @@
1
+ import type { EpochCache } from '@aztec-labs/epoch-cache';
2
+ import type { EpochNumber, SlotNumber } from '@aztec-labs/foundation/branded-types';
3
+ import { randomInt } from '@aztec-labs/foundation/crypto/random';
4
+ import {
5
+ flipSignature,
6
+ generateRecoverableSignature,
7
+ generateUnrecoverableSignature,
8
+ } from '@aztec-labs/foundation/crypto/secp256k1-signer';
9
+ import type { EthAddress } from '@aztec-labs/foundation/eth-address';
10
+ import type { Logger } from '@aztec-labs/foundation/log';
11
+ import { unfreeze } from '@aztec-labs/foundation/types';
12
+ import {
13
+ type CommitteeAttestation,
14
+ CommitteeAttestationsAndSigners,
15
+ MaliciousCommitteeAttestationsAndSigners,
16
+ MaliciousYParityCommitteeAttestationsAndSigners,
17
+ } from '@aztec-labs/stdlib/block';
18
+ import type { SequencerConfig } from '@aztec-labs/stdlib/interfaces/server';
19
+ import type { CoordinationSignatureContext } from '@aztec-labs/stdlib/p2p';
20
+
21
+ /** The test-only sequencer flags that make the proposer publish deliberately broken attestations. */
22
+ export type AttestationManipulationConfig = Pick<
23
+ SequencerConfig,
24
+ | 'injectFakeAttestation'
25
+ | 'injectHighSValueAttestation'
26
+ | 'injectUnrecoverableSignatureAttestation'
27
+ | 'injectYParityAttestation'
28
+ | 'shuffleAttestationOrdering'
29
+ >;
30
+
31
+ /** Whether any test-only attestation attack is configured. */
32
+ export function hasAttestationManipulation(config: AttestationManipulationConfig): boolean {
33
+ return !!(
34
+ config.injectFakeAttestation ||
35
+ config.injectHighSValueAttestation ||
36
+ config.injectUnrecoverableSignatureAttestation ||
37
+ config.injectYParityAttestation ||
38
+ config.shuffleAttestationOrdering
39
+ );
40
+ }
41
+
42
+ /** Breaks the attestations before publishing based on attack configs. */
43
+ export function manipulateAttestations(input: {
44
+ config: AttestationManipulationConfig;
45
+ epochCache: Pick<EpochCache, 'computeProposerIndex'>;
46
+ signatureContext: CoordinationSignatureContext;
47
+ log: Logger;
48
+ slotNumber: SlotNumber;
49
+ epoch: EpochNumber;
50
+ seed: bigint;
51
+ committee: EthAddress[];
52
+ attestations: CommitteeAttestation[];
53
+ }): CommitteeAttestationsAndSigners {
54
+ const { config, epochCache, signatureContext, log, slotNumber, epoch, seed, committee, attestations } = input;
55
+
56
+ // Compute the proposer index in the committee, since we dont want to tweak it.
57
+ // Otherwise, the L1 rollup contract will reject the block outright.
58
+ const proposerIndex = Number(epochCache.computeProposerIndex(slotNumber, epoch, seed, BigInt(committee.length)));
59
+
60
+ if (
61
+ config.injectFakeAttestation ||
62
+ config.injectHighSValueAttestation ||
63
+ config.injectUnrecoverableSignatureAttestation
64
+ ) {
65
+ // Find non-empty attestations that are not from the proposer
66
+ const nonProposerIndices: number[] = [];
67
+ for (let i = 0; i < attestations.length; i++) {
68
+ if (!attestations[i].signature.isEmpty() && i !== proposerIndex) {
69
+ nonProposerIndices.push(i);
70
+ }
71
+ }
72
+ if (nonProposerIndices.length > 0) {
73
+ const targetIndex = nonProposerIndices[randomInt(nonProposerIndices.length)];
74
+ if (config.injectHighSValueAttestation) {
75
+ log.warn(`Injecting high-s value attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
76
+ unfreeze(attestations[targetIndex]).signature = flipSignature(attestations[targetIndex].signature);
77
+ } else if (config.injectUnrecoverableSignatureAttestation) {
78
+ log.warn(
79
+ `Injecting unrecoverable signature attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`,
80
+ );
81
+ unfreeze(attestations[targetIndex]).signature = generateUnrecoverableSignature();
82
+ } else {
83
+ log.warn(`Injecting fake attestation in checkpoint for slot ${slotNumber} at index ${targetIndex}`);
84
+ unfreeze(attestations[targetIndex]).signature = generateRecoverableSignature();
85
+ }
86
+ }
87
+ return new CommitteeAttestationsAndSigners(attestations, signatureContext);
88
+ }
89
+
90
+ if (config.injectYParityAttestation) {
91
+ // Force every non-proposer signed slot's recovery byte to yParity (v ∈ {0, 1}) form in the packed L1
92
+ // tuple, after packAttestations has canonicalized it. The proposer's own slot is left canonical so
93
+ // propose() still passes verifyProposer. Models a malicious proposer landing a checkpoint L1 accepts
94
+ // but that can never be proven (ECDSA.recover rejects v ∉ {27, 28}).
95
+ log.warn(`Injecting yParity attestations in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
96
+ return new MaliciousYParityCommitteeAttestationsAndSigners(attestations, proposerIndex, signatureContext);
97
+ }
98
+
99
+ if (config.shuffleAttestationOrdering) {
100
+ log.warn(`Shuffling attestation ordering in checkpoint for slot ${slotNumber} (proposer #${proposerIndex})`);
101
+
102
+ const shuffled = [...attestations];
103
+
104
+ // Find two non-proposer positions that both have non-empty signatures to swap.
105
+ // This ensures the bitmap doesn't change, so the MaliciousCommitteeAttestationsAndSigners
106
+ // signers array stays correctly aligned with L1's committee reconstruction.
107
+ const swappable: number[] = [];
108
+ for (let k = 0; k < shuffled.length; k++) {
109
+ if (!shuffled[k].signature.isEmpty() && k !== proposerIndex) {
110
+ swappable.push(k);
111
+ }
112
+ }
113
+ if (swappable.length >= 2) {
114
+ const [i, j] = [swappable[0], swappable[1]];
115
+ [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
116
+ }
117
+
118
+ const signers = new CommitteeAttestationsAndSigners(attestations, signatureContext).getSigners();
119
+ return new MaliciousCommitteeAttestationsAndSigners(shuffled, signers, signatureContext);
120
+ }
121
+
122
+ return new CommitteeAttestationsAndSigners(attestations, signatureContext);
123
+ }
@@ -23,6 +23,8 @@ import {
23
23
 
24
24
  import { type SequencerClientConfig, getPublisherConfigFromSequencerConfig } from '../../config.js';
25
25
  import type { GlobalVariableBuilder } from '../../global_variable_builder/global_builder.js';
26
+ import { PROPOSE_REFERENCE_SEND } from '../../publisher/gas_constants.js';
27
+ import { PublisherManagerMetrics } from '../../publisher/publisher-manager-metrics.js';
26
28
  import { SequencerPublisherFactory } from '../../publisher/sequencer-publisher-factory.js';
27
29
  import { AutomineSequencer } from './automine_sequencer.js';
28
30
 
@@ -93,6 +95,8 @@ export async function createAutomineSequencer({
93
95
  const publisherManager = new PublisherManager(l1TxUtils, getPublisherConfigFromSequencerConfig(config), {
94
96
  bindings: log.getBindings(),
95
97
  funder: funderL1TxUtils,
98
+ metrics: new PublisherManagerMetrics(telemetry, 'sequencer'),
99
+ referenceSend: config.fishermanMode ? undefined : PROPOSE_REFERENCE_SEND,
96
100
  });
97
101
  const governanceProposerContract = new GovernanceProposerContract(
98
102
  publicClient,