@aztec/aztec-node 0.0.1-commit.2f68f620 → 0.0.1-commit.3100065

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 (52) hide show
  1. package/dest/aztec-node/config.d.ts +10 -1
  2. package/dest/aztec-node/config.d.ts.map +1 -1
  3. package/dest/aztec-node/config.js +10 -0
  4. package/dest/aztec-node/node_public_calls_simulator.d.ts +90 -0
  5. package/dest/aztec-node/node_public_calls_simulator.d.ts.map +1 -0
  6. package/dest/aztec-node/node_public_calls_simulator.js +346 -0
  7. package/dest/aztec-node/register_node_rpc_handlers.d.ts +10 -0
  8. package/dest/aztec-node/register_node_rpc_handlers.d.ts.map +1 -0
  9. package/dest/aztec-node/register_node_rpc_handlers.js +31 -0
  10. package/dest/aztec-node/server.d.ts +89 -64
  11. package/dest/aztec-node/server.d.ts.map +1 -1
  12. package/dest/aztec-node/server.js +222 -1131
  13. package/dest/bin/index.js +15 -10
  14. package/dest/factory.d.ts +33 -0
  15. package/dest/factory.d.ts.map +1 -0
  16. package/dest/factory.js +509 -0
  17. package/dest/index.d.ts +3 -1
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +2 -0
  20. package/dest/modules/block_parameter.d.ts +25 -0
  21. package/dest/modules/block_parameter.d.ts.map +1 -0
  22. package/dest/modules/block_parameter.js +100 -0
  23. package/dest/modules/node_block_provider.d.ts +19 -0
  24. package/dest/modules/node_block_provider.d.ts.map +1 -0
  25. package/dest/modules/node_block_provider.js +112 -0
  26. package/dest/modules/node_tx_receipt.d.ts +24 -0
  27. package/dest/modules/node_tx_receipt.d.ts.map +1 -0
  28. package/dest/modules/node_tx_receipt.js +70 -0
  29. package/dest/modules/node_world_state_queries.d.ts +65 -0
  30. package/dest/modules/node_world_state_queries.d.ts.map +1 -0
  31. package/dest/modules/node_world_state_queries.js +272 -0
  32. package/dest/sentinel/factory.d.ts +3 -3
  33. package/dest/sentinel/factory.d.ts.map +1 -1
  34. package/dest/sentinel/factory.js +8 -1
  35. package/dest/sentinel/sentinel.d.ts +21 -21
  36. package/dest/sentinel/sentinel.d.ts.map +1 -1
  37. package/dest/sentinel/sentinel.js +27 -47
  38. package/package.json +28 -27
  39. package/src/aztec-node/config.ts +19 -0
  40. package/src/aztec-node/node_public_calls_simulator.ts +383 -0
  41. package/src/aztec-node/register_node_rpc_handlers.ts +29 -0
  42. package/src/aztec-node/server.ts +307 -1315
  43. package/src/bin/index.ts +19 -12
  44. package/src/factory.ts +673 -0
  45. package/src/index.ts +2 -0
  46. package/src/modules/block_parameter.ts +93 -0
  47. package/src/modules/node_block_provider.ts +149 -0
  48. package/src/modules/node_tx_receipt.ts +115 -0
  49. package/src/modules/node_world_state_queries.ts +374 -0
  50. package/src/sentinel/README.md +3 -3
  51. package/src/sentinel/factory.ts +15 -3
  52. package/src/sentinel/sentinel.ts +34 -72
