@aztec/aztec-node 0.0.1-commit.9ef841308 → 0.0.1-commit.a4600f49

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 (71) hide show
  1. package/dest/aztec-node/block_response_helpers.d.ts +25 -0
  2. package/dest/aztec-node/block_response_helpers.d.ts.map +1 -0
  3. package/dest/aztec-node/block_response_helpers.js +112 -0
  4. package/dest/aztec-node/config.d.ts +16 -4
  5. package/dest/aztec-node/config.d.ts.map +1 -1
  6. package/dest/aztec-node/config.js +15 -5
  7. package/dest/aztec-node/node_public_calls_simulator.d.ts +97 -0
  8. package/dest/aztec-node/node_public_calls_simulator.d.ts.map +1 -0
  9. package/dest/aztec-node/node_public_calls_simulator.js +351 -0
  10. package/dest/aztec-node/public_data_overrides.d.ts +13 -0
  11. package/dest/aztec-node/public_data_overrides.d.ts.map +1 -0
  12. package/dest/aztec-node/public_data_overrides.js +21 -0
  13. package/dest/aztec-node/register_node_rpc_handlers.d.ts +10 -0
  14. package/dest/aztec-node/register_node_rpc_handlers.d.ts.map +1 -0
  15. package/dest/aztec-node/register_node_rpc_handlers.js +31 -0
  16. package/dest/aztec-node/server.d.ts +128 -133
  17. package/dest/aztec-node/server.d.ts.map +1 -1
  18. package/dest/aztec-node/server.js +376 -850
  19. package/dest/bin/index.js +15 -10
  20. package/dest/factory.d.ts +33 -0
  21. package/dest/factory.d.ts.map +1 -0
  22. package/dest/factory.js +523 -0
  23. package/dest/index.d.ts +3 -1
  24. package/dest/index.d.ts.map +1 -1
  25. package/dest/index.js +2 -0
  26. package/dest/modules/block_parameter.d.ts +25 -0
  27. package/dest/modules/block_parameter.d.ts.map +1 -0
  28. package/dest/modules/block_parameter.js +100 -0
  29. package/dest/modules/node_block_provider.d.ts +19 -0
  30. package/dest/modules/node_block_provider.d.ts.map +1 -0
  31. package/dest/modules/node_block_provider.js +112 -0
  32. package/dest/modules/node_tx_receipt.d.ts +24 -0
  33. package/dest/modules/node_tx_receipt.d.ts.map +1 -0
  34. package/dest/modules/node_tx_receipt.js +70 -0
  35. package/dest/modules/node_world_state_queries.d.ts +65 -0
  36. package/dest/modules/node_world_state_queries.d.ts.map +1 -0
  37. package/dest/modules/node_world_state_queries.js +272 -0
  38. package/dest/sentinel/config.d.ts +3 -2
  39. package/dest/sentinel/config.d.ts.map +1 -1
  40. package/dest/sentinel/config.js +15 -5
  41. package/dest/sentinel/factory.d.ts +5 -3
  42. package/dest/sentinel/factory.d.ts.map +1 -1
  43. package/dest/sentinel/factory.js +12 -5
  44. package/dest/sentinel/sentinel.d.ts +145 -21
  45. package/dest/sentinel/sentinel.d.ts.map +1 -1
  46. package/dest/sentinel/sentinel.js +226 -104
  47. package/dest/sentinel/store.d.ts +8 -8
  48. package/dest/sentinel/store.d.ts.map +1 -1
  49. package/dest/sentinel/store.js +25 -17
  50. package/dest/test/index.d.ts +3 -3
  51. package/dest/test/index.d.ts.map +1 -1
  52. package/package.json +28 -26
  53. package/src/aztec-node/block_response_helpers.ts +161 -0
  54. package/src/aztec-node/config.ts +30 -7
  55. package/src/aztec-node/node_public_calls_simulator.ts +394 -0
  56. package/src/aztec-node/public_data_overrides.ts +35 -0
  57. package/src/aztec-node/register_node_rpc_handlers.ts +29 -0
  58. package/src/aztec-node/server.ts +507 -1094
  59. package/src/bin/index.ts +19 -12
  60. package/src/factory.ts +688 -0
  61. package/src/index.ts +2 -0
  62. package/src/modules/block_parameter.ts +93 -0
  63. package/src/modules/node_block_provider.ts +149 -0
  64. package/src/modules/node_tx_receipt.ts +115 -0
  65. package/src/modules/node_world_state_queries.ts +374 -0
  66. package/src/sentinel/README.md +103 -0
  67. package/src/sentinel/config.ts +18 -6
  68. package/src/sentinel/factory.ts +21 -6
  69. package/src/sentinel/sentinel.ts +276 -129
  70. package/src/sentinel/store.ts +26 -18
  71. package/src/test/index.ts +2 -2
@@ -1,57 +1,49 @@
1
- import { Archiver, createArchiver } from '@aztec/archiver';
1
+ import { Archiver } from '@aztec/archiver';
2
2
  import { BBCircuitVerifier, BatchChonkVerifier, QueuedIVCVerifier } from '@aztec/bb-prover';
3
3
  import { TestCircuitVerifier } from '@aztec/bb-prover/test';
4
- import { type BlobClientInterface, createBlobClientWithFileStores } from '@aztec/blob-client/client';
5
- import { Blob } from '@aztec/blob-lib';
4
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
6
5
  import { ARCHIVE_HEIGHT, type L1_TO_L2_MSG_TREE_HEIGHT, type NOTE_HASH_TREE_HEIGHT } from '@aztec/constants';
