@aztec/aztec-node 0.0.1-commit.42ee6df9b → 0.0.1-commit.431c48d

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