@aztec/aztec-node 0.0.1-commit.c31f2472 → 0.0.1-commit.c52d6e7

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