7
- import { EpochCache, type EpochCacheInterface } from '@aztec/epoch-cache';
8
- import { createEthereumChain } from '@aztec/ethereum/chain';
9
- import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
10
- import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
11
- import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
12
- import type { L1TxUtils } from '@aztec/ethereum/l1-tx-utils';
13
- import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
14
- import { chunkBy, compactArray, pick, unique } from '@aztec/foundation/collection';
6
+ import type { EpochCacheInterface } from '@aztec/epoch-cache';
7
+ import { RollupContract } from '@aztec/ethereum/contracts';
8
+ import { type L1ContractAddresses, pickL1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
9
+ import {
10
+ BlockNumber,
11
+ CheckpointNumber,
12
+ type CheckpointProposalHash,
13
+ EpochNumber,
14
+ SlotNumber,
15
+ } from '@aztec/foundation/branded-types';
16
+ import { compactArray, pick, unique } from '@aztec/foundation/collection';
15
17
  import { Fr } from '@aztec/foundation/curves/bn254';
16
18
  import { EthAddress } from '@aztec/foundation/eth-address';
17
19
  import { BadRequestError } from '@aztec/foundation/json-rpc';
18
20
  import { type Logger, createLogger } from '@aztec/foundation/log';
21
+ import { retryUntil } from '@aztec/foundation/retry';
19
22
  import { count } from '@aztec/foundation/string';
20
- import { DateProvider, Timer } from '@aztec/foundation/timer';
23
+ import { Timer } from '@aztec/foundation/timer';
21
24
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
22
- import { type KeyStore, KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
23
- import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
24
- import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
25
- import {
26
- type P2P,
27
- type P2PClientDeps,
28
- createP2PClient,
29
- createTxValidatorForAcceptingTxsOverRPC,
30
- getDefaultAllowedSetupFunctions,
31
- } from '@aztec/p2p';
25
+ import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
26
+ import { uploadSnapshot } from '@aztec/node-lib/actions';
27
+ import { type P2P, createTxValidatorForAcceptingTxsOverRPC, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
32
28
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
33
- import { type ProverNode, type ProverNodeDeps, createProverNode } from '@aztec/prover-node';
34
- import { createKeyStoreForProver } from '@aztec/prover-node/config';
35
- import { GlobalVariableBuilder, SequencerClient, type SequencerPublisher } from '@aztec/sequencer-client';
36
- import { PublicProcessorFactory } from '@aztec/simulator/server';
37
- import {
38
- AttestationsBlockWatcher,
39
- EpochPruneWatcher,
40
- type SlasherClientInterface,
41
- type Watcher,
42
- createSlasher,
43
- } from '@aztec/slasher';
44
- import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
29
+ import type { ProverNode } from '@aztec/prover-node';
30
+ import { SequencerClient } from '@aztec/sequencer-client';
31
+ import { AutomineSequencer } from '@aztec/sequencer-client/automine';
32
+ import type { AvmSimulator } from '@aztec/simulator/server';
33
+ import type { SlasherClientInterface } from '@aztec/slasher';
34
+ import { STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS } from '@aztec/standard-contracts/multi-call-entrypoint';
45
35
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
46
36
  import {
47
37
  type BlockData,
48
38
  BlockHash,
49
39
  type BlockParameter,
40
+ type CheckpointsQuery,
50
41
  type DataInBlock,
51
- L2Block,
52
42
  type L2BlockSource,
43
+ type L2BlockTag,
44
+ type L2Tips,
45
+ inspectBlockParameter,
53
46
  } from '@aztec/stdlib/block';
54
- import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
55
47
  import type {
56
48
  ContractClassPublic,
57
49
  ContractDataSource,
@@ -59,16 +51,25 @@ import type {
59
51
  NodeInfo,
60
52
  ProtocolContractAddresses,
61
53
  } from '@aztec/stdlib/contract';
62
- import { GasFees } from '@aztec/stdlib/gas';
63
- import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
64
- import {
65
- type AztecNode,
66
- type AztecNodeAdmin,
67
- type AztecNodeAdminConfig,
68
- AztecNodeAdminConfigSchema,
69
- type GetContractClassLogsResponse,
70
- type GetPublicLogsResponse,
54
+ import type { L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
55
+ import { GasFees, type ManaUsageEstimate, getNetworkTxGasLimits } from '@aztec/stdlib/gas';
56
+ import type {
57
+ AztecNode,
58
+ AztecNodeAdmin,
59
+ AztecNodeAdminConfig,
60
+ AztecNodeDebug,
61
+ BlockIncludeOptions,
62
+ BlockResponse,
63
+ BlocksIncludeOptions,
64
+ CheckpointIncludeOptions,
65
+ CheckpointParameter,
66
+ CheckpointResponse,
67
+ CheckpointTag,
68
+ GetTxByHashOptions,
69
+ PeerInfo,
70
+ ProposalsForSlot,
71
71
  } from '@aztec/stdlib/interfaces/client';
72
+ import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
72
73
  import {
73
74
  type AllowedElement,
74
75
  type ClientProtocolCircuitVerifier,
@@ -78,24 +79,24 @@ import {
78
79
  type WorldStateSynchronizer,
79
80
  tryStop,
80
81
  } from '@aztec/stdlib/interfaces/server';
81
- import type { DebugLogStore, LogFilter, SiloedTag, Tag, TxScopedL2Log } from '@aztec/stdlib/logs';
82
- import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
83
- import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
84
- import type { Offense, SlashPayloadRound } from '@aztec/stdlib/slashing';
85
- import type { NullifierLeafPreimage, PublicDataTreeLeaf, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
82
+ import type { DebugLogStore, LogResult, PrivateLogsQuery, PublicLogsQuery } from '@aztec/stdlib/logs';
83
+ import { NullDebugLogStore } from '@aztec/stdlib/logs';
84
+ import type { L1ToL2MessageSource, L2ToL1MembershipWitness } from '@aztec/stdlib/messaging';
85
+ import type { CheckpointAttestation } from '@aztec/stdlib/p2p';
86
+ import type { Offense } from '@aztec/stdlib/slashing';
86
87
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
87
88
  import {
88
- type BlockHeader,
89
+ type FeeProvider,
90
+ type GetTxReceiptOptions,
89
91
  type GlobalVariableBuilder as GlobalVariableBuilderInterface,
90
92
  type IndexedTxEffect,
91
93
  PublicSimulationOutput,
94
+ type SimulationOverrides,
92
95
  Tx,
93
96
  type TxHash,
94
- TxReceipt,
95
- TxStatus,
97
+ type TxReceipt,
96
98
  type TxValidationResult,
97
99
  } from '@aztec/stdlib/tx';
98
- import { getPackageVersion } from '@aztec/stdlib/update-checker';
99
100
  import type { SingleValidatorStats, ValidatorsStats } from '@aztec/stdlib/validators';
100
101
  import {
101
102
  Attributes,
@@ -105,73 +106,175 @@ import {
105
106
  getTelemetryClient,
106
107
  trackSpan,
107
108
  } from '@aztec/telemetry-client';
108
- import {
109
- FullNodeCheckpointsBuilder as CheckpointsBuilder,
110
- FullNodeCheckpointsBuilder,
111
- NodeKeystoreAdapter,
112
- ValidatorClient,
113
- createProposalHandler,
114
- createValidatorClient,
115
- } from '@aztec/validator-client';
116
- import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
117
- import { createWorldStateSynchronizer } from '@aztec/world-state';
118
-
119
- import { createPublicClient } from 'viem';
120
-
121
- import { createSentinel } from '../sentinel/factory.js';
109
+ import { NodeKeystoreAdapter, ValidatorClient } from '@aztec/validator-client';
110
+
111
+ import { NodeBlockProvider } from '../modules/node_block_provider.js';
112
+ import { NodeTxReceiptBuilder } from '../modules/node_tx_receipt.js';
113
+ import { NodeWorldStateQueries } from '../modules/node_world_state_queries.js';
122
114
  import { Sentinel } from '../sentinel/sentinel.js';
123
- import { type AztecNodeConfig, createKeyStoreForValidator } from './config.js';
115
+ import type { AztecNodeConfig } from './config.js';
124
116
  import { NodeMetrics } from './node_metrics.js';
117
+ import { NodePublicCallsSimulator } from './node_public_calls_simulator.js';
118
+
119
+ /**
120
+ * Fully-constructed collaborators and settings an {@link AztecNodeService} owns. Built by `createAztecNodeService`
121
+ * (see `factory.ts`); passed as a single object so call sites name each dependency instead of relying on
122
+ * positional order.
123
+ */
124
+ export interface AztecNodeServiceDeps {
125
+ config: AztecNodeConfig;
126
+ p2pClient: P2P;
127
+ blockSource: L2BlockSource & Partial<Service>;
128
+ logsSource: L2LogsSource;
129
+ contractDataSource: ContractDataSource;
130
+ l1ToL2MessageSource: L1ToL2MessageSource;
131
+ worldStateSynchronizer: WorldStateSynchronizer;
132
+ sequencer: SequencerClient | undefined;
133
+ proverNode: ProverNode | undefined;
134
+ slasherClient: SlasherClientInterface | undefined;
135
+ validatorsSentinel: Sentinel | undefined;
136
+ stopStartedWatchers: () => Promise<void>;
137
+ l1ChainId: number;
138
+ version: number;
139
+ globalVariableBuilder: GlobalVariableBuilderInterface;
140
+ rollupContract: RollupContract | undefined;
141
+ feeProvider: FeeProvider;
142
+ epochCache: EpochCacheInterface;
143
+ packageVersion: string;
144
+ peerProofVerifier: ClientProtocolCircuitVerifier;
145
+ rpcProofVerifier: ClientProtocolCircuitVerifier;
146
+ telemetry?: TelemetryClient;
147
+ log?: Logger;
148
+ blobClient?: BlobClientInterface;
149
+ validatorClient?: ValidatorClient;
150
+ keyStoreManager?: KeystoreManager;
151
+ debugLogStore?: DebugLogStore;
152
+ automineSequencer?: AutomineSequencer;
153
+ // AVM execution backend for public simulation. Wired in production (factory.ts); absent in unit/TXE nodes
154
+ // that don't drive public execution, hence optional and asserted at the simulation call site. Owned by the
155
+ // node (disposed on stop), so it must be disposable — a spawned process pool + CDB IPC server.
156
+ avmSimulator?: AvmSimulator & AsyncDisposable;
157
+ }
125
158
 
126
159
  /**
127
160
  * The aztec node.
128
161
  */
129
- export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
162
+ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDebug, Traceable {
130
163
  private metrics: NodeMetrics;
131
- private initialHeaderHashPromise: Promise<BlockHash> | undefined = undefined;
132
-
133
164
  // Prevent two snapshot operations to happen simultaneously
134
165
  private isUploadingSnapshot = false;
166
+ // Saved minTxsPerBlock used by `pauseSequencer` to restore production-sequencer config on resume.
167
+ private sequencerPausedMinTxsPerBlock: number | undefined;
168
+ private readonly nodePublicCallsSimulator: NodePublicCallsSimulator;
169
+ private readonly worldStateQueries: NodeWorldStateQueries;
170
+ private readonly blockProvider: NodeBlockProvider;
171
+ private readonly txReceiptBuilder: NodeTxReceiptBuilder;
135
172
 
136
173
  public readonly tracer: Tracer;
137
174
 
138
- constructor(
139
- protected config: AztecNodeConfig,
140
- protected readonly p2pClient: P2P,
141
- protected readonly blockSource: L2BlockSource & Partial<Service>,
142
- protected readonly logsSource: L2LogsSource,
143
- protected readonly contractDataSource: ContractDataSource,
144
- protected readonly l1ToL2MessageSource: L1ToL2MessageSource,
145
- protected readonly worldStateSynchronizer: WorldStateSynchronizer,
146
- protected readonly sequencer: SequencerClient | undefined,
147
- protected readonly proverNode: ProverNode | undefined,
148
- protected readonly slasherClient: SlasherClientInterface | undefined,
149
- protected readonly validatorsSentinel: Sentinel | undefined,
150
- protected readonly epochPruneWatcher: EpochPruneWatcher | undefined,
151
- protected readonly l1ChainId: number,
152
- protected readonly version: number,
153
- protected readonly globalVariableBuilder: GlobalVariableBuilderInterface,
154
- protected readonly epochCache: EpochCacheInterface,
155
- protected readonly packageVersion: string,
156
- private peerProofVerifier: ClientProtocolCircuitVerifier,
157
- private rpcProofVerifier: ClientProtocolCircuitVerifier,
158
- private telemetry: TelemetryClient = getTelemetryClient(),
159
- private log = createLogger('node'),
160
- private blobClient?: BlobClientInterface,
161
- private validatorClient?: ValidatorClient,
162
- private keyStoreManager?: KeystoreManager,
163
- private debugLogStore: DebugLogStore = new NullDebugLogStore(),
164
- ) {
165
- this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
166
- this.tracer = telemetry.getTracer('AztecNodeService');
175
+ protected config: AztecNodeConfig;
176
+ protected readonly p2pClient: P2P;
177
+ protected readonly blockSource: L2BlockSource & Partial<Service>;
178
+ protected readonly logsSource: L2LogsSource;
179
+ protected readonly contractDataSource: ContractDataSource;
180
+ protected readonly l1ToL2MessageSource: L1ToL2MessageSource;
181
+ protected readonly worldStateSynchronizer: WorldStateSynchronizer;
182
+ protected readonly sequencer: SequencerClient | undefined;
183
+ protected readonly proverNode: ProverNode | undefined;
184
+ protected readonly slasherClient: SlasherClientInterface | undefined;
185
+ protected readonly validatorsSentinel: Sentinel | undefined;
186
+ private readonly stopStartedWatchers: () => Promise<void>;
187
+ protected readonly l1ChainId: number;
188
+ protected readonly version: number;
189
+ protected readonly globalVariableBuilder: GlobalVariableBuilderInterface;
190
+ protected readonly rollupContract: RollupContract | undefined;
191
+ protected readonly feeProvider: FeeProvider;
192
+ protected readonly epochCache: EpochCacheInterface;
193
+ protected readonly packageVersion: string;
194
+ private peerProofVerifier: ClientProtocolCircuitVerifier;
195
+ private rpcProofVerifier: ClientProtocolCircuitVerifier;
196
+ private telemetry: TelemetryClient;
197
+ private log: Logger;
198
+ private blobClient?: BlobClientInterface;
199
+ private validatorClient?: ValidatorClient;
200
+ private keyStoreManager?: KeystoreManager;
201
+ private debugLogStore: DebugLogStore;
202
+ private readonly automineSequencer?: AutomineSequencer;
203
+ private readonly avmSimulator?: AvmSimulator & AsyncDisposable;
204
+
205
+ constructor(deps: AztecNodeServiceDeps) {
206
+ this.config = deps.config;
207
+ this.p2pClient = deps.p2pClient;
208
+ this.blockSource = deps.blockSource;
209
+ this.logsSource = deps.logsSource;
210
+ this.contractDataSource = deps.contractDataSource;
211
+ this.l1ToL2MessageSource = deps.l1ToL2MessageSource;
212
+ this.worldStateSynchronizer = deps.worldStateSynchronizer;
213
+ this.sequencer = deps.sequencer;
214
+ this.proverNode = deps.proverNode;
215
+ this.slasherClient = deps.slasherClient;
216
+ this.validatorsSentinel = deps.validatorsSentinel;
217
+ this.stopStartedWatchers = deps.stopStartedWatchers;
218
+ this.l1ChainId = deps.l1ChainId;
219
+ this.version = deps.version;
220
+ this.globalVariableBuilder = deps.globalVariableBuilder;
221
+ this.rollupContract = deps.rollupContract;
222
+ this.feeProvider = deps.feeProvider;
223
+ this.epochCache = deps.epochCache;
224
+ this.packageVersion = deps.packageVersion;
225
+ this.peerProofVerifier = deps.peerProofVerifier;
226
+ this.rpcProofVerifier = deps.rpcProofVerifier;
227
+ this.telemetry = deps.telemetry ?? getTelemetryClient();
228
+ this.log = deps.log ?? createLogger('node');
229
+ this.blobClient = deps.blobClient;
230
+ this.validatorClient = deps.validatorClient;
231
+ this.keyStoreManager = deps.keyStoreManager;
232
+ this.debugLogStore = deps.debugLogStore ?? new NullDebugLogStore();
233
+ this.automineSequencer = deps.automineSequencer;
234
+ this.avmSimulator = deps.avmSimulator;
235
+
236
+ this.metrics = new NodeMetrics(this.telemetry, 'AztecNodeService');
237
+ this.tracer = this.telemetry.getTracer('AztecNodeService');
238
+
239
+ // The node never represents a proposer's payout addresses, so the simulator zeroes coinbase and
240
+ // fee recipient. The signature context only needs chain id + rollup address (see signature_utils).
241
+ this.nodePublicCallsSimulator = new NodePublicCallsSimulator({
242
+ blockSource: this.blockSource,
243
+ worldStateSynchronizer: this.worldStateSynchronizer,
244
+ l1ToL2MessageSource: this.l1ToL2MessageSource,
245
+ contractDataSource: this.contractDataSource,
246
+ globalVariableBuilder: this.globalVariableBuilder,
247
+ rollupContract: this.rollupContract,
248
+ epochCache: this.epochCache,
249
+ signatureContext: { chainId: this.l1ChainId, rollupAddress: this.config.rollupAddress },
250
+ config: this.config,
251
+ avmSimulator: this.avmSimulator,
252
+ telemetry: this.telemetry,
253
+ log: this.log.createChild('public-calls-simulator'),
254
+ });
255
+
256
+ this.worldStateQueries = new NodeWorldStateQueries({
257
+ worldStateSynchronizer: this.worldStateSynchronizer,
258
+ blockSource: this.blockSource,
259
+ l1ToL2MessageSource: this.l1ToL2MessageSource,
260
+ log: this.log.createChild('world-state-queries'),
261
+ });
262
+
263
+ this.blockProvider = new NodeBlockProvider(this.blockSource);
264
+
265
+ this.txReceiptBuilder = new NodeTxReceiptBuilder({
266
+ p2pClient: this.p2pClient,
267
+ blockSource: this.blockSource,
268
+ debugLogStore: this.debugLogStore,
269
+ });
167
270
 
168
271
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
169
- this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
272
+ this.log.info(`Aztec Node started on chain 0x${this.l1ChainId.toString(16)}`, pickL1ContractAddresses(this.config));
170
273
 
171
- // A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
274
+ // A defensive check that protects us against introducing a bug in the complex node creation flow. We must
172
275
  // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
173
276
  // memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
174
- if (debugLogStore.isEnabled && config.realProofs) {
277
+ if (this.debugLogStore.isEnabled && this.config.realProofs) {
175
278
  throw new Error('debugLogStore should never be enabled when realProofs are set');
176
279
  }
177
280
  }
@@ -186,440 +289,82 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
186
289
  return status.syncSummary;
187
290
  }
188
291
 
189
- public getL2Tips() {
292
+ public getChainTips(): Promise<L2Tips> {
190
293
  return this.blockSource.getL2Tips();
191
294
  }
192
295
 
193
- /**
194
- * initializes the Aztec Node, wait for component to sync.
195
- * @param config - The configuration to be used by the aztec node.
196
- * @returns - A fully synced Aztec Node for use in development/testing.
197
- */
198
- public static async createAndSync(
199
- inputConfig: AztecNodeConfig,
200
- deps: {
201
- telemetry?: TelemetryClient;
202
- logger?: Logger;
203
- publisher?: SequencerPublisher;
204
- dateProvider?: DateProvider;
205
- p2pClientDeps?: P2PClientDeps;
206
- proverNodeDeps?: Partial<ProverNodeDeps>;
207
- slashingProtectionDb?: SlashingProtectionDatabase;
208
- } = {},
209
- options: {
210
- prefilledPublicData?: PublicDataTreeLeaf[];
211
- dontStartSequencer?: boolean;
212
- dontStartProverNode?: boolean;
213
- } = {},
214
- ): Promise<AztecNodeService> {
215
- const config = { ...inputConfig }; // Copy the config so we dont mutate the input object
216
- const log = deps.logger ?? createLogger('node');
217
- const packageVersion = getPackageVersion() ?? '';
218
- const telemetry = deps.telemetry ?? getTelemetryClient();
219
- const dateProvider = deps.dateProvider ?? new DateProvider();
220
- const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
221
-
222
- // Build a key store from file if given or from environment otherwise.
223
- // We keep the raw KeyStore available so we can merge with prover keys if enableProverNode is set.
224
- let keyStoreManager: KeystoreManager | undefined;
225
- const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
226
- if (keyStoreProvided) {
227
- const keyStores = loadKeystores(config.keyStoreDirectory!);
228
- keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
229
- } else {
230
- const rawKeyStores: KeyStore[] = [];
231
- const validatorKeyStore = createKeyStoreForValidator(config);
232
- if (validatorKeyStore) {
233
- rawKeyStores.push(validatorKeyStore);
234
- }
235
- if (config.enableProverNode) {
236
- const proverKeyStore = createKeyStoreForProver(config);
237
- if (proverKeyStore) {
238
- rawKeyStores.push(proverKeyStore);
239
- }
240
- }
241
- if (rawKeyStores.length > 0) {
242
- keyStoreManager = new KeystoreManager(
243
- rawKeyStores.length === 1 ? rawKeyStores[0] : mergeKeystores(rawKeyStores),
244
- );
245
- }
246
- }
247
-
248
- await keyStoreManager?.validateSigners();
249
-
250
- // If we are a validator, verify our configuration before doing too much more.
251
- if (!config.disableValidator) {
252
- if (keyStoreManager === undefined) {
253
- throw new Error('Failed to create key store, a requirement for running a validator');
254
- }
255
- if (!keyStoreProvided && process.env.NODE_ENV !== 'test') {
256
- log.warn("Keystore created from env: it's recommended to use a file-based key store for production");
257
- }
258
- ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
259
- }
260
-
261
- // validate that the actual chain id matches that specified in configuration
262
- if (config.l1ChainId !== ethereumChain.chainInfo.id) {
263
- throw new Error(
264
- `RPC URL configured for chain id ${ethereumChain.chainInfo.id} but expected id ${config.l1ChainId}`,
265
- );
266
- }
267
-
268
- const publicClient = createPublicClient({
269
- chain: ethereumChain.chainInfo,
270
- transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
271
- pollingInterval: config.viemPollingIntervalMS,
272
- });
273
-
274
- const l1ContractsAddresses = await RegistryContract.collectAddresses(
275
- publicClient,
276
- config.l1Contracts.registryAddress,
277
- config.rollupVersion ?? 'canonical',
278
- );
279
-
280
- // Overwrite the passed in vars.
281
- config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
282
-
283
- const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
284
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
285
- rollupContract.getL1GenesisTime(),
286
- rollupContract.getSlotDuration(),
287
- rollupContract.getVersion(),
288
- rollupContract.getManaLimit().then(Number),
289
- ] as const);
290
-
291
- config.rollupVersion ??= Number(rollupVersionFromRollup);
292
-
293
- if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
294
- log.warn(
295
- `Registry looked up and returned a rollup with version (${config.rollupVersion}), but this does not match with version detected from the rollup directly: (${rollupVersionFromRollup}).`,
296
- );
297
- }
298
-
299
- const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
300
-
301
- // attempt snapshot sync if possible
302
- await trySnapshotSync(config, log);
303
-
304
- const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, { dateProvider });
305
-
306
- const archiver = await createArchiver(
307
- config,
308
- { blobClient, epochCache, telemetry, dateProvider },
309
- { blockUntilSync: !config.skipArchiverInitialSync },
310
- );
311
-
312
- // now create the merkle trees and the world state synchronizer
313
- const worldStateSynchronizer = await createWorldStateSynchronizer(
314
- config,
315
- archiver,
316
- options.prefilledPublicData,
317
- telemetry,
318
- );
319
- const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
320
- let peerProofVerifier: ClientProtocolCircuitVerifier;
321
- let rpcProofVerifier: ClientProtocolCircuitVerifier;
322
- if (useRealVerifiers) {
323
- peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
324
- const rpcVerifier = await BBCircuitVerifier.new(config);
325
- rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
326
- } else {
327
- peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
328
- rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
329
- }
330
-
331
- let debugLogStore: DebugLogStore;
332
- if (!config.realProofs) {
333
- log.warn(`Aztec node is accepting fake proofs`);
334
-
335
- debugLogStore = new InMemoryDebugLogStore();
336
- log.info(
337
- 'Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served',
338
- );
339
- } else {
340
- debugLogStore = new NullDebugLogStore();
341
- }
342
-
343
- const proverOnly = config.enableProverNode && config.disableValidator;
344
- if (proverOnly) {
345
- log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
346
- }
347
-
348
- // create the tx pool and the p2p client, which will need the l2 block source
349
- const p2pClient = await createP2PClient(
350
- config,
351
- archiver,
352
- peerProofVerifier,
353
- worldStateSynchronizer,
354
- epochCache,
355
- packageVersion,
356
- dateProvider,
357
- telemetry,
358
- deps.p2pClientDeps,
359
- );
360
-
361
- // We'll accumulate sentinel watchers here
362
- const watchers: Watcher[] = [];
363
-
364
- // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
365
- // Override maxTxsPerCheckpoint with the validator-specific limit if set.
366
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
367
- {
368
- ...config,
369
- l1GenesisTime,
370
- slotDuration: Number(slotDuration),
371
- rollupManaLimit,
372
- maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint,
373
- },
374
- worldStateSynchronizer,
375
- archiver,
376
- dateProvider,
377
- telemetry,
378
- );
379
-
380
- let validatorClient: ValidatorClient | undefined;
381
-
382
- if (!proverOnly) {
383
- // Create validator client if required
384
- validatorClient = await createValidatorClient(config, {
385
- checkpointsBuilder: validatorCheckpointsBuilder,
386
- worldState: worldStateSynchronizer,
387
- p2pClient,
388
- telemetry,
389
- dateProvider,
390
- epochCache,
391
- blockSource: archiver,
392
- l1ToL2MessageSource: archiver,
393
- keyStoreManager,
394
- blobClient,
395
- slashingProtectionDb: deps.slashingProtectionDb,
396
- });
397
-
398
- // If we have a validator client, register it as a source of offenses for the slasher,
399
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
400
- // like attestations or auths will fail.
401
- if (validatorClient) {
402
- watchers.push(validatorClient);
403
- if (!options.dontStartSequencer) {
404
- await validatorClient.registerHandlers();
405
- }
406
- }
407
- }
408
-
409
- // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
410
- // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
411
- // while non-reexecution is used for validating the proposals and collecting their txs.
412
- // Checkpoint proposals are handled if the blob client can upload blobs.
413
- if (!validatorClient) {
414
- const reexecute = !!config.alwaysReexecuteBlockProposals;
415
- log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
416
- createProposalHandler(config, {
417
- checkpointsBuilder: validatorCheckpointsBuilder,
418
- worldState: worldStateSynchronizer,
419
- epochCache,
420
- blockSource: archiver,
421
- l1ToL2MessageSource: archiver,
422
- p2pClient,
423
- blobClient,
424
- dateProvider,
425
- telemetry,
426
- }).register(p2pClient, reexecute);
427
- }
428
-
429
- // Start world state and wait for it to sync to the archiver.
430
- await worldStateSynchronizer.start();
296
+ public getL1Constants(): Promise<L1RollupConstants> {
297
+ return this.blockSource.getL1Constants();
298
+ }
431
299
 
432
- // Start p2p. Note that it depends on world state to be running.
433
- await p2pClient.start();
300
+ public getSyncedL2SlotNumber() {
301
+ return this.blockSource.getSyncedL2SlotNumber();
302
+ }
434
303
 
435
- let validatorsSentinel: Awaited<ReturnType<typeof createSentinel>> | undefined;
436
- let epochPruneWatcher: EpochPruneWatcher | undefined;
437
- let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
304
+ public getSyncedL2EpochNumber() {
305
+ return this.blockSource.getSyncedL2EpochNumber();
306
+ }
438
307
 
439
- if (!proverOnly) {
440
- validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
441
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
442
- watchers.push(validatorsSentinel);
443
- }
308
+ public getSyncedL1Timestamp() {
309
+ return this.blockSource.getL1Timestamp();
310
+ }
444
311
 
445
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
446
- epochPruneWatcher = new EpochPruneWatcher(
447
- archiver,
448
- archiver,
449
- epochCache,
450
- p2pClient.getTxProvider(),
451
- validatorCheckpointsBuilder,
452
- config,
453
- );
454
- watchers.push(epochPruneWatcher);
455
- }
312
+ public getCheckpointsData(query: CheckpointsQuery) {
313
+ return this.blockSource.getCheckpointsData(query);
314
+ }
456
315
 
457
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
458
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
459
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
460
- watchers.push(attestationsBlockWatcher);
461
- }
316
+ public async getBlockNumber(tip?: L2BlockTag): Promise<BlockNumber> {
317
+ if (tip === undefined || tip === 'proposed') {
318
+ return this.blockSource.getBlockNumber();
462
319
  }
463
-
464
- // Start p2p-related services once the archiver has completed sync
465
- void archiver
466
- .waitForInitialSync()
467
- .then(async () => {
468
- await p2pClient.start();
469
- await validatorsSentinel?.start();
470
- await epochPruneWatcher?.start();
471
- await attestationsBlockWatcher?.start();
472
- log.info(`All p2p services started`);
473
- })
474
- .catch(err => log.error('Failed to start p2p services after archiver sync', err));
475
-
476
- const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, {
477
- l1Contracts: config.l1Contracts,
478
- ethereumSlotDuration: config.ethereumSlotDuration,
479
- rollupVersion: BigInt(config.rollupVersion),
480
- l1GenesisTime,
481
- slotDuration: Number(slotDuration),
482
- });
483
-
484
- // Validator enabled, create/start relevant service
485
- let sequencer: SequencerClient | undefined;
486
- let slasherClient: SlasherClientInterface | undefined;
487
- if (!config.disableValidator && validatorClient) {
488
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
489
- // as they are executed when the node is selected as proposer.
490
- const validatorAddresses = keyStoreManager
491
- ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses()
492
- : [];
493
-
494
- slasherClient = await createSlasher(
495
- config,
496
- config.l1Contracts,
497
- getPublicClient(config),
498
- watchers,
499
- dateProvider,
500
- epochCache,
501
- validatorAddresses,
502
- undefined, // logger
503
- );
504
- await slasherClient.start();
505
-
506
- const l1TxUtils = config.sequencerPublisherForwarderAddress
507
- ? await createForwarderL1TxUtilsFromSigners(
508
- publicClient,
509
- keyStoreManager!.createAllValidatorPublisherSigners(),
510
- config.sequencerPublisherForwarderAddress,
511
- { ...config, scope: 'sequencer' },
512
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
513
- )
514
- : await createL1TxUtilsFromSigners(
515
- publicClient,
516
- keyStoreManager!.createAllValidatorPublisherSigners(),
517
- { ...config, scope: 'sequencer' },
518
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
519
- );
520
-
521
- // Create a funder L1TxUtils from the keystore funding account (if configured)
522
- const fundingSigner = keyStoreManager?.createFundingSigner();
523
- let funderL1TxUtils: L1TxUtils | undefined;
524
- if (fundingSigner) {
525
- const [funder] = await createL1TxUtilsFromSigners(
526
- publicClient,
527
- [fundingSigner],
528
- { ...config, scope: 'sequencer' },
529
- { telemetry, logger: log.createChild('l1-tx-utils:funder'), dateProvider },
530
- );
531
- funderL1TxUtils = funder;
532
- }
533
-
534
- // Create and start the sequencer client
535
- const checkpointsBuilder = new CheckpointsBuilder(
536
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration), rollupManaLimit },
537
- worldStateSynchronizer,
538
- archiver,
539
- dateProvider,
540
- telemetry,
541
- debugLogStore,
542
- );
543
-
544
- sequencer = await SequencerClient.new(config, {
545
- ...deps,
546
- epochCache,
547
- l1TxUtils,
548
- funderL1TxUtils,
549
- validatorClient,
550
- p2pClient,
551
- worldStateSynchronizer,
552
- slasherClient,
553
- checkpointsBuilder,
554
- l2BlockSource: archiver,
555
- l1ToL2MessageSource: archiver,
556
- telemetry,
557
- dateProvider,
558
- blobClient,
559
- nodeKeyStore: keyStoreManager!,
560
- globalVariableBuilder,
561
- });
320
+ return (await this.blockSource.getBlockNumber({ tag: tip })) ?? BlockNumber.ZERO;
321
+ }
322
+
323
+ public async getCheckpointNumber(tip?: CheckpointTag): Promise<CheckpointNumber> {
324
+ const tips = await this.blockSource.getL2Tips();
325
+ switch (tip) {
326
+ case undefined:
327
+ case 'checkpointed':
328
+ return tips.checkpointed.checkpoint.number;
329
+ case 'proven':
330
+ return tips.proven.checkpoint.number;
331
+ case 'finalized':
332
+ return tips.finalized.checkpoint.number;
562
333
  }
334
+ }
563
335
 
564
- if (!options.dontStartSequencer && sequencer) {
565
- await sequencer.start();
566
- log.verbose(`Sequencer started`);
567
- } else if (sequencer) {
568
- log.warn(`Sequencer created but not started`);
569
- }
336
+ public getBlock<Opts extends BlockIncludeOptions = {}>(
337
+ param: BlockParameter,
338
+ options: Opts = {} as Opts,
339
+ ): Promise<BlockResponse<Opts> | undefined> {
340
+ return this.blockProvider.getBlock(param, options);
341
+ }
570
342
 
571
- // Create prover node subsystem if enabled
572
- let proverNode: ProverNode | undefined;
573
- if (config.enableProverNode) {
574
- proverNode = await createProverNode(config, {
575
- ...deps.proverNodeDeps,
576
- telemetry,
577
- dateProvider,
578
- archiver,
579
- worldStateSynchronizer,
580
- p2pClient,
581
- epochCache,
582
- blobClient,
583
- keyStoreManager,
584
- });
343
+ public getBlockData(param: BlockParameter): Promise<BlockData | undefined> {
344
+ return this.blockProvider.getBlockData(param);
345
+ }
585
346
 
586
- if (!options.dontStartProverNode) {
587
- await proverNode.start();
588
- log.info(`Prover node subsystem started`);
589
- } else {
590
- log.info(`Prover node subsystem created but not started`);
591
- }
592
- }
347
+ public getBlocks<Opts extends BlocksIncludeOptions = {}>(
348
+ from: BlockNumber,
349
+ limit: number,
350
+ options: Opts = {} as Opts,
351
+ ): Promise<BlockResponse<Opts>[]> {
352
+ return this.blockProvider.getBlocks(from, limit, options);
353
+ }
593
354
 
594
- const node = new AztecNodeService(
595
- config,
596
- p2pClient,
597
- archiver,
598
- archiver,
599
- archiver,
600
- archiver,
601
- worldStateSynchronizer,
602
- sequencer,
603
- proverNode,
604
- slasherClient,
605
- validatorsSentinel,
606
- epochPruneWatcher,
607
- ethereumChain.chainInfo.id,
608
- config.rollupVersion,
609
- globalVariableBuilder,
610
- epochCache,
611
- packageVersion,
612
- peerProofVerifier,
613
- rpcProofVerifier,
614
- telemetry,
615
- log,
616
- blobClient,
617
- validatorClient,
618
- keyStoreManager,
619
- debugLogStore,
620
- );
355
+ public getCheckpoint<Opts extends CheckpointIncludeOptions = {}>(
356
+ param: CheckpointParameter,
357
+ options: Opts = {} as Opts,
358
+ ): Promise<CheckpointResponse<Opts> | undefined> {
359
+ return this.blockProvider.getCheckpoint(param, options);
360
+ }
621
361
 
622
- return node;
362
+ public getCheckpoints<Opts extends CheckpointIncludeOptions = {}>(
363
+ from: CheckpointNumber,
364
+ limit: number,
365
+ options: Opts = {} as Opts,
366
+ ): Promise<CheckpointResponse<Opts>[]> {
367
+ return this.blockProvider.getCheckpoints(from, limit, options);
623
368
  }
624
369
 
625
370
  /**
@@ -630,6 +375,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
630
375
  return this.sequencer;
631
376
  }
632
377
 
378
+ /** Test-only: returns the AutomineSequencer when wired via `useAutomineSequencer`. */
379
+ public getAutomineSequencer(): AutomineSequencer | undefined {
380
+ return this.automineSequencer;
381
+ }
382
+
633
383
  /** Returns the prover node subsystem, if enabled. */
634
384
  public getProverNode(): ProverNode | undefined {
635
385
  return this.proverNode;
@@ -652,7 +402,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
652
402
  * @returns - The currently deployed L1 contract addresses.
653
403
  */
654
404
  public getL1ContractAddresses(): Promise<L1ContractAddresses> {
655
- return Promise.resolve(this.config.l1Contracts);
405
+ return Promise.resolve(pickL1ContractAddresses(this.config));
656
406
  }
657
407
 
658
408
  public getEncodedEnr(): Promise<string | undefined> {
@@ -672,14 +422,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
672
422
  }
673
423
 
674
424
  public async getNodeInfo(): Promise<NodeInfo> {
675
- const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses] = await Promise.all([
676
- this.getNodeVersion(),
677
- this.getVersion(),
678
- this.getChainId(),
679
- this.getEncodedEnr(),
680
- this.getL1ContractAddresses(),
681
- this.getProtocolContractAddresses(),
682
- ]);
425
+ const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses, l1Constants] =
426
+ await Promise.all([
427
+ this.getNodeVersion(),
428
+ this.getVersion(),
429
+ this.getChainId(),
430
+ this.getEncodedEnr(),
431
+ this.getL1ContractAddresses(),
432
+ this.getProtocolContractAddresses(),
433
+ this.blockSource.getL1Constants(),
434
+ ]);
435
+
436
+ // Gas limits a single tx may declare on this network, derived from network-wide constants only (the
437
+ // timetable's blocks-per-checkpoint and the network-minimum per-block multipliers) — never this node's
438
+ // local caps or configured multipliers, which can make the node stricter at block-building time but
439
+ // cannot define what the network accepts for relay. Clients read txsLimits to set fallback gas limits.
440
+ const maxTxGas = getNetworkTxGasLimits(this.config, l1Constants);
683
441
 
684
442
  const nodeInfo: NodeInfo = {
685
443
  nodeVersion,
@@ -689,112 +447,29 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
689
447
  l1ContractAddresses: contractAddresses,
690
448
  protocolContractAddresses: protocolContractAddresses,
691
449
  realProofs: !!this.config.realProofs,
450
+ txsLimits: { gas: { daGas: maxTxGas.daGas, l2Gas: maxTxGas.l2Gas } },
692
451
  };
693
452
 
694
453
  return nodeInfo;
695
454
  }
696
455
 
697
- /**
698
- * Get a block specified by its block number, block hash, or 'latest'.
699
- * @param block - The block parameter (block number, block hash, or 'latest').
700
- * @returns The requested block.
701
- */
702
- public async getBlock(block: BlockParameter): Promise<L2Block | undefined> {
703
- if (BlockHash.isBlockHash(block)) {
704
- return this.getBlockByHash(block);
705
- }
706
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
707
- if (blockNumber === BlockNumber.ZERO) {
708
- return this.buildInitialBlock();
709
- }
710
- return await this.blockSource.getL2Block(blockNumber);
711
- }
712
-
713
- /**
714
- * Get a block specified by its hash.
715
- * @param blockHash - The block hash being requested.
716
- * @returns The requested block.
717
- */
718
- public async getBlockByHash(blockHash: BlockHash): Promise<L2Block | undefined> {
719
- const initialBlockHash = await this.#getInitialHeaderHash();
720
- if (blockHash.equals(initialBlockHash)) {
721
- return this.buildInitialBlock();
722
- }
723
- return await this.blockSource.getL2BlockByHash(blockHash);
724
- }
725
-
726
- private buildInitialBlock(): L2Block {
727
- const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
728
- return L2Block.empty(initialHeader);
729
- }
730
-
731
- /**
732
- * Get a block specified by its archive root.
733
- * @param archive - The archive root being requested.
734
- * @returns The requested block.
735
- */
736
- public async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
737
- return await this.blockSource.getL2BlockByArchive(archive);
738
- }
739
-
740
- /**
741
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
742
- * @param from - The start of the range of blocks to return.
743
- * @param limit - The maximum number of blocks to obtain.
744
- * @returns The blocks requested.
745
- */
746
- public async getBlocks(from: BlockNumber, limit: number): Promise<L2Block[]> {
747
- return (await this.blockSource.getBlocks(from, BlockNumber(limit))) ?? [];
748
- }
749
-
750
- public async getCheckpoints(from: CheckpointNumber, limit: number): Promise<PublishedCheckpoint[]> {
751
- return (await this.blockSource.getCheckpoints(from, limit)) ?? [];
752
- }
753
-
754
- public async getCheckpointedBlocks(from: BlockNumber, limit: number) {
755
- return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
756
- }
757
-
758
- public getCheckpointsDataForEpoch(epochNumber: EpochNumber) {
759
- return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
456
+ public async getCurrentMinFees(): Promise<GasFees> {
457
+ return await this.feeProvider.getCurrentMinFees();
760
458
  }
761
459
 
762
- /**
763
- * Method to fetch the current min L2 fees.
764
- * @returns The current min L2 fees.
765
- */
766
- public async getCurrentMinFees(): Promise<GasFees> {
767
- return await this.globalVariableBuilder.getCurrentMinFees();
460
+ /** Returns predicted min fees for the current slot and next N slots. */
461
+ public async getPredictedMinFees(manaUsage?: ManaUsageEstimate): Promise<GasFees[]> {
462
+ return await this.feeProvider.getPredictedMinFees(manaUsage);
768
463
  }
769
464
 
770
465
  public async getMaxPriorityFees(): Promise<GasFees> {
771
- for await (const tx of this.p2pClient.iteratePendingTxs()) {
466
+ for await (const tx of this.p2pClient.iteratePendingTxs({ includeProof: false })) {
772
467
  return tx.getGasSettings().maxPriorityFeesPerGas;
773
468
  }
774
469
 
775
470
  return GasFees.from({ feePerDaGas: 0n, feePerL2Gas: 0n });
776
471
  }
777
472
 
778
- /**
779
- * Method to fetch the latest block number synchronized by the node.
780
- * @returns The block number.
781
- */
782
- public async getBlockNumber(): Promise<BlockNumber> {
783
- return await this.blockSource.getBlockNumber();
784
- }
785
-
786
- public async getProvenBlockNumber(): Promise<BlockNumber> {
787
- return await this.blockSource.getProvenBlockNumber();
788
- }
789
-
790
- public async getCheckpointedBlockNumber(): Promise<BlockNumber> {
791
- return await this.blockSource.getCheckpointedL2BlockNumber();
792
- }
793
-
794
- public getCheckpointNumber(): Promise<CheckpointNumber> {
795
- return this.blockSource.getCheckpointNumber();
796
- }
797
-
798
473
  /**
799
474
  * Method to fetch the version of the package.
800
475
  * @returns The node package version
@@ -823,73 +498,25 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
823
498
  return this.contractDataSource.getContractClass(id);
824
499
  }
825
500
 
826
- public getContract(address: AztecAddress): Promise<ContractInstanceWithAddress | undefined> {
827
- return this.contractDataSource.getContract(address);
828
- }
829
-
830
- public async getPrivateLogsByTags(
831
- tags: SiloedTag[],
832
- page?: number,
833
- referenceBlock?: BlockHash,
834
- ): Promise<TxScopedL2Log[][]> {
835
- let upToBlockNumber: BlockNumber | undefined;
836
- if (referenceBlock) {
837
- const initialBlockHash = await this.#getInitialHeaderHash();
838
- if (referenceBlock.equals(initialBlockHash)) {
839
- upToBlockNumber = BlockNumber(0);
840
- } else {
841
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
842
- if (!header) {
843
- throw new Error(
844
- `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
845
- );
846
- }
847
- upToBlockNumber = header.globalVariables.blockNumber;
848
- }
849
- }
850
- return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
851
- }
852
-
853
- public async getPublicLogsByTagsFromContract(
854
- contractAddress: AztecAddress,
855
- tags: Tag[],
856
- page?: number,
857
- referenceBlock?: BlockHash,
858
- ): Promise<TxScopedL2Log[][]> {
859
- let upToBlockNumber: BlockNumber | undefined;
860
- if (referenceBlock) {
861
- const initialBlockHash = await this.#getInitialHeaderHash();
862
- if (referenceBlock.equals(initialBlockHash)) {
863
- upToBlockNumber = BlockNumber(0);
864
- } else {
865
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
866
- if (!header) {
867
- throw new Error(
868
- `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
869
- );
870
- }
871
- upToBlockNumber = header.globalVariables.blockNumber;
872
- }
501
+ public async getContract(
502
+ address: AztecAddress,
503
+ referenceBlock: BlockParameter = 'latest',
504
+ ): Promise<ContractInstanceWithAddress | undefined> {
505
+ const blockData = await this.getBlockData(referenceBlock);
506
+ if (!blockData) {
507
+ throw new Error(
508
+ `Reference block ${inspectBlockParameter(referenceBlock)} not found when querying contract ${address}. If the node API has been queried with an anchor block hash, possibly a reorg has occurred.`,
509
+ );
873
510
  }
874
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
511
+ return this.contractDataSource.getContract(address, blockData.header.globalVariables.timestamp);
875
512
  }
876
513
 
877
- /**
878
- * Gets public logs based on the provided filter.
879
- * @param filter - The filter to apply to the logs.
880
- * @returns The requested logs.
881
- */
882
- getPublicLogs(filter: LogFilter): Promise<GetPublicLogsResponse> {
883
- return this.logsSource.getPublicLogs(filter);
514
+ public getPrivateLogsByTags(query: PrivateLogsQuery): Promise<LogResult[][]> {
515
+ return this.logsSource.getPrivateLogsByTags(query);
884
516
  }
885
517
 
886
- /**
887
- * Gets contract class logs based on the provided filter.
888
- * @param filter - The filter to apply to the logs.
889
- * @returns The requested logs.
890
- */
891
- getContractClassLogs(filter: LogFilter): Promise<GetContractClassLogsResponse> {
892
- return this.logsSource.getContractClassLogs(filter);
518
+ public getPublicLogsByTags(query: PublicLogsQuery): Promise<LogResult[][]> {
519
+ return this.logsSource.getPublicLogsByTags(query);
893
520
  }
894
521
 
895
522
  /**
@@ -912,37 +539,23 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
912
539
  throw new Error(`Invalid tx: ${reason}`);
913
540
  }
914
541
 
915
- await this.p2pClient!.sendTx(tx);
542
+ try {
543
+ await this.p2pClient!.sendTx(tx);
544
+ } catch (err) {
545
+ this.metrics.receivedTx(timer.ms(), false);
546
+ this.log.warn(`Mempool rejected tx ${txHash}: ${(err as Error).message}`, { txHash });
547
+ throw err;
548
+ }
916
549
  const duration = timer.ms();
917
550
  this.metrics.receivedTx(duration, true);
918
551
  this.log.info(`Received tx ${txHash} in ${duration}ms`, { txHash });
919
552
  }
920
553
 
921
- public async getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
922
- // Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
923
- // as a fallback if we don't find a settled receipt in the archiver.
924
- const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
925
- const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
926
-
927
- // Then get the actual tx from the archiver, which tracks every tx in a mined block.
928
- const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
929
-
930
- let receipt: TxReceipt;
931
- if (settledTxReceipt) {
932
- receipt = settledTxReceipt;
933
- } else if (isKnownToPool) {
934
- // If the tx is in the pool but not in the archiver, it's pending.
935
- // This handles race conditions between archiver and p2p, where the archiver
936
- // has pruned the block in which a tx was mined, but p2p has not caught up yet.
937
- receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
938
- } else {
939
- // Otherwise, if we don't know the tx, we consider it dropped.
940
- receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
941
- }
942
-
943
- this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
944
-
945
- return receipt;
554
+ public getTxReceipt<TGetTxReceiptOptions extends GetTxReceiptOptions = {}>(
555
+ txHash: TxHash,
556
+ options?: TGetTxReceiptOptions,
557
+ ): Promise<TxReceipt<TGetTxReceiptOptions>> {
558
+ return this.txReceiptBuilder.getTxReceipt(txHash, options);
946
559
  }
947
560
 
948
561
  public getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined> {
@@ -954,13 +567,17 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
954
567
  */
955
568
  public async stop() {
956
569
  this.log.info(`Stopping Aztec Node`);
957
- await tryStop(this.validatorsSentinel);
958
- await tryStop(this.epochPruneWatcher);
570
+ await this.stopStartedWatchers();
959
571
  await tryStop(this.slasherClient);
960
572
  await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
961
573
  await tryStop(this.sequencer);
574
+ await tryStop(this.automineSequencer);
962
575
  await tryStop(this.proverNode);
963
576
  await tryStop(this.p2pClient);
577
+ // Dispose the AVM backend before world state: it kills the bb-avm-sim processes and closes the CDB IPC
578
+ // server, releasing their connections to the WSDB so it shuts down cleanly (and freeing the
579
+ // Server/Socket/ChildProcess handles that would otherwise keep the process alive after teardown).
580
+ await this.avmSimulator?.[Symbol.asyncDispose]();
964
581
  await tryStop(this.worldStateSynchronizer);
965
582
  await tryStop(this.blockSource);
966
583
  await tryStop(this.blobClient);
@@ -982,368 +599,146 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
982
599
  * @param after - The last known pending tx. Used for pagination
983
600
  * @returns - The pending txs.
984
601
  */
985
- public getPendingTxs(limit?: number, after?: TxHash): Promise<Tx[]> {
986
- return this.p2pClient!.getPendingTxs(limit, after);
602
+ public getPendingTxs(limit?: number, after?: TxHash, options?: GetTxByHashOptions): Promise<Tx[]> {
603
+ return this.p2pClient!.getPendingTxs(limit, after, options);
987
604
  }
988
605
 
989
606
  public getPendingTxCount(): Promise<number> {
990
607
  return this.p2pClient!.getPendingTxCount();
991
608
  }
992
609
 
610
+ public getPeers(includePending?: boolean): Promise<PeerInfo[]> {
611
+ return this.p2pClient!.getPeers(includePending);
612
+ }
613
+
614
+ public getCheckpointAttestationsForSlot(
615
+ slot: SlotNumber,
616
+ proposalPayloadHash?: CheckpointProposalHash,
617
+ ): Promise<CheckpointAttestation[]> {
618
+ return this.p2pClient!.getCheckpointAttestationsForSlot(slot, proposalPayloadHash);
619
+ }
620
+
621
+ public getProposalsForSlot(slot: SlotNumber): Promise<ProposalsForSlot> {
622
+ return this.p2pClient!.getProposalsForSlot(slot);
623
+ }
624
+
993
625
  /**
994
- * Method to retrieve a single tx from the mempool or unfinalized chain.
626
+ * Method to retrieve a single tx from the mempool or unfinalized chain. The tx's proof is only loaded and returned
627
+ * when `includeProof` is set.
995
628
  * @param txHash - The transaction hash to return.
629
+ * @param options - Options for the returned tx (eg whether to include its proof).
996
630
  * @returns - The tx if it exists.
997
631
  */
998
- public getTxByHash(txHash: TxHash): Promise<Tx | undefined> {
999
- return Promise.resolve(this.p2pClient!.getTxByHashFromPool(txHash));
632
+ public getTxByHash(txHash: TxHash, options?: GetTxByHashOptions): Promise<Tx | undefined> {
633
+ return this.p2pClient!.getTxByHashFromPool(txHash, { includeProof: !!options?.includeProof });
1000
634
  }
1001
635
 
1002
636
  /**
1003
- * Method to retrieve txs from the mempool or unfinalized chain.
637
+ * Method to retrieve txs from the mempool or unfinalized chain. The txs' proofs are only loaded and returned when
638
+ * `includeProof` is set.
1004
639
  * @param txHash - The transaction hash to return.
640
+ * @param options - Options for the returned txs (eg whether to include their proofs).
1005
641
  * @returns - The txs if it exists.
1006
642
  */
1007
- public async getTxsByHash(txHashes: TxHash[]): Promise<Tx[]> {
1008
- return compactArray(await Promise.all(txHashes.map(txHash => this.getTxByHash(txHash))));
643
+ public async getTxsByHash(txHashes: TxHash[], options?: GetTxByHashOptions): Promise<Tx[]> {
644
+ const txs = await this.p2pClient!.getTxsByHashFromPool(txHashes, { includeProof: !!options?.includeProof });
645
+ return compactArray(txs);
1009
646
  }
1010
647
 
1011
- public async findLeavesIndexes(
648
+ public findLeavesIndexes(
1012
649
  referenceBlock: BlockParameter,
1013
650
  treeId: MerkleTreeId,
1014
651
  leafValues: Fr[],
1015
652
  ): Promise<(DataInBlock<bigint> | undefined)[]> {
1016
- const committedDb = await this.getWorldState(referenceBlock);
1017
- const maybeIndices = await committedDb.findLeafIndices(
1018
- treeId,
1019
- leafValues.map(x => x.toBuffer()),
1020
- );
1021
- // Filter out undefined values to query block numbers only for found leaves
1022
- const definedIndices = maybeIndices.filter(x => x !== undefined);
1023
-
1024
- // Now we find the block numbers for the defined indices
1025
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
1026
-
1027
- // Build a map from leaf index to block number
1028
- const indexToBlockNumber = new Map<bigint, BlockNumber>();
1029
- for (let i = 0; i < definedIndices.length; i++) {
1030
- const blockNumber = blockNumbers[i];
1031
- if (blockNumber === undefined) {
1032
- throw new Error(
1033
- `Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`,
1034
- );
1035
- }
1036
- indexToBlockNumber.set(definedIndices[i], blockNumber);
1037
- }
1038
-
1039
- // Get unique block numbers in order to optimize num calls to getLeafValue function.
1040
- const uniqueBlockNumbers = [...new Set(indexToBlockNumber.values())];
1041
-
1042
- // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
1043
- const blockHashes = await Promise.all(
1044
- uniqueBlockNumbers.map(blockNumber => {
1045
- return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1046
- }),
1047
- );
1048
-
1049
- // Build a map from block number to block hash
1050
- const blockNumberToHash = new Map<BlockNumber, Fr>();
1051
- for (let i = 0; i < uniqueBlockNumbers.length; i++) {
1052
- const blockHash = blockHashes[i];
1053
- if (blockHash === undefined) {
1054
- throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
1055
- }
1056
- blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
1057
- }
1058
-
1059
- // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
1060
- return maybeIndices.map(index => {
1061
- if (index === undefined) {
1062
- return undefined;
1063
- }
1064
- const blockNumber = indexToBlockNumber.get(index);
1065
- if (blockNumber === undefined) {
1066
- throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1067
- }
1068
- const blockHash = blockNumberToHash.get(blockNumber);
1069
- if (blockHash === undefined) {
1070
- throw new Error(`Block hash not found for block number ${blockNumber}`);
1071
- }
1072
- return {
1073
- l2BlockNumber: blockNumber,
1074
- l2BlockHash: new BlockHash(blockHash),
1075
- data: index,
1076
- };
1077
- });
653
+ return this.worldStateQueries.findLeavesIndexes(referenceBlock, treeId, leafValues);
1078
654
  }
1079
655
 
1080
- public async getBlockHashMembershipWitness(
656
+ public getBlockHashMembershipWitness(
1081
657
  referenceBlock: BlockParameter,
1082
658
  blockHash: BlockHash,
1083
659
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
1084
- // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
1085
- // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1086
- // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1087
- const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1088
- if (referenceBlockNumber === BlockNumber.ZERO) {
1089
- // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
1090
- return undefined;
1091
- }
1092
- const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
1093
- const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
1094
- return pathAndIndex === undefined
1095
- ? undefined
1096
- : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
660
+ return this.worldStateQueries.getBlockHashMembershipWitness(referenceBlock, blockHash);
1097
661
  }
1098
662
 
1099
- public async getNoteHashMembershipWitness(
663
+ public getNoteHashMembershipWitness(
1100
664
  referenceBlock: BlockParameter,
1101
665
  noteHash: Fr,
1102
666
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
1103
- const committedDb = await this.getWorldState(referenceBlock);
1104
- const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
1105
- MerkleTreeId.NOTE_HASH_TREE,
1106
- [noteHash],
1107
- );
1108
- return pathAndIndex === undefined
1109
- ? undefined
1110
- : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
667
+ return this.worldStateQueries.getNoteHashMembershipWitness(referenceBlock, noteHash);
1111
668
  }
1112
669
 
1113
- public async getL1ToL2MessageMembershipWitness(
670
+ public getL1ToL2MessageMembershipWitness(
1114
671
  referenceBlock: BlockParameter,
1115
672
  l1ToL2Message: Fr,
1116
673
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
1117
- const db = await this.getWorldState(referenceBlock);
1118
- const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
1119
- if (!witness) {
1120
- return undefined;
1121
- }
1122
-
1123
- // REFACTOR: Return a MembershipWitness object
1124
- return [witness.index, witness.path];
674
+ return this.worldStateQueries.getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message);
1125
675
  }
1126
676
 
1127
- public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
1128
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1129
- return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
677
+ public getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
678
+ return this.worldStateQueries.getL1ToL2MessageCheckpoint(l1ToL2Message);
1130
679
  }
1131
680
 
1132
681
  /**
1133
- * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
1134
- * @param l1ToL2Message - The L1 to L2 message to check.
1135
- * @returns Whether the message is synced and ready to be included in a block.
682
+ * Returns all the L2 to L1 messages in an epoch.
683
+ *
684
+ * @deprecated Use {@link getL2ToL1MembershipWitness} to get an L2-to-L1 message witness directly.
685
+ *
686
+ * @param epoch - The epoch at which to get the data.
687
+ * @returns The L2 to L1 messages (empty array if the epoch is not found).
1136
688
  */
1137
- public async isL1ToL2MessageSynced(l1ToL2Message: Fr): Promise<boolean> {
1138
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1139
- return messageIndex !== undefined;
689
+ public getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
690
+ return this.worldStateQueries.getL2ToL1Messages(epoch);
1140
691
  }
1141
692
 
1142
693
  /**
1143
- * Returns all the L2 to L1 messages in an epoch.
1144
- * @param epoch - The epoch at which to get the data.
1145
- * @returns The L2 to L1 messages (empty array if the epoch is not found).
694
+ * Returns the L2-to-L1 membership witness for a message in `txHash`. Passthrough to the
695
+ * archiver's locally-cached resolver — see {@link Archiver.getL2ToL1MembershipWitness}.
1146
696
  */
1147
- public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
1148
- // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1149
- const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1150
- const blocksInCheckpoints = chunkBy(checkpointedBlocks, cb => cb.block.header.globalVariables.slotNumber).map(
1151
- group => group.map(cb => cb.block),
1152
- );
1153
- return blocksInCheckpoints.map(blocks =>
1154
- blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1155
- );
697
+ public getL2ToL1MembershipWitness(
698
+ txHash: TxHash,
699
+ message: Fr,
700
+ messageIndexInTx?: number,
701
+ ): Promise<L2ToL1MembershipWitness | undefined> {
702
+ return this.worldStateQueries.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
1156
703
  }
1157
704
 
1158
- public async getNullifierMembershipWitness(
705
+ public getNullifierMembershipWitness(
1159
706
  referenceBlock: BlockParameter,
1160
707
  nullifier: Fr,
1161
708
  ): Promise<NullifierMembershipWitness | undefined> {
1162
- const db = await this.getWorldState(referenceBlock);
1163
- const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
1164
- if (!witness) {
1165
- return undefined;
1166
- }
1167
-
1168
- const { index, path } = witness;
1169
- const leafPreimage = await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1170
- if (!leafPreimage) {
1171
- return undefined;
1172
- }
1173
-
1174
- return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
709
+ return this.worldStateQueries.getNullifierMembershipWitness(referenceBlock, nullifier);
1175
710
  }
1176
711
 
1177
- public async getLowNullifierMembershipWitness(
712
+ public getLowNullifierMembershipWitness(
1178
713
  referenceBlock: BlockParameter,
1179
714
  nullifier: Fr,
1180
715
  ): Promise<NullifierMembershipWitness | undefined> {
1181
- const committedDb = await this.getWorldState(referenceBlock);
1182
- const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1183
- if (!findResult) {
1184
- return undefined;
1185
- }
1186
- const { index, alreadyPresent } = findResult;
1187
- if (alreadyPresent) {
1188
- throw new Error(
1189
- `Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`,
1190
- );
1191
- }
1192
- const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
1193
-
1194
- const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1195
- return new NullifierMembershipWitness(BigInt(index), preimageData as NullifierLeafPreimage, siblingPath);
716
+ return this.worldStateQueries.getLowNullifierMembershipWitness(referenceBlock, nullifier);
1196
717
  }
1197
718
 
1198
- async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1199
- const committedDb = await this.getWorldState(referenceBlock);
1200
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1201
- if (!lowLeafResult) {
1202
- return undefined;
1203
- } else {
1204
- const preimage = (await committedDb.getLeafPreimage(
1205
- MerkleTreeId.PUBLIC_DATA_TREE,
1206
- lowLeafResult.index,
1207
- )) as PublicDataTreeLeafPreimage;
1208
- const path = await committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1209
- return new PublicDataWitness(lowLeafResult.index, preimage, path);
1210
- }
1211
- }
1212
-
1213
- public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1214
- const committedDb = await this.getWorldState(referenceBlock);
1215
- const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1216
-
1217
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1218
- if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
1219
- return Fr.ZERO;
1220
- }
1221
- const preimage = (await committedDb.getLeafPreimage(
1222
- MerkleTreeId.PUBLIC_DATA_TREE,
1223
- lowLeafResult.index,
1224
- )) as PublicDataTreeLeafPreimage;
1225
- return preimage.leaf.value;
1226
- }
1227
-
1228
- public async getBlockHeader(block: BlockParameter = 'latest'): Promise<BlockHeader | undefined> {
1229
- if (BlockHash.isBlockHash(block)) {
1230
- const initialBlockHash = await this.#getInitialHeaderHash();
1231
- if (block.equals(initialBlockHash)) {
1232
- // Block source doesn't handle initial header so we need to handle the case separately.
1233
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1234
- }
1235
- return this.blockSource.getBlockHeaderByHash(block);
1236
- } else {
1237
- // Block source doesn't handle initial header so we need to handle the case separately.
1238
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
1239
- if (blockNumber === BlockNumber.ZERO) {
1240
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1241
- }
1242
- return this.blockSource.getBlockHeader(block);
1243
- }
719
+ public getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
720
+ return this.worldStateQueries.getPublicDataWitness(referenceBlock, leafSlot);
1244
721
  }
1245
722
 
1246
- /**
1247
- * Get a block header specified by its archive root.
1248
- * @param archive - The archive root being requested.
1249
- * @returns The requested block header.
1250
- */
1251
- public async getBlockHeaderByArchive(archive: Fr): Promise<BlockHeader | undefined> {
1252
- return await this.blockSource.getBlockHeaderByArchive(archive);
1253
- }
1254
-
1255
- public getBlockData(number: BlockNumber): Promise<BlockData | undefined> {
1256
- return this.blockSource.getBlockData(number);
1257
- }
1258
-
1259
- public getBlockDataByArchive(archive: Fr): Promise<BlockData | undefined> {
1260
- return this.blockSource.getBlockDataByArchive(archive);
723
+ public getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
724
+ return this.worldStateQueries.getPublicStorageAt(referenceBlock, contract, slot);
1261
725
  }
1262
726
 
1263
727
  /**
1264
728
  * Simulates the public part of a transaction with the current state.
1265
729
  * @param tx - The transaction to simulate.
730
+ * @param skipFeeEnforcement - If true, fee enforcement is skipped.
731
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
1266
732
  **/
1267
733
  @trackSpan('AztecNodeService.simulatePublicCalls', (tx: Tx) => ({
1268
734
  [Attributes.TX_HASH]: tx.getTxHash().toString(),
1269
735
  }))
1270
- public async simulatePublicCalls(tx: Tx, skipFeeEnforcement = false): Promise<PublicSimulationOutput> {
1271
- // Check total gas limit for simulation
1272
- const gasSettings = tx.data.constants.txContext.gasSettings;
1273
- const txGasLimit = gasSettings.gasLimits.l2Gas;
1274
- const teardownGasLimit = gasSettings.teardownGasLimits.l2Gas;
1275
- if (txGasLimit + teardownGasLimit > this.config.rpcSimulatePublicMaxGasLimit) {
1276
- throw new BadRequestError(
1277
- `Transaction total gas limit ${
1278
- txGasLimit + teardownGasLimit
1279
- } (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${
1280
- this.config.rpcSimulatePublicMaxGasLimit
1281
- } for simulation`,
1282
- );
1283
- }
1284
-
1285
- const txHash = tx.getTxHash();
1286
- const latestBlockNumber = await this.blockSource.getBlockNumber();
1287
- const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1288
-
1289
- // If sequencer is not initialized, we just set these values to zero for simulation.
1290
- const coinbase = EthAddress.ZERO;
1291
- const feeRecipient = AztecAddress.ZERO;
1292
-
1293
- const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(
1294
- blockNumber,
1295
- coinbase,
1296
- feeRecipient,
1297
- );
1298
- const publicProcessorFactory = new PublicProcessorFactory(
1299
- this.contractDataSource,
1300
- new DateProvider(),
1301
- this.telemetry,
1302
- this.log.getBindings(),
1303
- );
1304
-
1305
- this.log.verbose(`Simulating public calls for tx ${txHash}`, {
1306
- globalVariables: newGlobalVariables.toInspect(),
1307
- txHash,
1308
- blockNumber,
1309
- });
1310
-
1311
- // Ensure world-state has caught up with the latest block we loaded from the archiver
1312
- await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1313
- const merkleTreeFork = await this.worldStateSynchronizer.fork();
1314
- try {
1315
- const config = PublicSimulatorConfig.from({
1316
- skipFeeEnforcement,
1317
- collectDebugLogs: true,
1318
- collectHints: false,
1319
- collectCallMetadata: true,
1320
- collectStatistics: false,
1321
- collectionLimits: CollectionLimitsConfig.from({
1322
- maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads,
1323
- }),
1324
- });
1325
- const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1326
-
1327
- // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1328
- const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1329
- // REFACTOR: Consider returning the error rather than throwing
1330
- if (failedTxs.length) {
1331
- this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
1332
- throw failedTxs[0].error;
1333
- }
1334
-
1335
- const [processedTx] = processedTxs;
1336
- return new PublicSimulationOutput(
1337
- processedTx.revertReason,
1338
- processedTx.globalVariables,
1339
- processedTx.txEffect,
1340
- returns,
1341
- processedTx.gasUsed,
1342
- debugLogs,
1343
- );
1344
- } finally {
1345
- await merkleTreeFork.close();
1346
- }
736
+ public simulatePublicCalls(
737
+ tx: Tx,
738
+ skipFeeEnforcement = false,
739
+ overrides?: SimulationOverrides,
740
+ ): Promise<PublicSimulationOutput> {
741
+ return this.nodePublicCallsSimulator.simulate(tx, skipFeeEnforcement, overrides);
1347
742
  }
1348
743
 
1349
744
  public async isValidTx(
@@ -1357,6 +752,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1357
752
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1358
753
  const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1359
754
  const l1Constants = await this.blockSource.getL1Constants();
755
+ // Enforce the same network admission limit the node advertises in getNodeInfo (network-wide, not this
756
+ // node's local caps), so a tx the wallet sized against txsLimits is not rejected here.
757
+ const networkTxGasLimits = getNetworkTxGasLimits(this.config, l1Constants);
1360
758
  const validator = createTxValidatorForAcceptingTxsOverRPC(
1361
759
  db,
1362
760
  this.contractDataSource,
@@ -1372,10 +770,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1372
770
  ],
1373
771
  gasFees: await this.getCurrentMinFees(),
1374
772
  skipFeeEnforcement,
773
+ isSimulation,
1375
774
  txsPermitted: !this.config.disableTransactions,
1376
- rollupManaLimit: l1Constants.rollupManaLimit,
1377
- maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1378
- maxBlockDAGas: this.config.validateMaxDABlockGas,
775
+ maxTxL2Gas: networkTxGasLimits.l2Gas,
776
+ maxTxDAGas: networkTxGasLimits.daGas,
1379
777
  },
1380
778
  this.log.getBindings(),
1381
779
  );
@@ -1391,7 +789,18 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1391
789
 
1392
790
  public async setConfig(config: Partial<AztecNodeAdminConfig>): Promise<void> {
1393
791
  const newConfig = { ...this.config, ...config };
1394
- this.sequencer?.updateConfig(config);
792
+ // If the sequencer is currently paused via pauseSequencer(), record the caller's desired
793
+ // minTxsPerBlock as the restore value (so resumeSequencer applies it) and keep the freeze
794
+ // (MAX_SAFE_INTEGER) applied to the underlying sequencer. Without this guard, forwarding
795
+ // the new minTxsPerBlock to the sequencer would silently unpause block production while
796
+ // pauseSequencer() still considers it paused.
797
+ const sequencerUpdate = { ...config };
798
+ if (this.sequencerPausedMinTxsPerBlock !== undefined && sequencerUpdate.minTxsPerBlock !== undefined) {
799
+ this.sequencerPausedMinTxsPerBlock = sequencerUpdate.minTxsPerBlock;
800
+ delete sequencerUpdate.minTxsPerBlock;
801
+ }
802
+ this.sequencer?.updateConfig(sequencerUpdate);
803
+ this.automineSequencer?.updateConfig(sequencerUpdate);
1395
804
  this.slasherClient?.updateConfig(config);
1396
805
  this.validatorsSentinel?.updateConfig(config);
1397
806
  await this.p2pClient.updateP2PConfig(config);
@@ -1419,7 +828,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1419
828
  classRegistry: ProtocolContractAddress.ContractClassRegistry,
1420
829
  feeJuice: ProtocolContractAddress.FeeJuice,
1421
830
  instanceRegistry: ProtocolContractAddress.ContractInstanceRegistry,
1422
- multiCallEntrypoint: ProtocolContractAddress.MultiCallEntrypoint,
831
+ multiCallEntrypoint: STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS,
1423
832
  });
1424
833
  }
1425
834
 
@@ -1483,7 +892,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1483
892
  return Promise.resolve();
1484
893
  }
1485
894
 
1486
- public async rollbackTo(targetBlock: BlockNumber, force?: boolean): Promise<void> {
895
+ public async rollbackTo(targetBlock: BlockNumber, force?: boolean, resumeSync = true): Promise<void> {
1487
896
  const archiver = this.blockSource as Archiver;
1488
897
  if (!('rollbackTo' in archiver)) {
1489
898
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1513,9 +922,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1513
922
  this.log.error(`Error during rollback`, err);
1514
923
  throw err;
1515
924
  } finally {
1516
- this.log.info(`Resuming world state and archiver sync.`);
1517
- this.worldStateSynchronizer.resumeSync();
1518
- archiver.resume();
925
+ if (resumeSync) {
926
+ this.log.info(`Resuming world state and archiver sync.`);
927
+ this.worldStateSynchronizer.resumeSync();
928
+ archiver.resume();
929
+ } else {
930
+ this.log.info(`Sync left paused after rollback (resumeSync=false).`);
931
+ }
1519
932
  }
1520
933
  }
1521
934
 
@@ -1532,11 +945,39 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1532
945
  return Promise.resolve();
1533
946
  }
1534
947
 
1535
- public getSlashPayloads(): Promise<SlashPayloadRound[]> {
1536
- if (!this.slasherClient) {
1537
- throw new Error(`Slasher client not enabled`);
948
+ public pauseSequencer(): Promise<void> {
949
+ if (this.automineSequencer) {
950
+ this.automineSequencer.pause();
951
+ return Promise.resolve();
952
+ }
953
+ if (this.sequencer) {
954
+ if (this.sequencerPausedMinTxsPerBlock === undefined) {
955
+ this.sequencerPausedMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock ?? 0;
956
+ this.sequencer.updateConfig({ minTxsPerBlock: Number.MAX_SAFE_INTEGER });
957
+ this.log.info(`Sequencer paused (minTxsPerBlock set to MAX_SAFE_INTEGER)`, {
958
+ previousMinTxsPerBlock: this.sequencerPausedMinTxsPerBlock,
959
+ });
960
+ }
961
+ return Promise.resolve();
1538
962
  }
1539
- return this.slasherClient.getSlashPayloads();
963
+ throw new BadRequestError('Cannot pause sequencer: no sequencer is running');
964
+ }
965
+
966
+ public resumeSequencer(): Promise<void> {
967
+ if (this.automineSequencer) {
968
+ this.automineSequencer.resume();
969
+ return Promise.resolve();
970
+ }
971
+ if (this.sequencer) {
972
+ if (this.sequencerPausedMinTxsPerBlock !== undefined) {
973
+ const restored = this.sequencerPausedMinTxsPerBlock;
974
+ this.sequencerPausedMinTxsPerBlock = undefined;
975
+ this.sequencer.updateConfig({ minTxsPerBlock: restored });
976
+ this.log.info(`Sequencer resumed (minTxsPerBlock restored)`, { minTxsPerBlock: restored });
977
+ }
978
+ return Promise.resolve();
979
+ }
980
+ throw new BadRequestError('Cannot resume sequencer: no sequencer is running');
1540
981
  }
1541
982
 
1542
983
  public getSlashOffenses(round: bigint | 'all' | 'current'): Promise<Offense[]> {
@@ -1544,7 +985,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1544
985
  throw new Error(`Slasher client not enabled`);
1545
986
  }
1546
987
  if (round === 'all') {
1547
- return this.slasherClient.getPendingOffenses();
988
+ return this.slasherClient.getOffenses();
1548
989
  } else {
1549
990
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1550
991
  }
@@ -1638,99 +1079,71 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1638
1079
  this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1639
1080
  }
1640
1081
 
1641
- #getInitialHeaderHash(): Promise<BlockHash> {
1642
- if (!this.initialHeaderHashPromise) {
1643
- this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
1082
+ public async mineBlock(): Promise<void> {
1083
+ if (this.automineSequencer) {
1084
+ await this.automineSequencer.buildEmptyBlock();
1085
+ return;
1644
1086
  }
1645
- return this.initialHeaderHashPromise;
1646
- }
1647
-
1648
- /**
1649
- * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1650
- * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1651
- * @returns An instance of a committed MerkleTreeOperations
1652
- */
1653
- protected async getWorldState(block: BlockParameter) {
1654
- let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1655
- try {
1656
- // Attempt to sync the world state if necessary
1657
- blockSyncedTo = await this.#syncWorldState();
1658
- } catch (err) {
1659
- this.log.error(`Error getting world state: ${err}`);
1087
+ if (!this.sequencer) {
1088
+ throw new BadRequestError('Cannot mine block: no sequencer is running');
1660
1089
  }
1661
1090
 
1662
- if (block === 'latest') {
1663
- this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
1664
- return this.worldStateSynchronizer.getCommitted();
1665
- }
1091
+ const currentBlockNumber = await this.getBlockNumber();
1666
1092
 
1667
- // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1668
- let blockNumber: BlockNumber;
1669
- if (BlockHash.isBlockHash(block)) {
1670
- const initialBlockHash = await this.#getInitialHeaderHash();
1671
- if (block.equals(initialBlockHash)) {
1672
- // Block source doesn't handle initial header so we need to handle the case separately.
1673
- return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1674
- }
1093
+ // Use slot duration + 50% buffer as the timeout so this works on running networks too
1094
+ const { slotDuration } = await this.blockSource.getL1Constants();
1095
+ const timeoutSeconds = Math.ceil(slotDuration * 1.5);
1675
1096
 
1676
- const header = await this.blockSource.getBlockHeaderByHash(block);
1677
- if (!header) {
1678
- throw new Error(
1679
- `Block hash ${block.toString()} not found when querying world state. If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
1680
- );
1681
- }
1097
+ // Temporarily set minTxsPerBlock to 0 so the sequencer produces a block even with no txs
1098
+ const originalMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock;
1099
+ this.sequencer.updateConfig({ minTxsPerBlock: 0 });
1682
1100
 
1683
- blockNumber = header.getBlockNumber();
1684
- } else {
1685
- blockNumber = block as BlockNumber;
1101
+ try {
1102
+ // Trigger the sequencer to produce a block immediately
1103
+ void this.sequencer.trigger();
1104
+
1105
+ // Wait for the new L2 block to appear
1106
+ await retryUntil(
1107
+ async () => {
1108
+ const newBlockNumber = await this.getBlockNumber();
1109
+ return newBlockNumber > currentBlockNumber ? true : undefined;
1110
+ },
1111
+ 'mineBlock',
1112
+ timeoutSeconds,
1113
+ 0.1,
1114
+ );
1115
+ } finally {
1116
+ this.sequencer.updateConfig({ minTxsPerBlock: originalMinTxsPerBlock });
1686
1117
  }
1118
+ }
1687
1119
 
1688
- // Check it's within world state sync range
1689
- if (blockNumber > blockSyncedTo) {
1690
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1120
+ public async prove(upToCheckpoint?: CheckpointNumber): Promise<CheckpointNumber> {
1121
+ if (!this.automineSequencer) {
1122
+ throw new BadRequestError('Cannot prove checkpoint: no automine sequencer is running');
1691
1123
  }
1692
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1693
-
1694
- const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
1124
+ return await this.automineSequencer.prove(upToCheckpoint);
1125
+ }
1695
1126
 
1696
- // Double-check world-state synced to the same block hash as was requested
1697
- if (BlockHash.isBlockHash(block)) {
1698
- const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1699
- if (!blockHash || !new BlockHash(blockHash).equals(block)) {
1700
- throw new Error(
1701
- `Block hash ${block.toString()} not found in world state at block number ${blockNumber}. If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
1702
- );
1703
- }
1127
+ public async warpL2TimeAtLeastTo(targetTimestamp: number): Promise<void> {
1128
+ if (!this.automineSequencer) {
1129
+ throw new BadRequestError('Cannot warp L2 time: no automine sequencer is running');
1704
1130
  }
1705
-
1706
- return snapshot;
1131
+ await this.automineSequencer.warpTo(targetTimestamp);
1707
1132
  }
1708
1133
 
1709
- /** Resolves a block parameter to a block number. */
1710
- protected async resolveBlockNumber(block: BlockParameter): Promise<BlockNumber> {
1711
- if (block === 'latest') {
1712
- return BlockNumber(await this.blockSource.getBlockNumber());
1713
- }
1714
- if (BlockHash.isBlockHash(block)) {
1715
- const initialBlockHash = await this.#getInitialHeaderHash();
1716
- if (block.equals(initialBlockHash)) {
1717
- return BlockNumber.ZERO;
1718
- }
1719
- const header = await this.blockSource.getBlockHeaderByHash(block);
1720
- if (!header) {
1721
- throw new Error(`Block hash ${block.toString()} not found.`);
1722
- }
1723
- return header.getBlockNumber();
1134
+ public async warpL2TimeAtLeastBy(duration: number): Promise<void> {
1135
+ if (!this.automineSequencer) {
1136
+ throw new BadRequestError('Cannot warp L2 time: no automine sequencer is running');
1724
1137
  }
1725
- return block as BlockNumber;
1138
+ await this.automineSequencer.warpBy(duration);
1726
1139
  }
1727
1140
 
1728
1141
  /**
1729
- * Ensure we fully sync the world state
1730
- * @returns A promise that fulfils once the world state is synced
1142
+ * Returns a committed world-state view at `block`, driving sync first. Delegates to
1143
+ * {@link NodeWorldStateQueries.getWorldState}; kept as a protected method so subclasses and tests can
1144
+ * exercise the node's block-resolution and reorg-aware sync behavior.
1731
1145
  */
1732
- async #syncWorldState(): Promise<BlockNumber> {
1733
- const blockSourceHeight = await this.blockSource.getBlockNumber();
1734
- return await this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
1146
+ protected getWorldState(block: BlockParameter) {
1147
+ return this.worldStateQueries.getWorldState(block);
1735
1148
  }
1736
1149
  }