@@ -1,80 +1,48 @@
1
- import { Archiver, L1ToL2MessagesNotReadyError, 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';
6
+ import type { EpochCacheInterface } from '@aztec/epoch-cache';
7
+ import { RollupContract } from '@aztec/ethereum/contracts';
11
8
  import { type L1ContractAddresses, pickL1ContractAddresses } 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';
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';
19
21
  import { retryUntil } from '@aztec/foundation/retry';
20
22
  import { count } from '@aztec/foundation/string';
21
- import { DateProvider, Timer } from '@aztec/foundation/timer';
23
+ import { Timer } from '@aztec/foundation/timer';
22
24
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
23
- import { isErrorClass } from '@aztec/foundation/types';
24
- import { type KeyStore, KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
25
- import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
26
- import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
27
- import {
28
- type P2P,
29
- type P2PClientDeps,
30
- createP2PClient,
31
- createTxValidatorForAcceptingTxsOverRPC,
32
- getDefaultAllowedSetupFunctions,
33
- } 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';
34
28
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
35
- import { type ProverNode, type ProverNodeDeps, createProverNode } from '@aztec/prover-node';
36
- import { createKeyStoreForProver } from '@aztec/prover-node/config';
37
- import {
38
- AutomineSequencer,
39
- FeeProviderImpl,
40
- GlobalVariableBuilder,
41
- SequencerClient,
42
- type SequencerPublisher,
43
- createAutomineSequencer,
44
- } from '@aztec/sequencer-client';
45
- import { PublicContractsDB, PublicProcessorFactory } from '@aztec/simulator/server';
46
- import {
47
- AttestationsBlockWatcher,
48
- AttestedInvalidProposalWatcher,
49
- BroadcastedInvalidCheckpointProposalWatcher,
50
- CheckpointEquivocationWatcher,
51
- DataWithholdingWatcher,
52
- type SlasherClientInterface,
53
- type Watcher,
54
- createSlasher,
55
- } from '@aztec/slasher';
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 { SlasherClientInterface } from '@aztec/slasher';
56
33
  import { STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS } from '@aztec/standard-contracts/multi-call-entrypoint';
57
- import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
58
34
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
59
35
  import {
60
36
  type BlockData,
61
37
  BlockHash,
62
38
  type BlockParameter,
63
- BlockTag,
64
39
  type CheckpointsQuery,
65
- type CommitteeAttestation,
66
40
  type DataInBlock,
67
41
  type L2BlockSource,
42
+ type L2BlockTag,
68
43
  type L2Tips,
69
- type NormalizedBlockParameter,
70
44
  inspectBlockParameter,
71
45
  } from '@aztec/stdlib/block';
72
- import {
73
- type CheckpointData,
74
- CheckpointReexecutionTracker,
75
- L1PublishedData,
76
- type PublishedCheckpoint,
77
- } from '@aztec/stdlib/checkpoint';
78
46
  import type {
79
47
  ContractClassPublic,
80
48
  ContractDataSource,
@@ -82,9 +50,8 @@ import type {
82
50
  NodeInfo,
83
51
  ProtocolContractAddresses,
84
52
  } from '@aztec/stdlib/contract';
85
- import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
86
- import { GasFees, type ManaUsageEstimate } from '@aztec/stdlib/gas';
87
- import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
53
+ import type { L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
54
+ import { GasFees, type ManaUsageEstimate, getNetworkTxGasLimits } from '@aztec/stdlib/gas';
88
55
  import type {
89
56
  AztecNode,
90
57
  AztecNodeAdmin,
@@ -93,11 +60,13 @@ import type {
93
60
  BlockIncludeOptions,
94
61
  BlockResponse,
95
62
  BlocksIncludeOptions,
96
- ChainTip,
97
- ChainTips,
98
63
  CheckpointIncludeOptions,
99
64
  CheckpointParameter,
100
65
  CheckpointResponse,
66
+ CheckpointTag,
67
+ GetTxByHashOptions,
68
+ PeerInfo,
69
+ ProposalsForSlot,
101
70
  } from '@aztec/stdlib/interfaces/client';
102
71
  import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
103
72
  import {
@@ -110,37 +79,24 @@ import {
110
79
  tryStop,
111
80
  } from '@aztec/stdlib/interfaces/server';
112
81
  import type { DebugLogStore, LogResult, PrivateLogsQuery, PublicLogsQuery } from '@aztec/stdlib/logs';
113
- import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
114
- import {
115
- InboxLeaf,
116
- type L1ToL2MessageSource,
117
- type L2ToL1MembershipWitness,
118
- appendL1ToL2MessagesToTree,
119
- } from '@aztec/stdlib/messaging';
82
+ import { NullDebugLogStore } from '@aztec/stdlib/logs';
83
+ import type { L1ToL2MessageSource, L2ToL1MembershipWitness } from '@aztec/stdlib/messaging';
84
+ import type { CheckpointAttestation } from '@aztec/stdlib/p2p';
120
85
  import type { Offense } from '@aztec/stdlib/slashing';
121
- import { MIN_EXECUTION_TIME } from '@aztec/stdlib/timetable';
122
- import type { NullifierLeafPreimage, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
123
86
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
124
87
  import {
125
- DroppedTxReceipt,
126
88
  type FeeProvider,
127
89
  type GetTxReceiptOptions,
128
90
  type GlobalVariableBuilder as GlobalVariableBuilderInterface,
129
91
  type IndexedTxEffect,
130
- MinedTxReceipt,
131
- type MinedTxStatus,
132
- PendingTxReceipt,
133
92
  PublicSimulationOutput,
134
93
  type SimulationOverrides,
135
94
  Tx,
136
95
  type TxHash,
137
96
  type TxReceipt,
138
- TxStatus,
139
97
  type TxValidationResult,
140
98
  } from '@aztec/stdlib/tx';
141
- import { getPackageVersion } from '@aztec/stdlib/update-checker';
142
99
  import type { SingleValidatorStats, ValidatorsStats } from '@aztec/stdlib/validators';
143
- import type { GenesisData } from '@aztec/stdlib/world-state';
144
100
  import {
145
101
  Attributes,
146
102
  type TelemetryClient,
@@ -149,31 +105,51 @@ import {
149
105
  getTelemetryClient,
150
106
  trackSpan,
151
107
  } from '@aztec/telemetry-client';
152
- import {
153
- FullNodeCheckpointsBuilder as CheckpointsBuilder,
154
- FullNodeCheckpointsBuilder,
155
- NodeKeystoreAdapter,
156
- ValidatorClient,
157
- createProposalHandler,
158
- createValidatorClient,
159
- } from '@aztec/validator-client';
160
- import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
161
- import { createWorldState, createWorldStateSynchronizer } from '@aztec/world-state';
162
-
163
- import { createPublicClient } from 'viem';
164
-
165
- import { createSentinel } from '../sentinel/factory.js';
108
+ import { NodeKeystoreAdapter, ValidatorClient } from '@aztec/validator-client';
109
+
110
+ import { NodeBlockProvider } from '../modules/node_block_provider.js';
111
+ import { NodeTxReceiptBuilder } from '../modules/node_tx_receipt.js';
112
+ import { NodeWorldStateQueries } from '../modules/node_world_state_queries.js';
166
113
  import { Sentinel } from '../sentinel/sentinel.js';
167
- import {
168
- blockResponseFromBlockData,
169
- blockResponseFromL2Block,
170
- checkpointResponseFromCheckpointData,
171
- checkpointResponseFromPublishedCheckpoint,
172
- projectProposedToCheckpointResponse,
173
- } from './block_response_helpers.js';
174
- import { type AztecNodeConfig, createKeyStoreForValidator } from './config.js';
114
+ import type { AztecNodeConfig } from './config.js';
175
115
  import { NodeMetrics } from './node_metrics.js';
176
- import { applyPublicDataOverrides } from './public_data_overrides.js';
116
+ import { NodePublicCallsSimulator } from './node_public_calls_simulator.js';
117
+
118
+ /**
119
+ * Fully-constructed collaborators and settings an {@link AztecNodeService} owns. Built by `createAztecNodeService`
120
+ * (see `factory.ts`); passed as a single object so call sites name each dependency instead of relying on
121
+ * positional order.
122
+ */
123
+ export interface AztecNodeServiceDeps {
124
+ config: AztecNodeConfig;
125
+ p2pClient: P2P;
126
+ blockSource: L2BlockSource & Partial<Service>;
127
+ logsSource: L2LogsSource;
128
+ contractDataSource: ContractDataSource;
129
+ l1ToL2MessageSource: L1ToL2MessageSource;
130
+ worldStateSynchronizer: WorldStateSynchronizer;
131
+ sequencer: SequencerClient | undefined;
132
+ proverNode: ProverNode | undefined;
133
+ slasherClient: SlasherClientInterface | undefined;
134
+ validatorsSentinel: Sentinel | undefined;
135
+ stopStartedWatchers: () => Promise<void>;
136
+ l1ChainId: number;
137
+ version: number;
138
+ globalVariableBuilder: GlobalVariableBuilderInterface;
139
+ rollupContract: RollupContract | undefined;
140
+ feeProvider: FeeProvider;
141
+ epochCache: EpochCacheInterface;
142
+ packageVersion: string;
143
+ peerProofVerifier: ClientProtocolCircuitVerifier;
144
+ rpcProofVerifier: ClientProtocolCircuitVerifier;
145
+ telemetry?: TelemetryClient;
146
+ log?: Logger;
147
+ blobClient?: BlobClientInterface;
148
+ validatorClient?: ValidatorClient;
149
+ keyStoreManager?: KeystoreManager;
150
+ debugLogStore?: DebugLogStore;
151
+ automineSequencer?: AutomineSequencer;
152
+ }
177
153
 
178
154
  /**
179
155
  * The aztec node.
@@ -184,48 +160,113 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
184
160
  private isUploadingSnapshot = false;
185
161
  // Saved minTxsPerBlock used by `pauseSequencer` to restore production-sequencer config on resume.
186
162
  private sequencerPausedMinTxsPerBlock: number | undefined;
163
+ private readonly nodePublicCallsSimulator: NodePublicCallsSimulator;
164
+ private readonly worldStateQueries: NodeWorldStateQueries;
165
+ private readonly blockProvider: NodeBlockProvider;
166
+ private readonly txReceiptBuilder: NodeTxReceiptBuilder;
187
167
 
188
168
  public readonly tracer: Tracer;
189
169
 
190
- constructor(
191
- protected config: AztecNodeConfig,
192
- protected readonly p2pClient: P2P,
193
- protected readonly blockSource: L2BlockSource & Partial<Service>,
194
- protected readonly logsSource: L2LogsSource,
195
- protected readonly contractDataSource: ContractDataSource,
196
- protected readonly l1ToL2MessageSource: L1ToL2MessageSource,
197
- protected readonly worldStateSynchronizer: WorldStateSynchronizer,
198
- protected readonly sequencer: SequencerClient | undefined,
199
- protected readonly proverNode: ProverNode | undefined,
200
- protected readonly slasherClient: SlasherClientInterface | undefined,
201
- protected readonly validatorsSentinel: Sentinel | undefined,
202
- private readonly stopStartedWatchers: () => Promise<void>,
203
- protected readonly l1ChainId: number,
204
- protected readonly version: number,
205
- protected readonly globalVariableBuilder: GlobalVariableBuilderInterface,
206
- protected readonly feeProvider: FeeProvider,
207
- protected readonly epochCache: EpochCacheInterface,
208
- protected readonly packageVersion: string,
209
- private peerProofVerifier: ClientProtocolCircuitVerifier,
210
- private rpcProofVerifier: ClientProtocolCircuitVerifier,
211
- private telemetry: TelemetryClient = getTelemetryClient(),
212
- private log = createLogger('node'),
213
- private blobClient?: BlobClientInterface,
214
- private validatorClient?: ValidatorClient,
215
- private keyStoreManager?: KeystoreManager,
216
- private debugLogStore: DebugLogStore = new NullDebugLogStore(),
217
- private readonly automineSequencer?: AutomineSequencer,
218
- ) {
219
- this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
220
- this.tracer = telemetry.getTracer('AztecNodeService');
170
+ protected config: AztecNodeConfig;
171
+ protected readonly p2pClient: P2P;
172
+ protected readonly blockSource: L2BlockSource & Partial<Service>;
173
+ protected readonly logsSource: L2LogsSource;
174
+ protected readonly contractDataSource: ContractDataSource;
175
+ protected readonly l1ToL2MessageSource: L1ToL2MessageSource;
176
+ protected readonly worldStateSynchronizer: WorldStateSynchronizer;
177
+ protected readonly sequencer: SequencerClient | undefined;
178
+ protected readonly proverNode: ProverNode | undefined;
179
+ protected readonly slasherClient: SlasherClientInterface | undefined;
180
+ protected readonly validatorsSentinel: Sentinel | undefined;
181
+ private readonly stopStartedWatchers: () => Promise<void>;
182
+ protected readonly l1ChainId: number;
183
+ protected readonly version: number;
184
+ protected readonly globalVariableBuilder: GlobalVariableBuilderInterface;
185
+ protected readonly rollupContract: RollupContract | undefined;
186
+ protected readonly feeProvider: FeeProvider;
187
+ protected readonly epochCache: EpochCacheInterface;
188
+ protected readonly packageVersion: string;
189
+ private peerProofVerifier: ClientProtocolCircuitVerifier;
190
+ private rpcProofVerifier: ClientProtocolCircuitVerifier;
191
+ private telemetry: TelemetryClient;
192
+ private log: Logger;
193
+ private blobClient?: BlobClientInterface;
194
+ private validatorClient?: ValidatorClient;
195
+ private keyStoreManager?: KeystoreManager;
196
+ private debugLogStore: DebugLogStore;
197
+ private readonly automineSequencer?: AutomineSequencer;
198
+
199
+ constructor(deps: AztecNodeServiceDeps) {
200
+ this.config = deps.config;
201
+ this.p2pClient = deps.p2pClient;
202
+ this.blockSource = deps.blockSource;
203
+ this.logsSource = deps.logsSource;
204
+ this.contractDataSource = deps.contractDataSource;
205
+ this.l1ToL2MessageSource = deps.l1ToL2MessageSource;
206
+ this.worldStateSynchronizer = deps.worldStateSynchronizer;
207
+ this.sequencer = deps.sequencer;
208
+ this.proverNode = deps.proverNode;
209
+ this.slasherClient = deps.slasherClient;
210
+ this.validatorsSentinel = deps.validatorsSentinel;
211
+ this.stopStartedWatchers = deps.stopStartedWatchers;
212
+ this.l1ChainId = deps.l1ChainId;
213
+ this.version = deps.version;
214
+ this.globalVariableBuilder = deps.globalVariableBuilder;
215
+ this.rollupContract = deps.rollupContract;
216
+ this.feeProvider = deps.feeProvider;
217
+ this.epochCache = deps.epochCache;
218
+ this.packageVersion = deps.packageVersion;
219
+ this.peerProofVerifier = deps.peerProofVerifier;
220
+ this.rpcProofVerifier = deps.rpcProofVerifier;
221
+ this.telemetry = deps.telemetry ?? getTelemetryClient();
222
+ this.log = deps.log ?? createLogger('node');
223
+ this.blobClient = deps.blobClient;
224
+ this.validatorClient = deps.validatorClient;
225
+ this.keyStoreManager = deps.keyStoreManager;
226
+ this.debugLogStore = deps.debugLogStore ?? new NullDebugLogStore();
227
+ this.automineSequencer = deps.automineSequencer;
228
+
229
+ this.metrics = new NodeMetrics(this.telemetry, 'AztecNodeService');
230
+ this.tracer = this.telemetry.getTracer('AztecNodeService');
231
+
232
+ // The node never represents a proposer's payout addresses, so the simulator zeroes coinbase and
233
+ // fee recipient. The signature context only needs chain id + rollup address (see signature_utils).
234
+ this.nodePublicCallsSimulator = new NodePublicCallsSimulator({
235
+ blockSource: this.blockSource,
236
+ worldStateSynchronizer: this.worldStateSynchronizer,
237
+ l1ToL2MessageSource: this.l1ToL2MessageSource,
238
+ contractDataSource: this.contractDataSource,
239
+ globalVariableBuilder: this.globalVariableBuilder,
240
+ rollupContract: this.rollupContract,
241
+ epochCache: this.epochCache,
242
+ signatureContext: { chainId: this.l1ChainId, rollupAddress: this.config.rollupAddress },
243
+ config: this.config,
244
+ telemetry: this.telemetry,
245
+ log: this.log.createChild('public-calls-simulator'),
246
+ });
247
+
248
+ this.worldStateQueries = new NodeWorldStateQueries({
249
+ worldStateSynchronizer: this.worldStateSynchronizer,
250
+ blockSource: this.blockSource,
251
+ l1ToL2MessageSource: this.l1ToL2MessageSource,
252
+ log: this.log.createChild('world-state-queries'),
253
+ });
254
+
255
+ this.blockProvider = new NodeBlockProvider(this.blockSource);
256
+
257
+ this.txReceiptBuilder = new NodeTxReceiptBuilder({
258
+ p2pClient: this.p2pClient,
259
+ blockSource: this.blockSource,
260
+ debugLogStore: this.debugLogStore,
261
+ });
221
262
 
222
263
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
223
- this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, pickL1ContractAddresses(config));
264
+ this.log.info(`Aztec Node started on chain 0x${this.l1ChainId.toString(16)}`, pickL1ContractAddresses(this.config));
224
265
 
225
- // A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
266
+ // A defensive check that protects us against introducing a bug in the complex node creation flow. We must
226
267
  // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
227
268
  // memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
228
- if (debugLogStore.isEnabled && config.realProofs) {
269
+ if (this.debugLogStore.isEnabled && this.config.realProofs) {
229
270
  throw new Error('debugLogStore should never be enabled when realProofs are set');
230
271
  }
231
272
  }
@@ -240,30 +281,43 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
240
281
  return status.syncSummary;
241
282
  }
242
283
 
243
- public async getChainTips(): Promise<ChainTips> {
244
- const { proposed, checkpointed, proven, finalized } = await this.blockSource.getL2Tips();
245
- return { proposed, checkpointed, proven, finalized };
284
+ public getChainTips(): Promise<L2Tips> {
285
+ return this.blockSource.getL2Tips();
286
+ }
287
+
288
+ public getL1Constants(): Promise<L1RollupConstants> {
289
+ return this.blockSource.getL1Constants();
290
+ }
291
+
292
+ public getSyncedL2SlotNumber() {
293
+ return this.blockSource.getSyncedL2SlotNumber();
294
+ }
295
+
296
+ public getSyncedL2EpochNumber() {
297
+ return this.blockSource.getSyncedL2EpochNumber();
298
+ }
299
+
300
+ public getSyncedL1Timestamp() {
301
+ return this.blockSource.getL1Timestamp();
246
302
  }
247
303
 
248
304
  public getCheckpointsData(query: CheckpointsQuery) {
249
305
  return this.blockSource.getCheckpointsData(query);
250
306
  }
251
307
 
252
- public async getBlockNumber(tip?: ChainTip): Promise<BlockNumber> {
308
+ public async getBlockNumber(tip?: L2BlockTag): Promise<BlockNumber> {
253
309
  if (tip === undefined || tip === 'proposed') {
254
310
  return this.blockSource.getBlockNumber();
255
311
  }
256
312
  return (await this.blockSource.getBlockNumber({ tag: tip })) ?? BlockNumber.ZERO;
257
313
  }
258
314
 
259
- public async getCheckpointNumber(tip?: ChainTip): Promise<CheckpointNumber> {
315
+ public async getCheckpointNumber(tip?: CheckpointTag): Promise<CheckpointNumber> {
260
316
  const tips = await this.blockSource.getL2Tips();
261
317
  switch (tip) {
262
318
  case undefined:
263
319
  case 'checkpointed':
264
320
  return tips.checkpointed.checkpoint.number;
265
- case 'proposed':
266
- return tips.proposedCheckpoint.checkpoint.number;
267
321
  case 'proven':
268
322
  return tips.proven.checkpoint.number;
269
323
  case 'finalized':
@@ -271,760 +325,38 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
271
325
  }
272
326
  }
273
327
 
274
- private isChainTip(value: unknown): value is ChainTip {
275
- return value === 'proposed' || value === 'checkpointed' || value === 'proven' || value === 'finalized';
276
- }
277
-
278
- /**
279
- * Normalizes a {@link BlockParameter} (which may be a bare value) into a
280
- * {@link NormalizedBlockParameter} object form. Performs no chain-tip resolution — tag
281
- * lookups are deferred to the underlying block source.
282
- */
283
- private normalizeBlockParameter(param: BlockParameter): NormalizedBlockParameter {
284
- if (BlockHash.isBlockHash(param)) {
285
- return { hash: param };
286
- }
287
- if (typeof param === 'number') {
288
- return { number: param as BlockNumber };
289
- }
290
- if (typeof param === 'string') {
291
- if (this.isBlockTag(param)) {
292
- return { tag: param === 'latest' ? 'proposed' : param };
293
- }
294
- throw new BadRequestError(`Invalid BlockParameter tag: ${param}`);
295
- }
296
- if (typeof param === 'object' && param !== null) {
297
- if ('number' in param) {
298
- return { number: param.number };
299
- }
300
- if ('hash' in param) {
301
- return { hash: param.hash };
302
- }
303
- if ('archive' in param) {
304
- return { archive: param.archive };
305
- }
306
- if ('tag' in param) {
307
- if (this.isBlockTag(param.tag)) {
308
- return { tag: param.tag };
309
- }
310
- throw new BadRequestError(`Invalid BlockParameter tag: ${param.tag}`);
311
- }
312
- }
313
- throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(param)}`);
314
- }
315
-
316
- private isBlockTag(value: string): value is BlockTag {
317
- return BlockTag.includes(value as BlockTag);
318
- }
319
-
320
- /**
321
- * Resolves a {@link CheckpointParameter} into a concrete `{ number }` or `{ slot }` query.
322
- *
323
- * Tag-based parameters (`'proposed'`, `'checkpointed'`, `'proven'`, `'finalized'`) are
324
- * translated up-front to the corresponding tip's checkpoint number via {@link L2BlockSource.getL2Tips}.
325
- * After resolution the unified {@link getCheckpoint} flow can perform a single
326
- * confirmed→proposed lookup against either store.
327
- */
328
- private async resolveCheckpointParameter(
329
- param: CheckpointParameter,
330
- ): Promise<{ number: CheckpointNumber } | { slot: SlotNumber }> {
331
- if (typeof param === 'number') {
332
- return { number: param as CheckpointNumber };
333
- }
334
- if (this.isChainTip(param)) {
335
- const tips = await this.blockSource.getL2Tips();
336
- switch (param) {
337
- case 'proposed':
338
- return { number: tips.proposedCheckpoint.checkpoint.number };
339
- case 'checkpointed':
340
- return { number: tips.checkpointed.checkpoint.number };
341
- case 'proven':
342
- return { number: tips.proven.checkpoint.number };
343
- case 'finalized':
344
- return { number: tips.finalized.checkpoint.number };
345
- }
346
- }
347
- if (typeof param === 'object' && param !== null) {
348
- if ('number' in param) {
349
- return { number: param.number };
350
- }
351
- if ('slot' in param) {
352
- return { slot: param.slot };
353
- }
354
- }
355
- throw new BadRequestError(`Invalid CheckpointParameter: ${JSON.stringify(param)}`);
356
- }
357
-
358
- /** Fetches checkpoint-level L1 and attestation data for use as block response context. */
359
- async #getCheckpointContext(
360
- checkpointNumber: CheckpointNumber,
361
- ): Promise<{ l1?: L1PublishedData; attestations?: CommitteeAttestation[] } | undefined> {
362
- const checkpoint = await this.blockSource.getCheckpointData({ number: checkpointNumber });
363
- if (!checkpoint) {
364
- return undefined;
365
- }
366
- return { l1: checkpoint.l1, attestations: checkpoint.attestations };
367
- }
368
-
369
- public async getBlock<Opts extends BlockIncludeOptions = {}>(
328
+ public getBlock<Opts extends BlockIncludeOptions = {}>(
370
329
  param: BlockParameter,
371
330
  options: Opts = {} as Opts,
372
331
  ): Promise<BlockResponse<Opts> | undefined> {
373
- const query = this.normalizeBlockParameter(param);
374
- const wantTxs = !!options.includeTransactions;
375
- const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
376
-
377
- if (wantTxs) {
378
- const block = await this.blockSource.getBlock(query);
379
- if (!block) {
380
- return undefined;
381
- }
382
- const ctx = wantContext ? await this.#getCheckpointContext(block.checkpointNumber) : undefined;
383
- return (await blockResponseFromL2Block(block, options, ctx)) as BlockResponse<Opts>;
384
- }
385
- const data = await this.blockSource.getBlockData(query);
386
- if (!data) {
387
- return undefined;
388
- }
389
- const ctx = wantContext ? await this.#getCheckpointContext(data.checkpointNumber) : undefined;
390
- return blockResponseFromBlockData(data, options, ctx) as BlockResponse<Opts>;
332
+ return this.blockProvider.getBlock(param, options);
391
333
  }
392
334
 
393
335
  public getBlockData(param: BlockParameter): Promise<BlockData | undefined> {
394
- const query = this.normalizeBlockParameter(param);
395
- return this.blockSource.getBlockData(query);
336
+ return this.blockProvider.getBlockData(param);
396
337
  }
397
338
 
398
- public async getBlocks<Opts extends BlocksIncludeOptions = {}>(
339
+ public getBlocks<Opts extends BlocksIncludeOptions = {}>(
399
340
  from: BlockNumber,
400
341
  limit: number,
401
342
  options: Opts = {} as Opts,
402
343
  ): Promise<BlockResponse<Opts>[]> {
403
- const wantTxs = !!options.includeTransactions;
404
- const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
405
- const onlyCheckpointed = !!options.onlyCheckpointed;
406
- if (wantTxs) {
407
- const blocks = await this.blockSource.getBlocks({ from, limit, onlyCheckpointed });
408
- const ctxByCheckpoint = await this.#getCheckpointContextsForBlocks(wantContext ? blocks : []);
409
- return (await Promise.all(
410
- blocks.map(block => blockResponseFromL2Block(block, options, ctxByCheckpoint.get(block.checkpointNumber))),
411
- )) as BlockResponse<Opts>[];
412
- }
413
- const dataItems = await this.blockSource.getBlocksData({ from, limit, onlyCheckpointed });
414
- const ctxByCheckpoint = await this.#getCheckpointContextsForBlocks(wantContext ? dataItems : []);
415
- return (await Promise.all(
416
- dataItems.map(data => blockResponseFromBlockData(data, options, ctxByCheckpoint.get(data.checkpointNumber))),
417
- )) as BlockResponse<Opts>[];
418
- }
419
-
420
- /** Fetches checkpoint context for a set of blocks, deduplicating shared checkpoints. */
421
- async #getCheckpointContextsForBlocks(
422
- blocks: { checkpointNumber: CheckpointNumber }[],
423
- ): Promise<Map<CheckpointNumber, { l1?: L1PublishedData; attestations?: CommitteeAttestation[] } | undefined>> {
424
- const unique = Array.from(new Set(blocks.map(b => b.checkpointNumber)));
425
- const entries = await Promise.all(unique.map(async n => [n, await this.#getCheckpointContext(n)] as const));
426
- return new Map(entries);
344
+ return this.blockProvider.getBlocks(from, limit, options);
427
345
  }
428
346
 
429
- public async getCheckpoint<Opts extends CheckpointIncludeOptions = {}>(
347
+ public getCheckpoint<Opts extends CheckpointIncludeOptions = {}>(
430
348
  param: CheckpointParameter,
431
349
  options: Opts = {} as Opts,
432
350
  ): Promise<CheckpointResponse<Opts> | undefined> {
433
- const query = await this.resolveCheckpointParameter(param);
434
-
435
- // Try the confirmed store first.
436
- const confirmed = options.includeBlocks
437
- ? await this.blockSource.getCheckpoint(query)
438
- : await this.blockSource.getCheckpointData(query);
439
- if (confirmed) {
440
- return (await (options.includeBlocks
441
- ? checkpointResponseFromPublishedCheckpoint(confirmed as PublishedCheckpoint, options)
442
- : checkpointResponseFromCheckpointData(confirmed as CheckpointData, options))) as CheckpointResponse<Opts>;
443
- }
444
-
445
- // Fall back to the proposed store.
446
- const proposed = await this.blockSource.getProposedCheckpointData(query);
447
- if (proposed) {
448
- if (options.includeAttestations || options.includeL1PublishInfo) {
449
- throw new BadRequestError(
450
- `Options includeL1PublishInfo or includeAttestations cannot be satisfied for a proposed checkpoint`,
451
- );
452
- }
453
- const blocks = options.includeBlocks
454
- ? await this.blockSource.getBlocks({ from: proposed.startBlock, limit: proposed.blockCount })
455
- : undefined;
456
- return (await projectProposedToCheckpointResponse(proposed, options, blocks)) as CheckpointResponse<Opts>;
457
- }
458
-
459
- return undefined;
351
+ return this.blockProvider.getCheckpoint(param, options);
460
352
  }
461
353
 
462
- public async getCheckpoints<Opts extends CheckpointIncludeOptions = {}>(
354
+ public getCheckpoints<Opts extends CheckpointIncludeOptions = {}>(
463
355
  from: CheckpointNumber,
464
356
  limit: number,
465
357
  options: Opts = {} as Opts,
466
358
  ): Promise<CheckpointResponse<Opts>[]> {
467
- if (options.includeBlocks) {
468
- const checkpoints = await this.blockSource.getCheckpoints({ from, limit });
469
- return (await Promise.all(
470
- checkpoints.map(cp => checkpointResponseFromPublishedCheckpoint(cp, options)),
471
- )) as CheckpointResponse<Opts>[];
472
- }
473
- const datas = await this.blockSource.getCheckpointsData({ from, limit });
474
- return datas.map(d => checkpointResponseFromCheckpointData(d, options)) as CheckpointResponse<Opts>[];
475
- }
476
-
477
- /**
478
- * initializes the Aztec Node, wait for component to sync.
479
- * @param config - The configuration to be used by the aztec node.
480
- * @returns - A fully synced Aztec Node for use in development/testing.
481
- */
482
- public static async createAndSync(
483
- inputConfig: AztecNodeConfig,
484
- deps: {
485
- telemetry?: TelemetryClient;
486
- logger?: Logger;
487
- publisher?: SequencerPublisher;
488
- dateProvider?: DateProvider;
489
- p2pClientDeps?: P2PClientDeps;
490
- proverNodeDeps?: Partial<ProverNodeDeps>;
491
- slashingProtectionDb?: SlashingProtectionDatabase;
492
- } = {},
493
- options: {
494
- genesis?: GenesisData;
495
- dontStartSequencer?: boolean;
496
- dontStartProverNode?: boolean;
497
- } = {},
498
- ): Promise<AztecNodeService> {
499
- const config = { ...inputConfig }; // Copy the config so we dont mutate the input object
500
- const log = deps.logger ?? createLogger('node');
501
- const packageVersion = getPackageVersion();
502
- const telemetry = deps.telemetry ?? getTelemetryClient();
503
- const dateProvider = deps.dateProvider ?? new DateProvider();
504
- const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
505
-
506
- // Build a key store from file if given or from environment otherwise.
507
- // We keep the raw KeyStore available so we can merge with prover keys if enableProverNode is set.
508
- let keyStoreManager: KeystoreManager | undefined;
509
- const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
510
- if (keyStoreProvided) {
511
- const keyStores = loadKeystores(config.keyStoreDirectory!);
512
- keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
513
- } else {
514
- const rawKeyStores: KeyStore[] = [];
515
- const validatorKeyStore = createKeyStoreForValidator(config);
516
- if (validatorKeyStore) {
517
- rawKeyStores.push(validatorKeyStore);
518
- }
519
- if (config.enableProverNode) {
520
- const proverKeyStore = createKeyStoreForProver(config);
521
- if (proverKeyStore) {
522
- rawKeyStores.push(proverKeyStore);
523
- }
524
- }
525
- if (rawKeyStores.length > 0) {
526
- keyStoreManager = new KeystoreManager(
527
- rawKeyStores.length === 1 ? rawKeyStores[0] : mergeKeystores(rawKeyStores),
528
- );
529
- }
530
- }
531
-
532
- await keyStoreManager?.validateSigners();
533
-
534
- // If we are a validator, verify our configuration before doing too much more.
535
- if (!config.disableValidator) {
536
- if (keyStoreManager === undefined) {
537
- throw new Error('Failed to create key store, a requirement for running a validator');
538
- }
539
- if (!keyStoreProvided && process.env.NODE_ENV !== 'test') {
540
- log.warn("Keystore created from env: it's recommended to use a file-based key store for production");
541
- }
542
- ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
543
- }
544
-
545
- // validate that the actual chain id matches that specified in configuration
546
- if (config.l1ChainId !== ethereumChain.chainInfo.id) {
547
- throw new Error(
548
- `RPC URL configured for chain id ${ethereumChain.chainInfo.id} but expected id ${config.l1ChainId}`,
549
- );
550
- }
551
-
552
- const publicClient = createPublicClient({
553
- chain: ethereumChain.chainInfo,
554
- transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
555
- pollingInterval: config.viemPollingIntervalMS,
556
- });
557
-
558
- const l1ContractsAddresses = await RegistryContract.collectAddresses(
559
- publicClient,
560
- config.registryAddress,
561
- config.rollupVersion ?? 'canonical',
562
- );
563
-
564
- Object.assign(config, l1ContractsAddresses);
565
-
566
- const rollupContract = new RollupContract(publicClient, config.rollupAddress.toString());
567
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
568
- rollupContract.getL1GenesisTime(),
569
- rollupContract.getSlotDuration(),
570
- rollupContract.getVersion(),
571
- rollupContract.getManaLimit().then(Number),
572
- ] as const);
573
-
574
- config.rollupVersion ??= Number(rollupVersionFromRollup);
575
-
576
- if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
577
- log.warn(
578
- `Registry looked up and returned a rollup with version (${config.rollupVersion}), but this does not match with version detected from the rollup directly: (${rollupVersionFromRollup}).`,
579
- );
580
- }
581
-
582
- const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
583
-
584
- // attempt snapshot sync if possible
585
- await trySnapshotSync(config, log);
586
-
587
- const epochCache = await EpochCache.create(config.rollupAddress, config, { dateProvider });
588
-
589
- // Track started resources so we can clean up on partial failure during node creation.
590
- const started: { stop?(): Promise<void> | void }[] = [];
591
- try {
592
- // Default the orphan-prune grace window from the block build duration when unset, so the archiver
593
- // waits roughly one build slot for a proposed checkpoint to arrive before pruning a block-only tip.
594
- config.orphanProposedBlockPruneGraceSeconds ??=
595
- config.blockDurationMs !== undefined ? Math.ceil(config.blockDurationMs / 1000) : MIN_EXECUTION_TIME;
596
-
597
- // Create world-state first so we can retrieve the initial header before constructing the archiver.
598
- const nativeWs = await createWorldState(config, options.genesis);
599
- const initialHeader = nativeWs.getInitialHeader();
600
- const initialBlockHash = await initialHeader.hash();
601
- const archiver = await createArchiver(
602
- config,
603
- { blobClient, epochCache, telemetry, dateProvider },
604
- {
605
- blockUntilSync: !config.skipArchiverInitialSync,
606
- // The non-pipelined automine sequencer publishes each checkpoint in-slot, so it never
607
- // leaves orphan proposed blocks; pruning would race its local push. See pruneOrphanProposedBlocks.
608
- enableOrphanProposedBlockPruning: !config.useAutomineSequencer,
609
- },
610
- initialHeader,
611
- initialBlockHash,
612
- );
613
- started.push(archiver);
614
-
615
- // The synchronizer takes ownership of the native world-state from here
616
- const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, nativeWs, telemetry);
617
- started.push(worldStateSynchronizer);
618
- const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
619
- let peerProofVerifier: ClientProtocolCircuitVerifier;
620
- let rpcProofVerifier: ClientProtocolCircuitVerifier;
621
- if (useRealVerifiers) {
622
- peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
623
- const rpcVerifier = await BBCircuitVerifier.new(config);
624
- rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
625
- } else {
626
- peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
627
- rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
628
- }
629
- started.push(peerProofVerifier, rpcProofVerifier);
630
-
631
- let debugLogStore: DebugLogStore;
632
- if (!config.realProofs) {
633
- log.warn(`Aztec node is accepting fake proofs`);
634
-
635
- debugLogStore = new InMemoryDebugLogStore();
636
- log.info(
637
- 'Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served',
638
- );
639
- } else {
640
- debugLogStore = new NullDebugLogStore();
641
- }
642
-
643
- const globalVariableBuilderConfig = {
644
- rollupAddress: config.rollupAddress,
645
- ethereumSlotDuration: config.ethereumSlotDuration,
646
- rollupVersion: BigInt(config.rollupVersion),
647
- l1GenesisTime,
648
- slotDuration: Number(slotDuration),
649
- };
650
-
651
- const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, globalVariableBuilderConfig);
652
- const feeProvider = new FeeProviderImpl(dateProvider, publicClient, globalVariableBuilderConfig);
653
-
654
- const proverOnly = config.enableProverNode && config.disableValidator;
655
- if (proverOnly) {
656
- log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
657
- }
658
-
659
- // create the tx pool and the p2p client, which will need the l2 block source
660
- const p2pClient = await createP2PClient(
661
- config,
662
- archiver,
663
- peerProofVerifier,
664
- worldStateSynchronizer,
665
- epochCache,
666
- feeProvider,
667
- packageVersion,
668
- dateProvider,
669
- telemetry,
670
- deps.p2pClientDeps,
671
- initialBlockHash,
672
- );
673
- started.push(p2pClient);
674
-
675
- // We'll accumulate sentinel watchers here
676
- const watchers: Watcher[] = [];
677
-
678
- // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
679
- // Override maxTxsPerCheckpoint with the validator-specific limit if set.
680
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
681
- {
682
- ...config,
683
- l1GenesisTime,
684
- slotDuration: Number(slotDuration),
685
- rollupManaLimit,
686
- maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint,
687
- },
688
- worldStateSynchronizer,
689
- archiver,
690
- dateProvider,
691
- telemetry,
692
- );
693
-
694
- let validatorClient: ValidatorClient | undefined;
695
-
696
- // Tracks successful checkpoint re-execution by a checkpoint proposal handler.
697
- const reexecutionTracker = new CheckpointReexecutionTracker();
698
-
699
- if (!config.disableValidator) {
700
- // Create validator client if required
701
- validatorClient = await createValidatorClient(config, {
702
- checkpointsBuilder: validatorCheckpointsBuilder,
703
- worldState: worldStateSynchronizer,
704
- p2pClient,
705
- telemetry,
706
- dateProvider,
707
- epochCache,
708
- blockSource: archiver,
709
- l1ToL2MessageSource: archiver,
710
- keyStoreManager,
711
- blobClient,
712
- reexecutionTracker,
713
- slashingProtectionDb: deps.slashingProtectionDb,
714
- });
715
-
716
- // If we have a validator client, register it as a source of offenses for the slasher,
717
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
718
- // like attestations or auths will fail.
719
- if (validatorClient) {
720
- watchers.push(validatorClient);
721
-
722
- const vc = validatorClient;
723
- const getValidatorAddresses = () => vc.getValidatorAddresses().map(a => a.toString());
724
- validatorClient.getProposalHandler().register(p2pClient, true, archiver, getValidatorAddresses);
725
-
726
- if (!options.dontStartSequencer) {
727
- await validatorClient.registerHandlers();
728
- }
729
- }
730
- }
731
-
732
- // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
733
- // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
734
- // while non-reexecution is used for validating the proposals and collecting their txs.
735
- // Checkpoint proposals rebuild blobs if the blob client can upload blobs.
736
- if (!validatorClient) {
737
- const reexecute = !!config.alwaysReexecuteBlockProposals;
738
- log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
739
- createProposalHandler(config, {
740
- checkpointsBuilder: validatorCheckpointsBuilder,
741
- worldState: worldStateSynchronizer,
742
- epochCache,
743
- blockSource: archiver,
744
- l1ToL2MessageSource: archiver,
745
- p2pClient,
746
- blobClient,
747
- dateProvider,
748
- telemetry,
749
- reexecutionTracker,
750
- }).register(p2pClient, reexecute, archiver);
751
- }
752
-
753
- // Start world state and wait for it to sync to the archiver.
754
- await worldStateSynchronizer.start();
755
-
756
- // Start p2p. Note that it depends on world state to be running.
757
- await p2pClient.start();
758
-
759
- let validatorsSentinel: Awaited<ReturnType<typeof createSentinel>> | undefined;
760
- let dataWithholdingWatcher: DataWithholdingWatcher | undefined;
761
- let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
762
- let attestedInvalidProposalWatcher: AttestedInvalidProposalWatcher | undefined;
763
- let broadcastedInvalidCheckpointProposalWatcher: BroadcastedInvalidCheckpointProposalWatcher | undefined;
764
- let checkpointEquivocationWatcher: CheckpointEquivocationWatcher | undefined;
765
-
766
- if (!proverOnly) {
767
- validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, reexecutionTracker, config);
768
- if (validatorsSentinel) {
769
- watchers.push(validatorsSentinel);
770
- }
771
-
772
- dataWithholdingWatcher = new DataWithholdingWatcher(
773
- epochCache,
774
- archiver,
775
- p2pClient.getTxProvider(),
776
- p2pClient,
777
- reexecutionTracker,
778
- { chainId: config.l1ChainId, rollupAddress: config.rollupAddress },
779
- config,
780
- );
781
- watchers.push(dataWithholdingWatcher);
782
-
783
- broadcastedInvalidCheckpointProposalWatcher = new BroadcastedInvalidCheckpointProposalWatcher(
784
- p2pClient,
785
- archiver,
786
- epochCache,
787
- config,
788
- );
789
- watchers.push(broadcastedInvalidCheckpointProposalWatcher);
790
-
791
- if (validatorClient) {
792
- attestedInvalidProposalWatcher = new AttestedInvalidProposalWatcher(
793
- p2pClient,
794
- validatorClient,
795
- archiver,
796
- epochCache,
797
- config,
798
- { log: log.createChild('attested-invalid-proposal-watcher') },
799
- );
800
- watchers.push(attestedInvalidProposalWatcher);
801
- }
802
-
803
- checkpointEquivocationWatcher = new CheckpointEquivocationWatcher(archiver, epochCache, config);
804
- watchers.push(checkpointEquivocationWatcher);
805
-
806
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config, log.getBindings());
807
- watchers.push(attestationsBlockWatcher);
808
- }
809
-
810
- const watchersToStart = compactArray([
811
- validatorsSentinel,
812
- dataWithholdingWatcher,
813
- attestationsBlockWatcher,
814
- broadcastedInvalidCheckpointProposalWatcher,
815
- attestedInvalidProposalWatcher,
816
- checkpointEquivocationWatcher,
817
- ]);
818
- const startedWatchers: Watcher[] = [];
819
- const stopStartedWatchers = async () => {
820
- for (const watcher of startedWatchers) {
821
- await tryStop(watcher);
822
- }
823
- };
824
-
825
- // Start p2p-related services once the archiver has completed sync
826
- void archiver
827
- .waitForInitialSync()
828
- .then(async () => {
829
- for (const watcher of watchersToStart) {
830
- await watcher.start();
831
- startedWatchers.push(watcher);
832
- }
833
- log.info(`All p2p services started`);
834
- })
835
- .catch(err => log.error('Failed to start p2p services after archiver sync', err));
836
- started.push({ stop: stopStartedWatchers });
837
-
838
- // Validator enabled, create/start relevant service
839
- let sequencer: SequencerClient | undefined;
840
- let automineSequencer: AutomineSequencer | undefined;
841
- let slasherClient: SlasherClientInterface | undefined;
842
- if (!config.disableValidator && validatorClient) {
843
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
844
- // as they are executed when the node is selected as proposer.
845
- const validatorAddresses = keyStoreManager
846
- ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses()
847
- : [];
848
-
849
- slasherClient = await createSlasher(
850
- config,
851
- pickL1ContractAddresses(config),
852
- getPublicClient(config),
853
- watchers,
854
- dateProvider,
855
- epochCache,
856
- validatorAddresses,
857
- undefined, // logger
858
- );
859
- await slasherClient.start();
860
- started.push(slasherClient);
861
-
862
- const l1TxUtils = config.sequencerPublisherForwarderAddress
863
- ? await createForwarderL1TxUtilsFromSigners(
864
- publicClient,
865
- keyStoreManager!.createAllValidatorPublisherSigners(),
866
- config.sequencerPublisherForwarderAddress,
867
- { ...config, scope: 'sequencer' },
868
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
869
- )
870
- : await createL1TxUtilsFromSigners(
871
- publicClient,
872
- keyStoreManager!.createAllValidatorPublisherSigners(),
873
- { ...config, scope: 'sequencer' },
874
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
875
- );
876
-
877
- // Create a funder L1TxUtils from the keystore funding account (if configured)
878
- const fundingSigner = keyStoreManager?.createFundingSigner();
879
- let funderL1TxUtils: L1TxUtils | undefined;
880
- if (fundingSigner) {
881
- const [funder] = await createL1TxUtilsFromSigners(
882
- publicClient,
883
- [fundingSigner],
884
- { ...config, scope: 'sequencer' },
885
- { telemetry, logger: log.createChild('l1-tx-utils:funder'), dateProvider },
886
- );
887
- funderL1TxUtils = funder;
888
- }
889
-
890
- // Create and start the sequencer client
891
- const checkpointsBuilder = new CheckpointsBuilder(
892
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration), rollupManaLimit },
893
- worldStateSynchronizer,
894
- archiver,
895
- dateProvider,
896
- telemetry,
897
- debugLogStore,
898
- );
899
-
900
- if (config.useAutomineSequencer) {
901
- // Test-only path: deterministic, queue-driven sequencer for non-block-building e2e tests.
902
- // See `AUTOMINE_E2E_OPTS` in `end-to-end/src/fixtures/fixtures.ts`.
903
- automineSequencer = await createAutomineSequencer({
904
- config,
905
- l1TxUtils,
906
- funderL1TxUtils,
907
- publicClient,
908
- rollupContract,
909
- epochCache,
910
- blobClient,
911
- telemetry,
912
- dateProvider,
913
- keyStoreManager: keyStoreManager!,
914
- validatorClient,
915
- checkpointsBuilder,
916
- globalVariableBuilder,
917
- worldStateSynchronizer,
918
- archiver,
919
- p2pClient,
920
- l1Constants: {
921
- l1GenesisTime,
922
- slotDuration: Number(slotDuration),
923
- ethereumSlotDuration: config.ethereumSlotDuration,
924
- rollupManaLimit,
925
- },
926
- log,
927
- });
928
- } else {
929
- sequencer = await SequencerClient.new(config, {
930
- ...deps,
931
- epochCache,
932
- l1TxUtils,
933
- funderL1TxUtils,
934
- validatorClient,
935
- p2pClient,
936
- worldStateSynchronizer,
937
- slasherClient,
938
- checkpointsBuilder,
939
- l2BlockSource: archiver,
940
- l1ToL2MessageSource: archiver,
941
- telemetry,
942
- dateProvider,
943
- blobClient,
944
- nodeKeyStore: keyStoreManager!,
945
- globalVariableBuilder,
946
- });
947
- }
948
- }
949
-
950
- if (!options.dontStartSequencer && sequencer) {
951
- await sequencer.start();
952
- started.push(sequencer);
953
- log.verbose(`Sequencer started`);
954
- } else if (sequencer) {
955
- log.warn(`Sequencer created but not started`);
956
- }
957
-
958
- if (!options.dontStartSequencer && automineSequencer) {
959
- await automineSequencer.start();
960
- started.push({ stop: () => automineSequencer!.stop() });
961
- log.verbose(`AutomineSequencer started`);
962
- } else if (automineSequencer) {
963
- log.warn(`AutomineSequencer created but not started`);
964
- }
965
-
966
- // Create prover node subsystem if enabled
967
- let proverNode: ProverNode | undefined;
968
- if (config.enableProverNode) {
969
- proverNode = await createProverNode(config, {
970
- ...deps.proverNodeDeps,
971
- telemetry,
972
- dateProvider,
973
- archiver,
974
- worldStateSynchronizer,
975
- p2pClient,
976
- epochCache,
977
- blobClient,
978
- keyStoreManager,
979
- });
980
-
981
- if (!options.dontStartProverNode) {
982
- await proverNode.start();
983
- started.push(proverNode);
984
- log.info(`Prover node subsystem started`);
985
- } else {
986
- log.info(`Prover node subsystem created but not started`);
987
- }
988
- }
989
-
990
- const node = new AztecNodeService(
991
- config,
992
- p2pClient,
993
- archiver,
994
- archiver,
995
- archiver,
996
- archiver,
997
- worldStateSynchronizer,
998
- sequencer,
999
- proverNode,
1000
- slasherClient,
1001
- validatorsSentinel,
1002
- stopStartedWatchers,
1003
- ethereumChain.chainInfo.id,
1004
- config.rollupVersion,
1005
- globalVariableBuilder,
1006
- feeProvider,
1007
- epochCache,
1008
- packageVersion,
1009
- peerProofVerifier,
1010
- rpcProofVerifier,
1011
- telemetry,
1012
- log,
1013
- blobClient,
1014
- validatorClient,
1015
- keyStoreManager,
1016
- debugLogStore,
1017
- automineSequencer,
1018
- );
1019
-
1020
- return node;
1021
- } catch (err) {
1022
- log.error('Failed during node creation, stopping started resources', err);
1023
- for (const resource of started.reverse()) {
1024
- await tryStop(resource);
1025
- }
1026
- throw err;
1027
- }
359
+ return this.blockProvider.getCheckpoints(from, limit, options);
1028
360
  }
1029
361
 
1030
362
  /**
@@ -1082,14 +414,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1082
414
  }
1083
415
 
1084
416
  public async getNodeInfo(): Promise<NodeInfo> {
1085
- const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses] = await Promise.all([
1086
- this.getNodeVersion(),
1087
- this.getVersion(),
1088
- this.getChainId(),
1089
- this.getEncodedEnr(),
1090
- this.getL1ContractAddresses(),
1091
- this.getProtocolContractAddresses(),
1092
- ]);
417
+ const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses, l1Constants] =
418
+ await Promise.all([
419
+ this.getNodeVersion(),
420
+ this.getVersion(),
421
+ this.getChainId(),
422
+ this.getEncodedEnr(),
423
+ this.getL1ContractAddresses(),
424
+ this.getProtocolContractAddresses(),
425
+ this.blockSource.getL1Constants(),
426
+ ]);
427
+
428
+ // Gas limits a single tx may declare on this network, derived from network-wide constants only (the
429
+ // timetable's blocks-per-checkpoint and the network-minimum per-block multipliers) — never this node's
430
+ // local caps or configured multipliers, which can make the node stricter at block-building time but
431
+ // cannot define what the network accepts for relay. Clients read txsLimits to set fallback gas limits.
432
+ const maxTxGas = getNetworkTxGasLimits(this.config, l1Constants);
1093
433
 
1094
434
  const nodeInfo: NodeInfo = {
1095
435
  nodeVersion,
@@ -1099,6 +439,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1099
439
  l1ContractAddresses: contractAddresses,
1100
440
  protocolContractAddresses: protocolContractAddresses,
1101
441
  realProofs: !!this.config.realProofs,
442
+ txsLimits: { gas: { daGas: maxTxGas.daGas, l2Gas: maxTxGas.l2Gas } },
1102
443
  };
1103
444
 
1104
445
  return nodeInfo;
@@ -1114,7 +455,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1114
455
  }
1115
456
 
1116
457
  public async getMaxPriorityFees(): Promise<GasFees> {
1117
- for await (const tx of this.p2pClient.iteratePendingTxs()) {
458
+ for await (const tx of this.p2pClient.iteratePendingTxs({ includeProof: false })) {
1118
459
  return tx.getGasSettings().maxPriorityFeesPerGas;
1119
460
  }
1120
461
 
@@ -1149,8 +490,17 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1149
490
  return this.contractDataSource.getContractClass(id);
1150
491
  }
1151
492
 
1152
- public getContract(address: AztecAddress): Promise<ContractInstanceWithAddress | undefined> {
1153
- return this.contractDataSource.getContract(address);
493
+ public async getContract(
494
+ address: AztecAddress,
495
+ referenceBlock: BlockParameter = 'latest',
496
+ ): Promise<ContractInstanceWithAddress | undefined> {
497
+ const blockData = await this.getBlockData(referenceBlock);
498
+ if (!blockData) {
499
+ throw new Error(
500
+ `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.`,
501
+ );
502
+ }
503
+ return this.contractDataSource.getContract(address, blockData.header.globalVariables.timestamp);
1154
504
  }
1155
505
 
1156
506
  public getPrivateLogsByTags(query: PrivateLogsQuery): Promise<LogResult[][]> {
@@ -1193,79 +543,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1193
543
  this.log.info(`Received tx ${txHash} in ${duration}ms`, { txHash });
1194
544
  }
1195
545
 
1196
- public async getTxReceipt<TGetTxReceiptOptions extends GetTxReceiptOptions = {}>(
546
+ public getTxReceipt<TGetTxReceiptOptions extends GetTxReceiptOptions = {}>(
1197
547
  txHash: TxHash,
1198
548
  options?: TGetTxReceiptOptions,
1199
549
  ): Promise<TxReceipt<TGetTxReceiptOptions>> {
1200
- // Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
1201
- // as a fallback if we don't find a mined tx effect in the archiver.
1202
- const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
1203
- const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
1204
-
1205
- // Then get the raw tx effect from the archiver, which tracks every tx in a mined block.
1206
- const indexed = await this.blockSource.getTxEffect(txHash);
1207
-
1208
- let receipt: TxReceipt;
1209
- if (indexed) {
1210
- receipt = await this.#assembleMinedReceipt(indexed, options);
1211
- } else if (isKnownToPool) {
1212
- // If the tx is in the pool but not in the archiver, it's pending.
1213
- // This handles race conditions between archiver and p2p, where the archiver
1214
- // has pruned the block in which a tx was mined, but p2p has not caught up yet.
1215
- let tx: Tx | undefined;
1216
- if (options?.includePendingTx) {
1217
- // The tx may have left the pool since we checked its status (mined or dropped); in that case we
1218
- // leave `tx` unset and still return a pending receipt.
1219
- const pendingTx = await this.p2pClient.getTxByHashFromPool(txHash);
1220
- tx = pendingTx && !options.includeProof ? pendingTx.withoutProof() : pendingTx;
1221
- }
1222
- receipt = new PendingTxReceipt(txHash, tx);
1223
- } else {
1224
- // Otherwise, if we don't know the tx, we consider it dropped.
1225
- receipt = new DroppedTxReceipt(txHash, 'Tx dropped by P2P node');
1226
- }
1227
-
1228
- this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
1229
-
1230
- return receipt;
1231
- }
1232
-
1233
- /**
1234
- * Assembles a {@link MinedTxReceipt} from a raw {@link IndexedTxEffect}, deriving the finalization status from the
1235
- * cached L2 tips and the epoch from the block's slot number.
1236
- */
1237
- async #assembleMinedReceipt(indexed: IndexedTxEffect, options?: GetTxReceiptOptions): Promise<MinedTxReceipt> {
1238
- const blockNumber = indexed.l2BlockNumber;
1239
- const [tips, l1Constants] = await Promise.all([this.blockSource.getL2Tips(), this.blockSource.getL1Constants()]);
1240
-
1241
- const status = this.#deriveMinedStatus(blockNumber, tips);
1242
- const epochNumber = getEpochAtSlot(indexed.slotNumber, l1Constants);
1243
-
1244
- return new MinedTxReceipt(
1245
- indexed.data.txHash,
1246
- status,
1247
- MinedTxReceipt.executionResultFromRevertCode(indexed.data.revertCode),
1248
- indexed.data.transactionFee.toBigInt(),
1249
- indexed.l2BlockHash,
1250
- blockNumber,
1251
- indexed.slotNumber,
1252
- indexed.txIndexInBlock,
1253
- epochNumber,
1254
- options?.includeTxEffect ? indexed.data : undefined,
1255
- /*debugLogs=*/ undefined,
1256
- );
1257
- }
1258
-
1259
- #deriveMinedStatus(blockNumber: BlockNumber, tips: L2Tips): MinedTxStatus {
1260
- if (blockNumber <= tips.finalized.block.number) {
1261
- return TxStatus.FINALIZED;
1262
- } else if (blockNumber <= tips.proven.block.number) {
1263
- return TxStatus.PROVEN;
1264
- } else if (blockNumber <= tips.checkpointed.block.number) {
1265
- return TxStatus.CHECKPOINTED;
1266
- } else {
1267
- return TxStatus.PROPOSED;
1268
- }
550
+ return this.txReceiptBuilder.getTxReceipt(txHash, options);
1269
551
  }
1270
552
 
1271
553
  public getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined> {
@@ -1305,151 +587,83 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1305
587
  * @param after - The last known pending tx. Used for pagination
1306
588
  * @returns - The pending txs.
1307
589
  */
1308
- public getPendingTxs(limit?: number, after?: TxHash): Promise<Tx[]> {
1309
- return this.p2pClient!.getPendingTxs(limit, after);
590
+ public getPendingTxs(limit?: number, after?: TxHash, options?: GetTxByHashOptions): Promise<Tx[]> {
591
+ return this.p2pClient!.getPendingTxs(limit, after, options);
1310
592
  }
1311
593
 
1312
594
  public getPendingTxCount(): Promise<number> {
1313
595
  return this.p2pClient!.getPendingTxCount();
1314
596
  }
1315
597
 
598
+ public getPeers(includePending?: boolean): Promise<PeerInfo[]> {
599
+ return this.p2pClient!.getPeers(includePending);
600
+ }
601
+
602
+ public getCheckpointAttestationsForSlot(
603
+ slot: SlotNumber,
604
+ proposalPayloadHash?: CheckpointProposalHash,
605
+ ): Promise<CheckpointAttestation[]> {
606
+ return this.p2pClient!.getCheckpointAttestationsForSlot(slot, proposalPayloadHash);
607
+ }
608
+
609
+ public getProposalsForSlot(slot: SlotNumber): Promise<ProposalsForSlot> {
610
+ return this.p2pClient!.getProposalsForSlot(slot);
611
+ }
612
+
1316
613
  /**
1317
- * Method to retrieve a single tx from the mempool or unfinalized chain.
614
+ * Method to retrieve a single tx from the mempool or unfinalized chain. The tx's proof is only loaded and returned
615
+ * when `includeProof` is set.
1318
616
  * @param txHash - The transaction hash to return.
617
+ * @param options - Options for the returned tx (eg whether to include its proof).
1319
618
  * @returns - The tx if it exists.
1320
619
  */
1321
- public getTxByHash(txHash: TxHash): Promise<Tx | undefined> {
1322
- return Promise.resolve(this.p2pClient!.getTxByHashFromPool(txHash));
620
+ public getTxByHash(txHash: TxHash, options?: GetTxByHashOptions): Promise<Tx | undefined> {
621
+ return this.p2pClient!.getTxByHashFromPool(txHash, { includeProof: !!options?.includeProof });
1323
622
  }
1324
623
 
1325
624
  /**
1326
- * Method to retrieve txs from the mempool or unfinalized chain.
625
+ * Method to retrieve txs from the mempool or unfinalized chain. The txs' proofs are only loaded and returned when
626
+ * `includeProof` is set.
1327
627
  * @param txHash - The transaction hash to return.
628
+ * @param options - Options for the returned txs (eg whether to include their proofs).
1328
629
  * @returns - The txs if it exists.
1329
630
  */
1330
- public async getTxsByHash(txHashes: TxHash[]): Promise<Tx[]> {
1331
- return compactArray(await Promise.all(txHashes.map(txHash => this.getTxByHash(txHash))));
631
+ public async getTxsByHash(txHashes: TxHash[], options?: GetTxByHashOptions): Promise<Tx[]> {
632
+ const txs = await this.p2pClient!.getTxsByHashFromPool(txHashes, { includeProof: !!options?.includeProof });
633
+ return compactArray(txs);
1332
634
  }
1333
635
 
1334
- public async findLeavesIndexes(
636
+ public findLeavesIndexes(
1335
637
  referenceBlock: BlockParameter,
1336
638
  treeId: MerkleTreeId,
1337
639
  leafValues: Fr[],
1338
640
  ): Promise<(DataInBlock<bigint> | undefined)[]> {
1339
- const committedDb = await this.getWorldState(referenceBlock);
1340
- const maybeIndices = await committedDb.findLeafIndices(
1341
- treeId,
1342
- leafValues.map(x => x.toBuffer()),
1343
- );
1344
- // Filter out undefined values to query block numbers only for found leaves
1345
- const definedIndices = maybeIndices.filter(x => x !== undefined);
1346
-
1347
- // Now we find the block numbers for the defined indices
1348
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
1349
-
1350
- // Build a map from leaf index to block number
1351
- const indexToBlockNumber = new Map<bigint, BlockNumber>();
1352
- for (let i = 0; i < definedIndices.length; i++) {
1353
- const blockNumber = blockNumbers[i];
1354
- if (blockNumber === undefined) {
1355
- throw new Error(
1356
- `Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`,
1357
- );
1358
- }
1359
- indexToBlockNumber.set(definedIndices[i], blockNumber);
1360
- }
1361
-
1362
- // Get unique block numbers in order to optimize num calls to getLeafValue function.
1363
- const uniqueBlockNumbers = [...new Set(indexToBlockNumber.values())];
1364
-
1365
- // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
1366
- const blockHashes = await Promise.all(
1367
- uniqueBlockNumbers.map(blockNumber => {
1368
- return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1369
- }),
1370
- );
1371
-
1372
- // Build a map from block number to block hash
1373
- const blockNumberToHash = new Map<BlockNumber, BlockHash>();
1374
- for (let i = 0; i < uniqueBlockNumbers.length; i++) {
1375
- const blockHash = blockHashes[i];
1376
- if (blockHash === undefined) {
1377
- throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
1378
- }
1379
- blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
1380
- }
1381
-
1382
- // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
1383
- return maybeIndices.map(index => {
1384
- if (index === undefined) {
1385
- return undefined;
1386
- }
1387
- const blockNumber = indexToBlockNumber.get(index);
1388
- if (blockNumber === undefined) {
1389
- throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1390
- }
1391
- const l2BlockHash = blockNumberToHash.get(blockNumber);
1392
- if (l2BlockHash === undefined) {
1393
- throw new Error(`Block hash not found for block number ${blockNumber}`);
1394
- }
1395
- return {
1396
- l2BlockNumber: blockNumber,
1397
- l2BlockHash,
1398
- data: index,
1399
- };
1400
- });
641
+ return this.worldStateQueries.findLeavesIndexes(referenceBlock, treeId, leafValues);
1401
642
  }
1402
643
 
1403
- public async getBlockHashMembershipWitness(
644
+ public getBlockHashMembershipWitness(
1404
645
  referenceBlock: BlockParameter,
1405
646
  blockHash: BlockHash,
1406
647
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
1407
- // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
1408
- // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1409
- // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1410
- const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1411
- if (referenceBlockNumber === BlockNumber.ZERO) {
1412
- // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
1413
- return undefined;
1414
- }
1415
- const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
1416
- const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
1417
- return pathAndIndex === undefined
1418
- ? undefined
1419
- : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
648
+ return this.worldStateQueries.getBlockHashMembershipWitness(referenceBlock, blockHash);
1420
649
  }
1421
650
 
1422
- public async getNoteHashMembershipWitness(
651
+ public getNoteHashMembershipWitness(
1423
652
  referenceBlock: BlockParameter,
1424
653
  noteHash: Fr,
1425
654
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
1426
- const committedDb = await this.getWorldState(referenceBlock);
1427
- const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
1428
- MerkleTreeId.NOTE_HASH_TREE,
1429
- [noteHash],
1430
- );
1431
- return pathAndIndex === undefined
1432
- ? undefined
1433
- : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
655
+ return this.worldStateQueries.getNoteHashMembershipWitness(referenceBlock, noteHash);
1434
656
  }
1435
657
 
1436
- public async getL1ToL2MessageMembershipWitness(
658
+ public getL1ToL2MessageMembershipWitness(
1437
659
  referenceBlock: BlockParameter,
1438
660
  l1ToL2Message: Fr,
1439
661
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
1440
- const db = await this.getWorldState(referenceBlock);
1441
- const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
1442
- if (!witness) {
1443
- return undefined;
1444
- }
1445
-
1446
- // REFACTOR: Return a MembershipWitness object
1447
- return [witness.index, witness.path];
662
+ return this.worldStateQueries.getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message);
1448
663
  }
1449
664
 
1450
- public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
1451
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1452
- return messageIndex !== undefined ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
665
+ public getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
666
+ return this.worldStateQueries.getL1ToL2MessageCheckpoint(l1ToL2Message);
1453
667
  }
1454
668
 
1455
669
  /**
@@ -1460,12 +674,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1460
674
  * @param epoch - The epoch at which to get the data.
1461
675
  * @returns The L2 to L1 messages (empty array if the epoch is not found).
1462
676
  */
1463
- public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
1464
- const blocks = await this.blockSource.getBlocks({ epoch, onlyCheckpointed: true });
1465
- const blocksInCheckpoints = chunkBy(blocks, block => block.header.globalVariables.slotNumber);
1466
- return blocksInCheckpoints.map(slotBlocks =>
1467
- slotBlocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1468
- );
677
+ public getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
678
+ return this.worldStateQueries.getL2ToL1Messages(epoch);
1469
679
  }
1470
680
 
1471
681
  /**
@@ -1477,77 +687,29 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1477
687
  message: Fr,
1478
688
  messageIndexInTx?: number,
1479
689
  ): Promise<L2ToL1MembershipWitness | undefined> {
1480
- return this.blockSource.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
690
+ return this.worldStateQueries.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
1481
691
  }
1482
692
 
1483
- public async getNullifierMembershipWitness(
693
+ public getNullifierMembershipWitness(
1484
694
  referenceBlock: BlockParameter,
1485
695
  nullifier: Fr,
1486
696
  ): Promise<NullifierMembershipWitness | undefined> {
1487
- const db = await this.getWorldState(referenceBlock);
1488
- const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
1489
- if (!witness) {
1490
- return undefined;
1491
- }
1492
-
1493
- const { index, path } = witness;
1494
- const leafPreimage = await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1495
- if (!leafPreimage) {
1496
- return undefined;
1497
- }
1498
-
1499
- return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
697
+ return this.worldStateQueries.getNullifierMembershipWitness(referenceBlock, nullifier);
1500
698
  }
1501
699
 
1502
- public async getLowNullifierMembershipWitness(
700
+ public getLowNullifierMembershipWitness(
1503
701
  referenceBlock: BlockParameter,
1504
702
  nullifier: Fr,
1505
703
  ): Promise<NullifierMembershipWitness | undefined> {
1506
- const committedDb = await this.getWorldState(referenceBlock);
1507
- const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1508
- if (!findResult) {
1509
- return undefined;
1510
- }
1511
- const { index, alreadyPresent } = findResult;
1512
- if (alreadyPresent) {
1513
- throw new Error(
1514
- `Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`,
1515
- );
1516
- }
1517
- const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
1518
-
1519
- const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1520
- return new NullifierMembershipWitness(BigInt(index), preimageData as NullifierLeafPreimage, siblingPath);
704
+ return this.worldStateQueries.getLowNullifierMembershipWitness(referenceBlock, nullifier);
1521
705
  }
1522
706
 
1523
- async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1524
- const committedDb = await this.getWorldState(referenceBlock);
1525
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1526
- if (!lowLeafResult) {
1527
- return undefined;
1528
- } else {
1529
- const preimage = (await committedDb.getLeafPreimage(
1530
- MerkleTreeId.PUBLIC_DATA_TREE,
1531
- lowLeafResult.index,
1532
- )) as PublicDataTreeLeafPreimage;
1533
- const path = await committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1534
- return new PublicDataWitness(lowLeafResult.index, preimage, path);
1535
- }
707
+ public getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
708
+ return this.worldStateQueries.getPublicDataWitness(referenceBlock, leafSlot);
1536
709
  }
1537
710
 
1538
- public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1539
- const committedDb = await this.getWorldState(referenceBlock);
1540
- const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1541
-
1542
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1543
- if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
1544
- return Fr.ZERO;
1545
- }
1546
- const preimage = (await committedDb.getLeafPreimage(
1547
- MerkleTreeId.PUBLIC_DATA_TREE,
1548
- lowLeafResult.index,
1549
- )) as PublicDataTreeLeafPreimage;
1550
- return preimage.leaf.value;
711
+ public getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
712
+ return this.worldStateQueries.getPublicStorageAt(referenceBlock, contract, slot);
1551
713
  }
1552
714
 
1553
715
  /**
@@ -1559,126 +721,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1559
721
  @trackSpan('AztecNodeService.simulatePublicCalls', (tx: Tx) => ({
1560
722
  [Attributes.TX_HASH]: tx.getTxHash().toString(),
1561
723
  }))
1562
- public async simulatePublicCalls(
724
+ public simulatePublicCalls(
1563
725
  tx: Tx,
1564
726
  skipFeeEnforcement = false,
1565
727
  overrides?: SimulationOverrides,
1566
728
  ): Promise<PublicSimulationOutput> {
1567
- // Check total gas limit for simulation
1568
- const gasSettings = tx.data.constants.txContext.gasSettings;
1569
- const txGasLimit = gasSettings.gasLimits.l2Gas;
1570
- const teardownGasLimit = gasSettings.teardownGasLimits.l2Gas;
1571
- if (txGasLimit + teardownGasLimit > this.config.rpcSimulatePublicMaxGasLimit) {
1572
- throw new BadRequestError(
1573
- `Transaction total gas limit ${
1574
- txGasLimit + teardownGasLimit
1575
- } (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${
1576
- this.config.rpcSimulatePublicMaxGasLimit
1577
- } for simulation`,
1578
- );
1579
- }
1580
-
1581
- const txHash = tx.getTxHash();
1582
- const l2Tips = await this.blockSource.getL2Tips();
1583
- const latestBlockNumber = l2Tips.proposed.number;
1584
- const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1585
-
1586
- // If sequencer is not initialized, we just set these values to zero for simulation.
1587
- const coinbase = EthAddress.ZERO;
1588
- const feeRecipient = AztecAddress.ZERO;
1589
-
1590
- const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(
1591
- blockNumber,
1592
- coinbase,
1593
- feeRecipient,
1594
- );
1595
-
1596
- const publicProcessorFactory = new PublicProcessorFactory(
1597
- this.contractDataSource,
1598
- new DateProvider(),
1599
- this.telemetry,
1600
- this.log.getBindings(),
1601
- );
1602
-
1603
- this.log.verbose(`Simulating public calls for tx ${txHash}`, {
1604
- globalVariables: newGlobalVariables.toInspect(),
1605
- txHash,
1606
- blockNumber,
1607
- });
1608
-
1609
- // Ensure world-state has caught up with the latest block we loaded from the archiver
1610
- await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1611
-
1612
- // If we detect the next block would start a new checkpoint, then insert L1-to-L2 messages into
1613
- // the world state tree so simulation can take them into account. We detect if the next block would
1614
- // start a new checkpoint by checking if the proposed checkpoint's block number matches the latest block number,
1615
- // which means the next block would be the first block of the next checkpoint.
1616
- const targetCheckpoint = CheckpointNumber(
1617
- (l2Tips.proposedCheckpoint.checkpoint.number ?? CheckpointNumber.ZERO) + 1,
1618
- );
1619
- const nextCheckpointMessages: Fr[] | undefined =
1620
- l2Tips.proposedCheckpoint.block.number === l2Tips.proposed.number
1621
- ? await this.l1ToL2MessageSource.getL1ToL2Messages(targetCheckpoint).catch(err => {
1622
- if (isErrorClass(err, L1ToL2MessagesNotReadyError)) {
1623
- this.log.warn(
1624
- `L1-to-L2 messages for checkpoint ${targetCheckpoint} are not ready yet (simulating without them)`,
1625
- );
1626
- } else {
1627
- this.log.error(
1628
- `Failed to get L1-to-L2 messages for checkpoint ${targetCheckpoint} (simulating without them)`,
1629
- err,
1630
- );
1631
- }
1632
- return undefined;
1633
- })
1634
- : undefined;
1635
-
1636
- // Request a new fork of the world state at the latest block number, and apply any overrides and next checkpoint messages to it before simulation
1637
- await using merkleTreeFork = await this.worldStateSynchronizer.fork(latestBlockNumber);
1638
-
1639
- if (nextCheckpointMessages !== undefined) {
1640
- this.log.debug(
1641
- `Appending ${nextCheckpointMessages.length} L1-to-L2 messages to the world state tree for the next checkpoint`,
1642
- { checkpointNumber: l2Tips.proposedCheckpoint.checkpoint.number + 1 },
1643
- );
1644
- await appendL1ToL2MessagesToTree(merkleTreeFork, nextCheckpointMessages);
1645
- }
1646
- await applyPublicDataOverrides(merkleTreeFork, overrides?.publicStorage);
1647
-
1648
- const config = PublicSimulatorConfig.from({
1649
- skipFeeEnforcement,
1650
- collectDebugLogs: true,
1651
- collectHints: false,
1652
- collectCallMetadata: true,
1653
- collectStatistics: false,
1654
- collectionLimits: CollectionLimitsConfig.from({
1655
- maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads,
1656
- }),
1657
- });
1658
-
1659
- const contractsDB = new PublicContractsDB(this.contractDataSource, this.log.getBindings());
1660
- if (overrides?.contracts) {
1661
- contractsDB.addContracts(Object.values(overrides.contracts).map(({ instance }) => instance));
1662
- }
1663
- const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config, contractsDB);
1664
-
1665
- // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1666
- const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1667
- // REFACTOR: Consider returning the error rather than throwing
1668
- if (failedTxs.length) {
1669
- this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
1670
- throw failedTxs[0].error;
1671
- }
1672
-
1673
- const [processedTx] = processedTxs;
1674
- return new PublicSimulationOutput(
1675
- processedTx.revertReason,
1676
- processedTx.globalVariables,
1677
- processedTx.txEffect,
1678
- returns,
1679
- processedTx.gasUsed,
1680
- debugLogs,
1681
- );
729
+ return this.nodePublicCallsSimulator.simulate(tx, skipFeeEnforcement, overrides);
1682
730
  }
1683
731
 
1684
732
  public async isValidTx(
@@ -1692,6 +740,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1692
740
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1693
741
  const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1694
742
  const l1Constants = await this.blockSource.getL1Constants();
743
+ // Enforce the same network admission limit the node advertises in getNodeInfo (network-wide, not this
744
+ // node's local caps), so a tx the wallet sized against txsLimits is not rejected here.
745
+ const networkTxGasLimits = getNetworkTxGasLimits(this.config, l1Constants);
1695
746
  const validator = createTxValidatorForAcceptingTxsOverRPC(
1696
747
  db,
1697
748
  this.contractDataSource,
@@ -1707,10 +758,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1707
758
  ],
1708
759
  gasFees: await this.getCurrentMinFees(),
1709
760
  skipFeeEnforcement,
761
+ isSimulation,
1710
762
  txsPermitted: !this.config.disableTransactions,
1711
- rollupManaLimit: l1Constants.rollupManaLimit,
1712
- maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1713
- maxBlockDAGas: this.config.validateMaxDABlockGas,
763
+ maxTxL2Gas: networkTxGasLimits.l2Gas,
764
+ maxTxDAGas: networkTxGasLimits.daGas,
1714
765
  },
1715
766
  this.log.getBindings(),
1716
767
  );
@@ -2054,92 +1105,33 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
2054
1105
  }
2055
1106
  }
2056
1107
 
2057
- /**
2058
- * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
2059
- * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
2060
- * @returns An instance of a committed MerkleTreeOperations
2061
- */
2062
- protected async getWorldState(block: BlockParameter) {
2063
- const query = this.normalizeBlockParameter(block);
2064
-
2065
- // When the request anchors on a specific block hash, resolve it against the archiver up front and
2066
- // drive the world-state sync to that exact block number and hash. Resolving against the archiver
2067
- // first fails fast with a clear reorg error if the hash is unknown, and passing the hash to the
2068
- // synchronizer makes the sync reorg-aware: it barriers until the archive-tree commit for that block
2069
- // has landed and verifies it matches the requested fork, instead of syncing to bare latest height
2070
- // and then racing the snapshot read below against an in-flight archive-tree write.
2071
- const requestedHash = 'hash' in query ? query.hash : undefined;
2072
- const anchorBlockNumber = requestedHash !== undefined ? await this.resolveBlockNumber(query) : undefined;
2073
-
2074
- let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
2075
- try {
2076
- // Attempt to sync the world state if necessary
2077
- blockSyncedTo = await this.#syncWorldState(anchorBlockNumber, requestedHash);
2078
- } catch (err) {
2079
- this.log.error(`Error getting world state: ${err}`);
2080
- }
2081
-
2082
- if ('tag' in query && query.tag === 'proposed') {
2083
- this.log.debug(`Using committed db for latest block, world state synced upto ${blockSyncedTo}`);
2084
- return this.worldStateSynchronizer.getCommitted();
1108
+ public async prove(upToCheckpoint?: CheckpointNumber): Promise<CheckpointNumber> {
1109
+ if (!this.automineSequencer) {
1110
+ throw new BadRequestError('Cannot prove checkpoint: no automine sequencer is running');
2085
1111
  }
1112
+ return await this.automineSequencer.prove(upToCheckpoint);
1113
+ }
2086
1114
 
2087
- const blockNumber = anchorBlockNumber ?? (await this.resolveBlockNumber(query));
2088
-
2089
- // Check it's within world state sync range
2090
- if (blockNumber > blockSyncedTo) {
2091
- throw new Error(
2092
- `Queried block ${inspectBlockParameter(block)} not yet synced by the node (node is synced upto ${blockSyncedTo}).`,
2093
- );
2094
- }
2095
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
2096
-
2097
- const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
2098
-
2099
- // Double-check world-state synced to the same block hash as was requested.
2100
- // Block 0 is skipped: the snapshot returned by `getSnapshot(0)` is the *pre*-genesis archive
2101
- // (size 0), so leaf 0 is not yet inserted from that snapshot's view even though block 0's hash
2102
- // does live at archive index 0 in the committed tree. The genesis hash is already validated by
2103
- // the archiver when it resolves the hash query to block number 0.
2104
- if (requestedHash !== undefined && blockNumber !== BlockNumber.ZERO) {
2105
- const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
2106
- if (!blockHash || !requestedHash.equals(blockHash)) {
2107
- throw new Error(
2108
- `Block hash ${requestedHash.toString()} not found in world state at block number ${blockNumber} (world state has ${blockHash?.toString() ?? 'no hash'} at that index, genesis header hash is ${this.blockSource.getGenesisBlockHash().toString()}). If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
2109
- );
2110
- }
1115
+ public async warpL2TimeAtLeastTo(targetTimestamp: number): Promise<void> {
1116
+ if (!this.automineSequencer) {
1117
+ throw new BadRequestError('Cannot warp L2 time: no automine sequencer is running');
2111
1118
  }
2112
-
2113
- return snapshot;
1119
+ await this.automineSequencer.warpTo(targetTimestamp);
2114
1120
  }
2115
1121
 
2116
- /** Resolves any {@link BlockParameter} variant to a concrete block number. */
2117
- protected async resolveBlockNumber(block: BlockParameter): Promise<BlockNumber> {
2118
- const query = this.normalizeBlockParameter(block);
2119
- const blockNumber = await this.blockSource.getBlockNumber(query);
2120
- if (blockNumber === undefined) {
2121
- if ('hash' in query) {
2122
- throw new Error(
2123
- `Block hash ${query.hash.toString()} not found when querying world state. If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
2124
- );
2125
- }
2126
- if ('archive' in query) {
2127
- throw new Error(`Block with archive ${query.archive.toString()} not found.`);
2128
- }
2129
- throw new Error(`Block not found for ${inspectBlockParameter(block)}.`);
1122
+ public async warpL2TimeAtLeastBy(duration: number): Promise<void> {
1123
+ if (!this.automineSequencer) {
1124
+ throw new BadRequestError('Cannot warp L2 time: no automine sequencer is running');
2130
1125
  }
2131
- return blockNumber;
1126
+ await this.automineSequencer.warpBy(duration);
2132
1127
  }
2133
1128
 
2134
1129
  /**
2135
- * Ensure the world state is synced.
2136
- * @param targetBlockNumber - Block to sync up to. Defaults to the latest block known to the archiver.
2137
- * @param blockHash - If provided, the synchronizer verifies the block at `targetBlockNumber` matches this
2138
- * hash, resyncing (and so detecting reorgs) if it does not yet match or has been reorged away.
2139
- * @returns A promise that fulfils once the world state is synced
1130
+ * Returns a committed world-state view at `block`, driving sync first. Delegates to
1131
+ * {@link NodeWorldStateQueries.getWorldState}; kept as a protected method so subclasses and tests can
1132
+ * exercise the node's block-resolution and reorg-aware sync behavior.
2140
1133
  */
2141
- async #syncWorldState(targetBlockNumber?: BlockNumber, blockHash?: BlockHash): Promise<BlockNumber> {
2142
- const target = targetBlockNumber ?? (await this.blockSource.getBlockNumber());
2143
- return await this.worldStateSynchronizer.syncImmediate(target, blockHash);
1134
+ protected getWorldState(block: BlockParameter) {
1135
+ return this.worldStateQueries.getWorldState(block);
2144
1136
  }
2145
1137
  }