@aztec/aztec-node 0.0.1-commit.b655e406 → 0.0.1-commit.b8a057fa

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 (77) 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 +26 -8
  5. package/dest/aztec-node/config.d.ts.map +1 -1
  6. package/dest/aztec-node/config.js +32 -8
  7. package/dest/aztec-node/node_metrics.d.ts +1 -1
  8. package/dest/aztec-node/node_metrics.d.ts.map +1 -1
  9. package/dest/aztec-node/node_metrics.js +9 -16
  10. package/dest/aztec-node/node_public_calls_simulator.d.ts +97 -0
  11. package/dest/aztec-node/node_public_calls_simulator.d.ts.map +1 -0
  12. package/dest/aztec-node/node_public_calls_simulator.js +351 -0
  13. package/dest/aztec-node/public_data_overrides.d.ts +13 -0
  14. package/dest/aztec-node/public_data_overrides.d.ts.map +1 -0
  15. package/dest/aztec-node/public_data_overrides.js +21 -0
  16. package/dest/aztec-node/register_node_rpc_handlers.d.ts +10 -0
  17. package/dest/aztec-node/register_node_rpc_handlers.d.ts.map +1 -0
  18. package/dest/aztec-node/register_node_rpc_handlers.js +31 -0
  19. package/dest/aztec-node/server.d.ts +163 -225
  20. package/dest/aztec-node/server.d.ts.map +1 -1
  21. package/dest/aztec-node/server.js +897 -703
  22. package/dest/bin/index.d.ts +1 -1
  23. package/dest/bin/index.js +15 -10
  24. package/dest/factory.d.ts +33 -0
  25. package/dest/factory.d.ts.map +1 -0
  26. package/dest/factory.js +523 -0
  27. package/dest/index.d.ts +3 -1
  28. package/dest/index.d.ts.map +1 -1
  29. package/dest/index.js +2 -0
  30. package/dest/modules/block_parameter.d.ts +25 -0
  31. package/dest/modules/block_parameter.d.ts.map +1 -0
  32. package/dest/modules/block_parameter.js +100 -0
  33. package/dest/modules/node_block_provider.d.ts +19 -0
  34. package/dest/modules/node_block_provider.d.ts.map +1 -0
  35. package/dest/modules/node_block_provider.js +112 -0
  36. package/dest/modules/node_tx_receipt.d.ts +24 -0
  37. package/dest/modules/node_tx_receipt.d.ts.map +1 -0
  38. package/dest/modules/node_tx_receipt.js +70 -0
  39. package/dest/modules/node_world_state_queries.d.ts +65 -0
  40. package/dest/modules/node_world_state_queries.d.ts.map +1 -0
  41. package/dest/modules/node_world_state_queries.js +272 -0
  42. package/dest/sentinel/config.d.ts +3 -2
  43. package/dest/sentinel/config.d.ts.map +1 -1
  44. package/dest/sentinel/config.js +15 -5
  45. package/dest/sentinel/factory.d.ts +6 -4
  46. package/dest/sentinel/factory.d.ts.map +1 -1
  47. package/dest/sentinel/factory.js +13 -6
  48. package/dest/sentinel/index.d.ts +1 -1
  49. package/dest/sentinel/sentinel.d.ts +160 -34
  50. package/dest/sentinel/sentinel.d.ts.map +1 -1
  51. package/dest/sentinel/sentinel.js +285 -125
  52. package/dest/sentinel/store.d.ts +11 -10
  53. package/dest/sentinel/store.d.ts.map +1 -1
  54. package/dest/sentinel/store.js +36 -23
  55. package/dest/test/index.d.ts +3 -3
  56. package/dest/test/index.d.ts.map +1 -1
  57. package/package.json +32 -28
  58. package/src/aztec-node/block_response_helpers.ts +161 -0
  59. package/src/aztec-node/config.ts +64 -21
  60. package/src/aztec-node/node_metrics.ts +6 -17
  61. package/src/aztec-node/node_public_calls_simulator.ts +394 -0
  62. package/src/aztec-node/public_data_overrides.ts +35 -0
  63. package/src/aztec-node/register_node_rpc_handlers.ts +29 -0
  64. package/src/aztec-node/server.ts +689 -940
  65. package/src/bin/index.ts +19 -12
  66. package/src/factory.ts +688 -0
  67. package/src/index.ts +2 -0
  68. package/src/modules/block_parameter.ts +93 -0
  69. package/src/modules/node_block_provider.ts +149 -0
  70. package/src/modules/node_tx_receipt.ts +115 -0
  71. package/src/modules/node_world_state_queries.ts +374 -0
  72. package/src/sentinel/README.md +103 -0
  73. package/src/sentinel/config.ts +18 -6
  74. package/src/sentinel/factory.ts +23 -13
  75. package/src/sentinel/sentinel.ts +358 -157
  76. package/src/sentinel/store.ts +43 -34
  77. package/src/test/index.ts +2 -2
@@ -1,59 +1,48 @@
1
- import { Archiver, createArchiver } from '@aztec/archiver';
2
- import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
3
- import { type BlobSinkClientInterface, createBlobSinkClient } from '@aztec/blob-sink/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
- INITIAL_L2_BLOCK_NUM,
7
- type L1_TO_L2_MSG_TREE_HEIGHT,
8
- type NOTE_HASH_TREE_HEIGHT,
9
- type NULLIFIER_TREE_HEIGHT,
10
- type PUBLIC_DATA_TREE_HEIGHT,
11
- } from '@aztec/constants';
12
- import { EpochCache, type EpochCacheInterface } from '@aztec/epoch-cache';
13
- import {
14
- type L1ContractAddresses,
15
- RegistryContract,
16
- RollupContract,
17
- createEthereumChain,
18
- getPublicClient,
19
- } from '@aztec/ethereum';
20
- 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';
17
+ import { Fr } from '@aztec/foundation/curves/bn254';
21
18
  import { EthAddress } from '@aztec/foundation/eth-address';
22
- import { Fr } from '@aztec/foundation/fields';
23
19
  import { BadRequestError } from '@aztec/foundation/json-rpc';
24
20
  import { type Logger, createLogger } from '@aztec/foundation/log';
25
- import { SerialQueue } from '@aztec/foundation/queue';
21
+ import { retryUntil } from '@aztec/foundation/retry';
26
22
  import { count } from '@aztec/foundation/string';
27
- import { DateProvider, Timer } from '@aztec/foundation/timer';
23
+ import { Timer } from '@aztec/foundation/timer';
28
24
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
29
25
  import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
30
- import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
31
- import { createL1TxUtilsWithBlobsFromEthSigner } from '@aztec/node-lib/factories';
32
- 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';
33
28
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
34
- import {
35
- BlockBuilder,
36
- GlobalVariableBuilder,
37
- SequencerClient,
38
- type SequencerPublisher,
39
- createValidatorForAcceptingTxs,
40
- } from '@aztec/sequencer-client';
41
- import { PublicProcessorFactory } from '@aztec/simulator/server';
42
- import {
43
- AttestationsBlockWatcher,
44
- EpochPruneWatcher,
45
- type SlasherClientInterface,
46
- type Watcher,
47
- createSlasher,
48
- } from '@aztec/slasher';
29
+ import type { ProverNode } from '@aztec/prover-node';
30
+ import { SequencerClient } from '@aztec/sequencer-client';
31
+ import { AutomineSequencer } from '@aztec/sequencer-client/automine';
32
+ import type { 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';
49
35
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
50
36
  import {
51
- type InBlock,
52
- type L2Block,
53
- L2BlockHash,
54
- type L2BlockNumber,
37
+ type BlockData,
38
+ BlockHash,
39
+ type BlockParameter,
40
+ type CheckpointsQuery,
41
+ type DataInBlock,
55
42
  type L2BlockSource,
56
- type PublishedL2Block,
43
+ type L2BlockTag,
44
+ type L2Tips,
45
+ inspectBlockParameter,
57
46
  } from '@aztec/stdlib/block';
58
47
  import type {
59
48
  ContractClassPublic,
@@ -62,16 +51,25 @@ import type {
62
51
  NodeInfo,
63
52
  ProtocolContractAddresses,
64
53
  } from '@aztec/stdlib/contract';
65
- import type { GasFees } from '@aztec/stdlib/gas';
66
- import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
67
- import {
68
- type AztecNode,
69
- type AztecNodeAdmin,
70
- type AztecNodeAdminConfig,
71
- AztecNodeAdminConfigSchema,
72
- type GetContractClassLogsResponse,
73
- 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,
74
71
  } from '@aztec/stdlib/interfaces/client';
72
+ import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
75
73
  import {
76
74
  type AllowedElement,
77
75
  type ClientProtocolCircuitVerifier,
@@ -81,24 +79,24 @@ import {
81
79
  type WorldStateSynchronizer,
82
80
  tryStop,
83
81
  } from '@aztec/stdlib/interfaces/server';
84
- import type { LogFilter, PrivateLog, TxScopedL2Log } from '@aztec/stdlib/logs';
85
- import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
86
- import { P2PClientType } from '@aztec/stdlib/p2p';
87
- import type { Offense, SlashPayloadRound } from '@aztec/stdlib/slashing';
88
- 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';
89
87
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
90
88
  import {
91
- type BlockHeader,
89
+ type FeeProvider,
90
+ type GetTxReceiptOptions,
92
91
  type GlobalVariableBuilder as GlobalVariableBuilderInterface,
93
92
  type IndexedTxEffect,
94
93
  PublicSimulationOutput,
94
+ type SimulationOverrides,
95
95
  Tx,
96
96
  type TxHash,
97
- TxReceipt,
98
- TxStatus,
97
+ type TxReceipt,
99
98
  type TxValidationResult,
100
99
  } from '@aztec/stdlib/tx';
101
- import { getPackageVersion } from '@aztec/stdlib/update-checker';
102
100
  import type { SingleValidatorStats, ValidatorsStats } from '@aztec/stdlib/validators';
103
101
  import {
104
102
  Attributes,
@@ -108,62 +106,182 @@ import {
108
106
  getTelemetryClient,
109
107
  trackSpan,
110
108
  } from '@aztec/telemetry-client';
111
- import {
112
- NodeKeystoreAdapter,
113
- ValidatorClient,
114
- createBlockProposalHandler,
115
- createValidatorClient,
116
- } from '@aztec/validator-client';
117
- import { createWorldStateSynchronizer } from '@aztec/world-state';
118
-
119
- import { createPublicClient, fallback, http } from 'viem';
109
+ import { NodeKeystoreAdapter, ValidatorClient } from '@aztec/validator-client';
120
110
 
121
- import { createSentinel } from '../sentinel/factory.js';
111
+ import { NodeBlockProvider } from '../modules/node_block_provider.js';
112
+ import { NodeTxReceiptBuilder } from '../modules/node_tx_receipt.js';
113
+ import { NodeWorldStateQueries } from '../modules/node_world_state_queries.js';
122
114
  import { Sentinel } from '../sentinel/sentinel.js';
123
- import { type AztecNodeConfig, createKeyStoreForValidator } from './config.js';
115
+ import type { AztecNodeConfig } from './config.js';
124
116
  import { NodeMetrics } from './node_metrics.js';
117
+ import { NodePublicCallsSimulator } from './node_public_calls_simulator.js';
118
+
119
+ /**
120
+ * Fully-constructed collaborators and settings an {@link AztecNodeService} owns. Built by `createAztecNodeService`
121
+ * (see `factory.ts`); passed as a single object so call sites name each dependency instead of relying on
122
+ * positional order.
123
+ */
124
+ export interface AztecNodeServiceDeps {
125
+ config: AztecNodeConfig;
126
+ p2pClient: P2P;
127
+ blockSource: L2BlockSource & Partial<Service>;
128
+ logsSource: L2LogsSource;
129
+ contractDataSource: ContractDataSource;
130
+ l1ToL2MessageSource: L1ToL2MessageSource;
131
+ worldStateSynchronizer: WorldStateSynchronizer;
132
+ sequencer: SequencerClient | undefined;
133
+ proverNode: ProverNode | undefined;
134
+ slasherClient: SlasherClientInterface | undefined;
135
+ validatorsSentinel: Sentinel | undefined;
136
+ stopStartedWatchers: () => Promise<void>;
137
+ l1ChainId: number;
138
+ version: number;
139
+ globalVariableBuilder: GlobalVariableBuilderInterface;
140
+ rollupContract: RollupContract | undefined;
141
+ feeProvider: FeeProvider;
142
+ epochCache: EpochCacheInterface;
143
+ packageVersion: string;
144
+ peerProofVerifier: ClientProtocolCircuitVerifier;
145
+ rpcProofVerifier: ClientProtocolCircuitVerifier;
146
+ telemetry?: TelemetryClient;
147
+ log?: Logger;
148
+ blobClient?: BlobClientInterface;
149
+ validatorClient?: ValidatorClient;
150
+ keyStoreManager?: KeystoreManager;
151
+ debugLogStore?: DebugLogStore;
152
+ automineSequencer?: AutomineSequencer;
153
+ // AVM execution backend for public simulation. Wired in production (factory.ts); absent in unit/TXE nodes
154
+ // that don't drive public execution, hence optional and asserted at the simulation call site. Owned by the
155
+ // node (disposed on stop), so it must be disposable — a spawned process pool + CDB IPC server.
156
+ avmSimulator?: AvmSimulator & AsyncDisposable;
157
+ }
125
158
 
126
159
  /**
127
160
  * The aztec node.
128
161
  */
129
- export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
162
+ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDebug, Traceable {
130
163
  private metrics: NodeMetrics;
131
-
132
164
  // Prevent two snapshot operations to happen simultaneously
133
165
  private isUploadingSnapshot = false;
134
-
135
- // Serial queue to ensure that we only send one tx at a time
136
- private txQueue: SerialQueue = new SerialQueue();
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;
137
172
 
138
173
  public readonly tracer: Tracer;
139
174
 
140
- constructor(
141
- protected config: AztecNodeConfig,
142
- protected readonly p2pClient: P2P,
143
- protected readonly blockSource: L2BlockSource & Partial<Service>,
144
- protected readonly logsSource: L2LogsSource,
145
- protected readonly contractDataSource: ContractDataSource,
146
- protected readonly l1ToL2MessageSource: L1ToL2MessageSource,
147
- protected readonly worldStateSynchronizer: WorldStateSynchronizer,
148
- protected readonly sequencer: SequencerClient | undefined,
149
- protected readonly slasherClient: SlasherClientInterface | undefined,
150
- protected readonly validatorsSentinel: Sentinel | undefined,
151
- protected readonly epochPruneWatcher: EpochPruneWatcher | undefined,
152
- protected readonly l1ChainId: number,
153
- protected readonly version: number,
154
- protected readonly globalVariableBuilder: GlobalVariableBuilderInterface,
155
- protected readonly epochCache: EpochCacheInterface,
156
- protected readonly packageVersion: string,
157
- private proofVerifier: ClientProtocolCircuitVerifier,
158
- private telemetry: TelemetryClient = getTelemetryClient(),
159
- private log = createLogger('node'),
160
- ) {
161
- this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
162
- this.tracer = telemetry.getTracer('AztecNodeService');
163
- this.txQueue.start();
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
+ });
164
270
 
165
271
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
166
- 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;
167
285
  }
168
286
 
169
287
  public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
@@ -171,312 +289,82 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
171
289
  return status.syncSummary;
172
290
  }
173
291
 
174
- public getL2Tips() {
292
+ public getChainTips(): Promise<L2Tips> {
175
293
  return this.blockSource.getL2Tips();
176
294
  }
177
295
 
178
- /**
179
- * initializes the Aztec Node, wait for component to sync.
180
- * @param config - The configuration to be used by the aztec node.
181
- * @returns - A fully synced Aztec Node for use in development/testing.
182
- */
183
- public static async createAndSync(
184
- inputConfig: AztecNodeConfig,
185
- deps: {
186
- telemetry?: TelemetryClient;
187
- logger?: Logger;
188
- publisher?: SequencerPublisher;
189
- dateProvider?: DateProvider;
190
- blobSinkClient?: BlobSinkClientInterface;
191
- p2pClientDeps?: P2PClientDeps<P2PClientType.Full>;
192
- } = {},
193
- options: {
194
- prefilledPublicData?: PublicDataTreeLeaf[];
195
- dontStartSequencer?: boolean;
196
- } = {},
197
- ): Promise<AztecNodeService> {
198
- const config = { ...inputConfig }; // Copy the config so we dont mutate the input object
199
- const log = deps.logger ?? createLogger('node');
200
- const packageVersion = getPackageVersion() ?? '';
201
- const telemetry = deps.telemetry ?? getTelemetryClient();
202
- const dateProvider = deps.dateProvider ?? new DateProvider();
203
- const blobSinkClient =
204
- deps.blobSinkClient ?? createBlobSinkClient(config, { logger: createLogger('node:blob-sink:client') });
205
- const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
206
-
207
- // Build a key store from file if given or from environment otherwise
208
- let keyStoreManager: KeystoreManager | undefined;
209
- const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
210
- if (keyStoreProvided) {
211
- const keyStores = loadKeystores(config.keyStoreDirectory!);
212
- keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
213
- } else {
214
- const keyStore = createKeyStoreForValidator(config);
215
- if (keyStore) {
216
- keyStoreManager = new KeystoreManager(keyStore);
217
- }
218
- }
219
-
220
- await keyStoreManager?.validateSigners();
221
-
222
- // If we are a validator, verify our configuration before doing too much more.
223
- if (!config.disableValidator) {
224
- if (keyStoreManager === undefined) {
225
- throw new Error('Failed to create key store, a requirement for running a validator');
226
- }
227
- if (!keyStoreProvided) {
228
- log.warn(
229
- 'KEY STORE CREATED FROM ENVIRONMENT, IT IS RECOMMENDED TO USE A FILE-BASED KEY STORE IN PRODUCTION ENVIRONMENTS',
230
- );
231
- }
232
- ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
233
- }
234
-
235
- // validate that the actual chain id matches that specified in configuration
236
- if (config.l1ChainId !== ethereumChain.chainInfo.id) {
237
- throw new Error(
238
- `RPC URL configured for chain id ${ethereumChain.chainInfo.id} but expected id ${config.l1ChainId}`,
239
- );
240
- }
241
-
242
- const publicClient = createPublicClient({
243
- chain: ethereumChain.chainInfo,
244
- transport: fallback(config.l1RpcUrls.map((url: string) => http(url))),
245
- pollingInterval: config.viemPollingIntervalMS,
246
- });
247
-
248
- const l1ContractsAddresses = await RegistryContract.collectAddresses(
249
- publicClient,
250
- config.l1Contracts.registryAddress,
251
- config.rollupVersion ?? 'canonical',
252
- );
253
-
254
- // Overwrite the passed in vars.
255
- config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
256
-
257
- const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
258
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
259
- rollupContract.getL1GenesisTime(),
260
- rollupContract.getSlotDuration(),
261
- rollupContract.getVersion(),
262
- ] as const);
263
-
264
- config.rollupVersion ??= Number(rollupVersionFromRollup);
265
-
266
- if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
267
- log.warn(
268
- `Registry looked up and returned a rollup with version (${config.rollupVersion}), but this does not match with version detected from the rollup directly: (${rollupVersionFromRollup}).`,
269
- );
270
- }
271
-
272
- // attempt snapshot sync if possible
273
- await trySnapshotSync(config, log);
274
-
275
- const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, { dateProvider });
276
-
277
- const archiver = await createArchiver(
278
- config,
279
- { blobSinkClient, epochCache, telemetry, dateProvider },
280
- { blockUntilSync: !config.skipArchiverInitialSync },
281
- );
282
-
283
- // now create the merkle trees and the world state synchronizer
284
- const worldStateSynchronizer = await createWorldStateSynchronizer(
285
- config,
286
- archiver,
287
- options.prefilledPublicData,
288
- telemetry,
289
- );
290
- const circuitVerifier = config.realProofs ? await BBCircuitVerifier.new(config) : new TestCircuitVerifier();
291
- if (!config.realProofs) {
292
- log.warn(`Aztec node is accepting fake proofs`);
293
- }
294
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
295
-
296
- // create the tx pool and the p2p client, which will need the l2 block source
297
- const p2pClient = await createP2PClient(
298
- P2PClientType.Full,
299
- config,
300
- archiver,
301
- proofVerifier,
302
- worldStateSynchronizer,
303
- epochCache,
304
- packageVersion,
305
- dateProvider,
306
- telemetry,
307
- deps.p2pClientDeps,
308
- );
309
-
310
- // We should really not be modifying the config object
311
- config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
312
-
313
- const blockBuilder = new BlockBuilder(
314
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
315
- worldStateSynchronizer,
316
- archiver,
317
- dateProvider,
318
- telemetry,
319
- );
320
-
321
- // We'll accumulate sentinel watchers here
322
- const watchers: Watcher[] = [];
323
-
324
- // Create validator client if required
325
- const validatorClient = createValidatorClient(config, {
326
- p2pClient,
327
- telemetry,
328
- dateProvider,
329
- epochCache,
330
- blockBuilder,
331
- blockSource: archiver,
332
- l1ToL2MessageSource: archiver,
333
- keyStoreManager,
334
- });
335
-
336
- // If we have a validator client, register it as a source of offenses for the slasher,
337
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
338
- // like attestations or auths will fail.
339
- if (validatorClient) {
340
- watchers.push(validatorClient);
341
- if (!options.dontStartSequencer) {
342
- await validatorClient.registerHandlers();
343
- }
344
- }
296
+ public getL1Constants(): Promise<L1RollupConstants> {
297
+ return this.blockSource.getL1Constants();
298
+ }
345
299
 
346
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
347
- // create a BlockProposalHandler to reexecute block proposals for monitoring
348
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
349
- log.info('Setting up block proposal reexecution for monitoring');
350
- createBlockProposalHandler(config, {
351
- blockBuilder,
352
- epochCache,
353
- blockSource: archiver,
354
- l1ToL2MessageSource: archiver,
355
- p2pClient,
356
- dateProvider,
357
- telemetry,
358
- }).registerForReexecution(p2pClient);
359
- }
300
+ public getSyncedL2SlotNumber() {
301
+ return this.blockSource.getSyncedL2SlotNumber();
302
+ }
360
303
 
361
- // Start world state and wait for it to sync to the archiver.
362
- await worldStateSynchronizer.start();
304
+ public getSyncedL2EpochNumber() {
305
+ return this.blockSource.getSyncedL2EpochNumber();
306
+ }
363
307
 
364
- // Start p2p. Note that it depends on world state to be running.
365
- await p2pClient.start();
308
+ public getSyncedL1Timestamp() {
309
+ return this.blockSource.getL1Timestamp();
310
+ }
366
311
 
367
- const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
368
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
369
- watchers.push(validatorsSentinel);
370
- }
312
+ public getCheckpointsData(query: CheckpointsQuery) {
313
+ return this.blockSource.getCheckpointsData(query);
314
+ }
371
315
 
372
- let epochPruneWatcher: EpochPruneWatcher | undefined;
373
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
374
- epochPruneWatcher = new EpochPruneWatcher(
375
- archiver,
376
- archiver,
377
- epochCache,
378
- p2pClient.getTxProvider(),
379
- blockBuilder,
380
- config,
381
- );
382
- watchers.push(epochPruneWatcher);
316
+ public async getBlockNumber(tip?: L2BlockTag): Promise<BlockNumber> {
317
+ if (tip === undefined || tip === 'proposed') {
318
+ return this.blockSource.getBlockNumber();
383
319
  }
384
-
385
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
386
- let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
387
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
388
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
389
- 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;
390
333
  }
334
+ }
391
335
 
392
- // Start p2p-related services once the archiver has completed sync
393
- void archiver
394
- .waitForInitialSync()
395
- .then(async () => {
396
- await p2pClient.start();
397
- await validatorsSentinel?.start();
398
- await epochPruneWatcher?.start();
399
- await attestationsBlockWatcher?.start();
400
- log.info(`All p2p services started`);
401
- })
402
- .catch(err => log.error('Failed to start p2p services after archiver sync', err));
403
-
404
- // Validator enabled, create/start relevant service
405
- let sequencer: SequencerClient | undefined;
406
- let slasherClient: SlasherClientInterface | undefined;
407
- if (!config.disableValidator) {
408
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
409
- // as they are executed when the node is selected as proposer.
410
- const validatorAddresses = keyStoreManager
411
- ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses()
412
- : [];
413
-
414
- slasherClient = await createSlasher(
415
- config,
416
- config.l1Contracts,
417
- getPublicClient(config),
418
- watchers,
419
- dateProvider,
420
- epochCache,
421
- validatorAddresses,
422
- undefined, // logger
423
- );
424
- await slasherClient.start();
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
+ }
425
342
 
426
- const l1TxUtils = await createL1TxUtilsWithBlobsFromEthSigner(
427
- publicClient,
428
- keyStoreManager!.createAllValidatorPublisherSigners(),
429
- { ...config, scope: 'sequencer' },
430
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider },
431
- );
343
+ public getBlockData(param: BlockParameter): Promise<BlockData | undefined> {
344
+ return this.blockProvider.getBlockData(param);
345
+ }
432
346
 
433
- // Create and start the sequencer client
434
- sequencer = await SequencerClient.new(config, {
435
- ...deps,
436
- epochCache,
437
- l1TxUtils,
438
- validatorClient,
439
- p2pClient,
440
- worldStateSynchronizer,
441
- slasherClient,
442
- blockBuilder,
443
- l2BlockSource: archiver,
444
- l1ToL2MessageSource: archiver,
445
- telemetry,
446
- dateProvider,
447
- blobSinkClient,
448
- nodeKeyStore: keyStoreManager!,
449
- });
450
- }
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
+ }
451
354
 
452
- if (!options.dontStartSequencer && sequencer) {
453
- await sequencer.start();
454
- log.verbose(`Sequencer started`);
455
- } else if (sequencer) {
456
- log.warn(`Sequencer created but not started`);
457
- }
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
+ }
458
361
 
459
- return new AztecNodeService(
460
- config,
461
- p2pClient,
462
- archiver,
463
- archiver,
464
- archiver,
465
- archiver,
466
- worldStateSynchronizer,
467
- sequencer,
468
- slasherClient,
469
- validatorsSentinel,
470
- epochPruneWatcher,
471
- ethereumChain.chainInfo.id,
472
- config.rollupVersion,
473
- new GlobalVariableBuilder(config),
474
- epochCache,
475
- packageVersion,
476
- proofVerifier,
477
- telemetry,
478
- log,
479
- );
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);
480
368
  }
481
369
 
482
370
  /**
@@ -487,6 +375,16 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
487
375
  return this.sequencer;
488
376
  }
489
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
+
490
388
  public getBlockSource(): L2BlockSource {
491
389
  return this.blockSource;
492
390
  }
@@ -504,7 +402,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
504
402
  * @returns - The currently deployed L1 contract addresses.
505
403
  */
506
404
  public getL1ContractAddresses(): Promise<L1ContractAddresses> {
507
- return Promise.resolve(this.config.l1Contracts);
405
+ return Promise.resolve(pickL1ContractAddresses(this.config));
508
406
  }
509
407
 
510
408
  public getEncodedEnr(): Promise<string | undefined> {
@@ -512,7 +410,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
512
410
  }
513
411
 
514
412
  public async getAllowedPublicSetup(): Promise<AllowedElement[]> {
515
- return this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
413
+ return [...(await getDefaultAllowedSetupFunctions()), ...(this.config.txPublicSetupAllowListExtend ?? [])];
516
414
  }
517
415
 
518
416
  /**
@@ -524,14 +422,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
524
422
  }
525
423
 
526
424
  public async getNodeInfo(): Promise<NodeInfo> {
527
- const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses] = await Promise.all([
528
- this.getNodeVersion(),
529
- this.getVersion(),
530
- this.getChainId(),
531
- this.getEncodedEnr(),
532
- this.getL1ContractAddresses(),
533
- this.getProtocolContractAddresses(),
534
- ]);
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);
535
441
 
536
442
  const nodeInfo: NodeInfo = {
537
443
  nodeVersion,
@@ -540,73 +446,28 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
540
446
  enr,
541
447
  l1ContractAddresses: contractAddresses,
542
448
  protocolContractAddresses: protocolContractAddresses,
449
+ realProofs: !!this.config.realProofs,
450
+ txsLimits: { gas: { daGas: maxTxGas.daGas, l2Gas: maxTxGas.l2Gas } },
543
451
  };
544
452
 
545
453
  return nodeInfo;
546
454
  }
547
455
 
548
- /**
549
- * Get a block specified by its number.
550
- * @param number - The block number being requested.
551
- * @returns The requested block.
552
- */
553
- public async getBlock(number: L2BlockNumber): Promise<L2Block | undefined> {
554
- const blockNumber = number === 'latest' ? await this.getBlockNumber() : number;
555
- return await this.blockSource.getBlock(blockNumber);
456
+ public async getCurrentMinFees(): Promise<GasFees> {
457
+ return await this.feeProvider.getCurrentMinFees();
556
458
  }
557
459
 
558
- /**
559
- * Get a block specified by its hash.
560
- * @param blockHash - The block hash being requested.
561
- * @returns The requested block.
562
- */
563
- public async getBlockByHash(blockHash: Fr): Promise<L2Block | undefined> {
564
- const publishedBlock = await this.blockSource.getPublishedBlockByHash(blockHash);
565
- return publishedBlock?.block;
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);
566
463
  }
567
464
 
568
- /**
569
- * Get a block specified by its archive root.
570
- * @param archive - The archive root being requested.
571
- * @returns The requested block.
572
- */
573
- public async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
574
- const publishedBlock = await this.blockSource.getPublishedBlockByArchive(archive);
575
- return publishedBlock?.block;
576
- }
577
-
578
- /**
579
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
580
- * @param from - The start of the range of blocks to return.
581
- * @param limit - The maximum number of blocks to obtain.
582
- * @returns The blocks requested.
583
- */
584
- public async getBlocks(from: number, limit: number): Promise<L2Block[]> {
585
- return (await this.blockSource.getBlocks(from, limit)) ?? [];
586
- }
587
-
588
- public async getPublishedBlocks(from: number, limit: number): Promise<PublishedL2Block[]> {
589
- return (await this.blockSource.getPublishedBlocks(from, limit)) ?? [];
590
- }
591
-
592
- /**
593
- * Method to fetch the current base fees.
594
- * @returns The current base fees.
595
- */
596
- public async getCurrentBaseFees(): Promise<GasFees> {
597
- return await this.globalVariableBuilder.getCurrentBaseFees();
598
- }
599
-
600
- /**
601
- * Method to fetch the latest block number synchronized by the node.
602
- * @returns The block number.
603
- */
604
- public async getBlockNumber(): Promise<number> {
605
- return await this.blockSource.getBlockNumber();
606
- }
465
+ public async getMaxPriorityFees(): Promise<GasFees> {
466
+ for await (const tx of this.p2pClient.iteratePendingTxs({ includeProof: false })) {
467
+ return tx.getGasSettings().maxPriorityFeesPerGas;
468
+ }
607
469
 
608
- public async getProvenBlockNumber(): Promise<number> {
609
- return await this.blockSource.getProvenBlockNumber();
470
+ return GasFees.from({ feePerDaGas: 0n, feePerL2Gas: 0n });
610
471
  }
611
472
 
612
473
  /**
@@ -637,47 +498,25 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
637
498
  return this.contractDataSource.getContractClass(id);
638
499
  }
639
500
 
640
- public getContract(address: AztecAddress): Promise<ContractInstanceWithAddress | undefined> {
641
- return this.contractDataSource.getContract(address);
642
- }
643
-
644
- /**
645
- * Retrieves all private logs from up to `limit` blocks, starting from the block number `from`.
646
- * @param from - The block number from which to begin retrieving logs.
647
- * @param limit - The maximum number of blocks to retrieve logs from.
648
- * @returns An array of private logs from the specified range of blocks.
649
- */
650
- public getPrivateLogs(from: number, limit: number): Promise<PrivateLog[]> {
651
- return this.logsSource.getPrivateLogs(from, limit);
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
+ );
510
+ }
511
+ return this.contractDataSource.getContract(address, blockData.header.globalVariables.timestamp);
652
512
  }
653
513
 
654
- /**
655
- * Gets all logs that match any of the received tags (i.e. logs with their first field equal to a tag).
656
- * @param tags - The tags to filter the logs by.
657
- * @param logsPerTag - The maximum number of logs to return for each tag. By default no limit is set
658
- * @returns For each received tag, an array of matching logs is returned. An empty array implies no logs match
659
- * that tag.
660
- */
661
- public getLogsByTags(tags: Fr[], logsPerTag?: number): Promise<TxScopedL2Log[][]> {
662
- return this.logsSource.getLogsByTags(tags, logsPerTag);
514
+ public getPrivateLogsByTags(query: PrivateLogsQuery): Promise<LogResult[][]> {
515
+ return this.logsSource.getPrivateLogsByTags(query);
663
516
  }
664
517
 
665
- /**
666
- * Gets public logs based on the provided filter.
667
- * @param filter - The filter to apply to the logs.
668
- * @returns The requested logs.
669
- */
670
- getPublicLogs(filter: LogFilter): Promise<GetPublicLogsResponse> {
671
- return this.logsSource.getPublicLogs(filter);
672
- }
673
-
674
- /**
675
- * Gets contract class logs based on the provided filter.
676
- * @param filter - The filter to apply to the logs.
677
- * @returns The requested logs.
678
- */
679
- getContractClassLogs(filter: LogFilter): Promise<GetContractClassLogsResponse> {
680
- return this.logsSource.getContractClassLogs(filter);
518
+ public getPublicLogsByTags(query: PublicLogsQuery): Promise<LogResult[][]> {
519
+ return this.logsSource.getPublicLogsByTags(query);
681
520
  }
682
521
 
683
522
  /**
@@ -685,7 +524,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
685
524
  * @param tx - The transaction to be submitted.
686
525
  */
687
526
  public async sendTx(tx: Tx) {
688
- await this.txQueue.put(() => this.#sendTx(tx));
527
+ await this.#sendTx(tx);
689
528
  }
690
529
 
691
530
  async #sendTx(tx: Tx) {
@@ -700,27 +539,23 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
700
539
  throw new Error(`Invalid tx: ${reason}`);
701
540
  }
702
541
 
703
- await this.p2pClient!.sendTx(tx);
704
- this.metrics.receivedTx(timer.ms(), true);
705
- this.log.info(`Received tx ${txHash}`, { txHash });
706
- }
707
-
708
- public async getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
709
- let txReceipt = new TxReceipt(txHash, TxStatus.DROPPED, 'Tx dropped by P2P node.');
710
-
711
- // We first check if the tx is in pending (instead of first checking if it is mined) because if we first check
712
- // for mined and then for pending there could be a race condition where the tx is mined between the two checks
713
- // and we would incorrectly return a TxReceipt with status DROPPED
714
- if ((await this.p2pClient.getTxStatus(txHash)) === 'pending') {
715
- txReceipt = new TxReceipt(txHash, TxStatus.PENDING, '');
716
- }
717
-
718
- const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
719
- if (settledTxReceipt) {
720
- txReceipt = settledTxReceipt;
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;
721
548
  }
549
+ const duration = timer.ms();
550
+ this.metrics.receivedTx(duration, true);
551
+ this.log.info(`Received tx ${txHash} in ${duration}ms`, { txHash });
552
+ }
722
553
 
723
- return txReceipt;
554
+ public getTxReceipt<TGetTxReceiptOptions extends GetTxReceiptOptions = {}>(
555
+ txHash: TxHash,
556
+ options?: TGetTxReceiptOptions,
557
+ ): Promise<TxReceipt<TGetTxReceiptOptions>> {
558
+ return this.txReceiptBuilder.getTxReceipt(txHash, options);
724
559
  }
725
560
 
726
561
  public getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined> {
@@ -732,448 +567,178 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
732
567
  */
733
568
  public async stop() {
734
569
  this.log.info(`Stopping Aztec Node`);
735
- await this.txQueue.end();
736
- await tryStop(this.validatorsSentinel);
737
- await tryStop(this.epochPruneWatcher);
570
+ await this.stopStartedWatchers();
738
571
  await tryStop(this.slasherClient);
739
- await tryStop(this.proofVerifier);
572
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
740
573
  await tryStop(this.sequencer);
574
+ await tryStop(this.automineSequencer);
575
+ await tryStop(this.proverNode);
741
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]();
742
581
  await tryStop(this.worldStateSynchronizer);
743
582
  await tryStop(this.blockSource);
583
+ await tryStop(this.blobClient);
744
584
  await tryStop(this.telemetry);
745
585
  this.log.info(`Stopped Aztec Node`);
746
586
  }
747
587
 
588
+ /**
589
+ * Returns the blob client used by this node.
590
+ * @internal - Exposed for testing purposes only.
591
+ */
592
+ public getBlobClient(): BlobClientInterface | undefined {
593
+ return this.blobClient;
594
+ }
595
+
748
596
  /**
749
597
  * Method to retrieve pending txs.
750
598
  * @param limit - The number of items to returns
751
599
  * @param after - The last known pending tx. Used for pagination
752
600
  * @returns - The pending txs.
753
601
  */
754
- public getPendingTxs(limit?: number, after?: TxHash): Promise<Tx[]> {
755
- 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);
756
604
  }
757
605
 
758
606
  public getPendingTxCount(): Promise<number> {
759
607
  return this.p2pClient!.getPendingTxCount();
760
608
  }
761
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
+
762
625
  /**
763
- * 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.
764
628
  * @param txHash - The transaction hash to return.
629
+ * @param options - Options for the returned tx (eg whether to include its proof).
765
630
  * @returns - The tx if it exists.
766
631
  */
767
- public getTxByHash(txHash: TxHash): Promise<Tx | undefined> {
768
- 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 });
769
634
  }
770
635
 
771
636
  /**
772
- * 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.
773
639
  * @param txHash - The transaction hash to return.
640
+ * @param options - Options for the returned txs (eg whether to include their proofs).
774
641
  * @returns - The txs if it exists.
775
642
  */
776
- public async getTxsByHash(txHashes: TxHash[]): Promise<Tx[]> {
777
- 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);
778
646
  }
779
647
 
780
- /**
781
- * Find the indexes of the given leaves in the given tree along with a block metadata pointing to the block in which
782
- * the leaves were inserted.
783
- * @param blockNumber - The block number at which to get the data or 'latest' for latest data.
784
- * @param treeId - The tree to search in.
785
- * @param leafValues - The values to search for.
786
- * @returns The indices of leaves and the block metadata of a block in which the leaves were inserted.
787
- */
788
- public async findLeavesIndexes(
789
- blockNumber: L2BlockNumber,
648
+ public findLeavesIndexes(
649
+ referenceBlock: BlockParameter,
790
650
  treeId: MerkleTreeId,
791
651
  leafValues: Fr[],
792
- ): Promise<(InBlock<bigint> | undefined)[]> {
793
- const committedDb = await this.#getWorldState(blockNumber);
794
- const maybeIndices = await committedDb.findLeafIndices(
795
- treeId,
796
- leafValues.map(x => x.toBuffer()),
797
- );
798
- // We filter out undefined values
799
- const indices = maybeIndices.filter(x => x !== undefined) as bigint[];
800
-
801
- // Now we find the block numbers for the indices
802
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
803
-
804
- // If any of the block numbers are undefined, we throw an error.
805
- for (let i = 0; i < indices.length; i++) {
806
- if (blockNumbers[i] === undefined) {
807
- throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
808
- }
809
- }
810
-
811
- // Get unique block numbers in order to optimize num calls to getLeafValue function.
812
- const uniqueBlockNumbers = [...new Set(blockNumbers.filter(x => x !== undefined))];
813
-
814
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
815
- // (note that block number corresponds to the leaf index in the archive tree).
816
- const blockHashes = await Promise.all(
817
- uniqueBlockNumbers.map(blockNumber => {
818
- return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, blockNumber!);
819
- }),
820
- );
821
-
822
- // If any of the block hashes are undefined, we throw an error.
823
- for (let i = 0; i < uniqueBlockNumbers.length; i++) {
824
- if (blockHashes[i] === undefined) {
825
- throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
826
- }
827
- }
828
-
829
- // Create InBlock objects by combining indices, blockNumbers and blockHashes and return them.
830
- return maybeIndices.map((index, i) => {
831
- if (index === undefined) {
832
- return undefined;
833
- }
834
- const blockNumber = blockNumbers[i];
835
- if (blockNumber === undefined) {
836
- return undefined;
837
- }
838
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
839
- const blockHash = blockHashes[blockHashIndex];
840
- if (!blockHash) {
841
- return undefined;
842
- }
843
- return {
844
- l2BlockNumber: Number(blockNumber),
845
- l2BlockHash: L2BlockHash.fromField(blockHash),
846
- data: index,
847
- };
848
- });
849
- }
850
-
851
- /**
852
- * Returns a sibling path for the given index in the nullifier tree.
853
- * @param blockNumber - The block number at which to get the data.
854
- * @param leafIndex - The index of the leaf for which the sibling path is required.
855
- * @returns The sibling path for the leaf index.
856
- */
857
- public async getNullifierSiblingPath(
858
- blockNumber: L2BlockNumber,
859
- leafIndex: bigint,
860
- ): Promise<SiblingPath<typeof NULLIFIER_TREE_HEIGHT>> {
861
- const committedDb = await this.#getWorldState(blockNumber);
862
- return committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, leafIndex);
863
- }
864
-
865
- /**
866
- * Returns a sibling path for the given index in the data tree.
867
- * @param blockNumber - The block number at which to get the data.
868
- * @param leafIndex - The index of the leaf for which the sibling path is required.
869
- * @returns The sibling path for the leaf index.
870
- */
871
- public async getNoteHashSiblingPath(
872
- blockNumber: L2BlockNumber,
873
- leafIndex: bigint,
874
- ): Promise<SiblingPath<typeof NOTE_HASH_TREE_HEIGHT>> {
875
- const committedDb = await this.#getWorldState(blockNumber);
876
- return committedDb.getSiblingPath(MerkleTreeId.NOTE_HASH_TREE, leafIndex);
652
+ ): Promise<(DataInBlock<bigint> | undefined)[]> {
653
+ return this.worldStateQueries.findLeavesIndexes(referenceBlock, treeId, leafValues);
877
654
  }
878
655
 
879
- public async getArchiveMembershipWitness(
880
- blockNumber: L2BlockNumber,
881
- archive: Fr,
656
+ public getBlockHashMembershipWitness(
657
+ referenceBlock: BlockParameter,
658
+ blockHash: BlockHash,
882
659
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
883
- const committedDb = await this.#getWorldState(blockNumber);
884
- const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [archive]);
885
- return pathAndIndex === undefined
886
- ? undefined
887
- : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
660
+ return this.worldStateQueries.getBlockHashMembershipWitness(referenceBlock, blockHash);
888
661
  }
889
662
 
890
- public async getNoteHashMembershipWitness(
891
- blockNumber: L2BlockNumber,
663
+ public getNoteHashMembershipWitness(
664
+ referenceBlock: BlockParameter,
892
665
  noteHash: Fr,
893
666
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
894
- const committedDb = await this.#getWorldState(blockNumber);
895
- const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
896
- MerkleTreeId.NOTE_HASH_TREE,
897
- [noteHash],
898
- );
899
- return pathAndIndex === undefined
900
- ? undefined
901
- : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
667
+ return this.worldStateQueries.getNoteHashMembershipWitness(referenceBlock, noteHash);
902
668
  }
903
669
 
904
- /**
905
- * Returns the index and a sibling path for a leaf in the committed l1 to l2 data tree.
906
- * @param blockNumber - The block number at which to get the data.
907
- * @param l1ToL2Message - The l1ToL2Message to get the index / sibling path for.
908
- * @returns A tuple of the index and the sibling path of the L1ToL2Message (undefined if not found).
909
- */
910
- public async getL1ToL2MessageMembershipWitness(
911
- blockNumber: L2BlockNumber,
670
+ public getL1ToL2MessageMembershipWitness(
671
+ referenceBlock: BlockParameter,
912
672
  l1ToL2Message: Fr,
913
673
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
914
- const db = await this.#getWorldState(blockNumber);
915
- const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
916
- if (!witness) {
917
- return undefined;
918
- }
919
-
920
- // REFACTOR: Return a MembershipWitness object
921
- return [witness.index, witness.path];
674
+ return this.worldStateQueries.getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message);
922
675
  }
923
676
 
924
- public async getL1ToL2MessageBlock(l1ToL2Message: Fr): Promise<number | undefined> {
925
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
926
- return messageIndex ? InboxLeaf.l2BlockFromIndex(messageIndex) : undefined;
677
+ public getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
678
+ return this.worldStateQueries.getL1ToL2MessageCheckpoint(l1ToL2Message);
927
679
  }
928
680
 
929
681
  /**
930
- * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
931
- * @param l1ToL2Message - The L1 to L2 message to check.
932
- * @returns Whether the message is synced and ready to be included in a block.
933
- */
934
- public async isL1ToL2MessageSynced(l1ToL2Message: Fr): Promise<boolean> {
935
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
936
- return messageIndex !== undefined;
937
- }
938
-
939
- /**
940
- * Returns all the L2 to L1 messages in a block.
941
- * @param blockNumber - The block number at which to get the data.
942
- * @returns The L2 to L1 messages (undefined if the block number is not found).
943
- */
944
- public async getL2ToL1Messages(blockNumber: L2BlockNumber): Promise<Fr[][] | undefined> {
945
- const block = await this.blockSource.getBlock(blockNumber === 'latest' ? await this.getBlockNumber() : blockNumber);
946
- return block?.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs);
947
- }
948
-
949
- /**
950
- * Returns a sibling path for a leaf in the committed blocks tree.
951
- * @param blockNumber - The block number at which to get the data.
952
- * @param leafIndex - Index of the leaf in the tree.
953
- * @returns The sibling path.
682
+ * Returns all the L2 to L1 messages in an epoch.
683
+ *
684
+ * @deprecated Use {@link getL2ToL1MembershipWitness} to get an L2-to-L1 message witness directly.
685
+ *
686
+ * @param epoch - The epoch at which to get the data.
687
+ * @returns The L2 to L1 messages (empty array if the epoch is not found).
954
688
  */
955
- public async getArchiveSiblingPath(
956
- blockNumber: L2BlockNumber,
957
- leafIndex: bigint,
958
- ): Promise<SiblingPath<typeof ARCHIVE_HEIGHT>> {
959
- const committedDb = await this.#getWorldState(blockNumber);
960
- return committedDb.getSiblingPath(MerkleTreeId.ARCHIVE, leafIndex);
689
+ public getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
690
+ return this.worldStateQueries.getL2ToL1Messages(epoch);
961
691
  }
962
692
 
963
693
  /**
964
- * Returns a sibling path for a leaf in the committed public data tree.
965
- * @param blockNumber - The block number at which to get the data.
966
- * @param leafIndex - Index of the leaf in the tree.
967
- * @returns The sibling path.
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}.
968
696
  */
969
- public async getPublicDataSiblingPath(
970
- blockNumber: L2BlockNumber,
971
- leafIndex: bigint,
972
- ): Promise<SiblingPath<typeof PUBLIC_DATA_TREE_HEIGHT>> {
973
- const committedDb = await this.#getWorldState(blockNumber);
974
- return committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, leafIndex);
697
+ public getL2ToL1MembershipWitness(
698
+ txHash: TxHash,
699
+ message: Fr,
700
+ messageIndexInTx?: number,
701
+ ): Promise<L2ToL1MembershipWitness | undefined> {
702
+ return this.worldStateQueries.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
975
703
  }
976
704
 
977
- /**
978
- * Returns a nullifier membership witness for a given nullifier at a given block.
979
- * @param blockNumber - The block number at which to get the index.
980
- * @param nullifier - Nullifier we try to find witness for.
981
- * @returns The nullifier membership witness (if found).
982
- */
983
- public async getNullifierMembershipWitness(
984
- blockNumber: L2BlockNumber,
705
+ public getNullifierMembershipWitness(
706
+ referenceBlock: BlockParameter,
985
707
  nullifier: Fr,
986
708
  ): Promise<NullifierMembershipWitness | undefined> {
987
- const db = await this.#getWorldState(blockNumber);
988
- const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
989
- if (!witness) {
990
- return undefined;
991
- }
992
-
993
- const { index, path } = witness;
994
- const leafPreimage = await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
995
- if (!leafPreimage) {
996
- return undefined;
997
- }
998
-
999
- return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
709
+ return this.worldStateQueries.getNullifierMembershipWitness(referenceBlock, nullifier);
1000
710
  }
1001
711
 
1002
- /**
1003
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1004
- * @param blockNumber - The block number at which to get the index.
1005
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1006
- * @returns The low nullifier membership witness (if found).
1007
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1008
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1009
- * we are trying to prove non-inclusion for.
1010
- *
1011
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1012
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1013
- * index of the nullifier itself when it already exists in the tree.
1014
- * TODO: This is a confusing behavior and we should eventually address that.
1015
- */
1016
- public async getLowNullifierMembershipWitness(
1017
- blockNumber: L2BlockNumber,
712
+ public getLowNullifierMembershipWitness(
713
+ referenceBlock: BlockParameter,
1018
714
  nullifier: Fr,
1019
715
  ): Promise<NullifierMembershipWitness | undefined> {
1020
- const committedDb = await this.#getWorldState(blockNumber);
1021
- const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1022
- if (!findResult) {
1023
- return undefined;
1024
- }
1025
- const { index, alreadyPresent } = findResult;
1026
- if (alreadyPresent) {
1027
- this.log.warn(`Nullifier ${nullifier.toBigInt()} already exists in the tree`);
1028
- }
1029
- const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
1030
-
1031
- const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1032
- return new NullifierMembershipWitness(BigInt(index), preimageData as NullifierLeafPreimage, siblingPath);
716
+ return this.worldStateQueries.getLowNullifierMembershipWitness(referenceBlock, nullifier);
1033
717
  }
1034
718
 
1035
- async getPublicDataWitness(blockNumber: L2BlockNumber, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1036
- const committedDb = await this.#getWorldState(blockNumber);
1037
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1038
- if (!lowLeafResult) {
1039
- return undefined;
1040
- } else {
1041
- const preimage = (await committedDb.getLeafPreimage(
1042
- MerkleTreeId.PUBLIC_DATA_TREE,
1043
- lowLeafResult.index,
1044
- )) as PublicDataTreeLeafPreimage;
1045
- const path = await committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1046
- return new PublicDataWitness(lowLeafResult.index, preimage, path);
1047
- }
719
+ public getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
720
+ return this.worldStateQueries.getPublicDataWitness(referenceBlock, leafSlot);
1048
721
  }
1049
722
 
1050
- /**
1051
- * Gets the storage value at the given contract storage slot.
1052
- *
1053
- * @remarks The storage slot here refers to the slot as it is defined in Noir not the index in the merkle tree.
1054
- * Aztec's version of `eth_getStorageAt`.
1055
- *
1056
- * @param contract - Address of the contract to query.
1057
- * @param slot - Slot to query.
1058
- * @param blockNumber - The block number at which to get the data or 'latest'.
1059
- * @returns Storage value at the given contract slot.
1060
- */
1061
- public async getPublicStorageAt(blockNumber: L2BlockNumber, contract: AztecAddress, slot: Fr): Promise<Fr> {
1062
- const committedDb = await this.#getWorldState(blockNumber);
1063
- const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1064
-
1065
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1066
- if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
1067
- return Fr.ZERO;
1068
- }
1069
- const preimage = (await committedDb.getLeafPreimage(
1070
- MerkleTreeId.PUBLIC_DATA_TREE,
1071
- lowLeafResult.index,
1072
- )) as PublicDataTreeLeafPreimage;
1073
- return preimage.leaf.value;
1074
- }
1075
-
1076
- /**
1077
- * Returns the currently committed block header, or the initial header if no blocks have been produced.
1078
- * @returns The current committed block header.
1079
- */
1080
- public async getBlockHeader(blockNumber: L2BlockNumber = 'latest'): Promise<BlockHeader | undefined> {
1081
- return blockNumber === 0 || (blockNumber === 'latest' && (await this.blockSource.getBlockNumber()) === 0)
1082
- ? this.worldStateSynchronizer.getCommitted().getInitialHeader()
1083
- : this.blockSource.getBlockHeader(blockNumber);
1084
- }
1085
-
1086
- /**
1087
- * Get a block header specified by its hash.
1088
- * @param blockHash - The block hash being requested.
1089
- * @returns The requested block header.
1090
- */
1091
- public async getBlockHeaderByHash(blockHash: Fr): Promise<BlockHeader | undefined> {
1092
- return await this.blockSource.getBlockHeaderByHash(blockHash);
1093
- }
1094
-
1095
- /**
1096
- * Get a block header specified by its archive root.
1097
- * @param archive - The archive root being requested.
1098
- * @returns The requested block header.
1099
- */
1100
- public async getBlockHeaderByArchive(archive: Fr): Promise<BlockHeader | undefined> {
1101
- 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);
1102
725
  }
1103
726
 
1104
727
  /**
1105
728
  * Simulates the public part of a transaction with the current state.
1106
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.
1107
732
  **/
1108
733
  @trackSpan('AztecNodeService.simulatePublicCalls', (tx: Tx) => ({
1109
734
  [Attributes.TX_HASH]: tx.getTxHash().toString(),
1110
735
  }))
1111
- public async simulatePublicCalls(tx: Tx, skipFeeEnforcement = false): Promise<PublicSimulationOutput> {
1112
- // Check total gas limit for simulation
1113
- const gasSettings = tx.data.constants.txContext.gasSettings;
1114
- const txGasLimit = gasSettings.gasLimits.l2Gas;
1115
- const teardownGasLimit = gasSettings.teardownGasLimits.l2Gas;
1116
- if (txGasLimit + teardownGasLimit > this.config.rpcSimulatePublicMaxGasLimit) {
1117
- throw new BadRequestError(
1118
- `Transaction total gas limit ${
1119
- txGasLimit + teardownGasLimit
1120
- } (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${
1121
- this.config.rpcSimulatePublicMaxGasLimit
1122
- } for simulation`,
1123
- );
1124
- }
1125
-
1126
- const txHash = tx.getTxHash();
1127
- const blockNumber = (await this.blockSource.getBlockNumber()) + 1;
1128
-
1129
- // If sequencer is not initialized, we just set these values to zero for simulation.
1130
- const coinbase = EthAddress.ZERO;
1131
- const feeRecipient = AztecAddress.ZERO;
1132
-
1133
- const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(
1134
- blockNumber,
1135
- coinbase,
1136
- feeRecipient,
1137
- );
1138
- const publicProcessorFactory = new PublicProcessorFactory(
1139
- this.contractDataSource,
1140
- new DateProvider(),
1141
- this.telemetry,
1142
- );
1143
-
1144
- this.log.verbose(`Simulating public calls for tx ${txHash}`, {
1145
- globalVariables: newGlobalVariables.toInspect(),
1146
- txHash,
1147
- blockNumber,
1148
- });
1149
-
1150
- const merkleTreeFork = await this.worldStateSynchronizer.fork();
1151
- try {
1152
- const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, {
1153
- skipFeeEnforcement,
1154
- clientInitiatedSimulation: true,
1155
- maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads,
1156
- });
1157
-
1158
- // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1159
- const [processedTxs, failedTxs, _usedTxs, returns] = await processor.process([tx]);
1160
- // REFACTOR: Consider returning the error rather than throwing
1161
- if (failedTxs.length) {
1162
- this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
1163
- throw failedTxs[0].error;
1164
- }
1165
-
1166
- const [processedTx] = processedTxs;
1167
- return new PublicSimulationOutput(
1168
- processedTx.revertReason,
1169
- processedTx.globalVariables,
1170
- processedTx.txEffect,
1171
- returns,
1172
- processedTx.gasUsed,
1173
- );
1174
- } finally {
1175
- await merkleTreeFork.close();
1176
- }
736
+ public simulatePublicCalls(
737
+ tx: Tx,
738
+ skipFeeEnforcement = false,
739
+ overrides?: SimulationOverrides,
740
+ ): Promise<PublicSimulationOutput> {
741
+ return this.nodePublicCallsSimulator.simulate(tx, skipFeeEnforcement, overrides);
1177
742
  }
1178
743
 
1179
744
  public async isValidTx(
@@ -1181,21 +746,37 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1181
746
  { isSimulation, skipFeeEnforcement }: { isSimulation?: boolean; skipFeeEnforcement?: boolean } = {},
1182
747
  ): Promise<TxValidationResult> {
1183
748
  const db = this.worldStateSynchronizer.getCommitted();
1184
- const verifier = isSimulation ? undefined : this.proofVerifier;
749
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1185
750
 
1186
- // 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)
1187
752
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1188
- const blockNumber = (await this.blockSource.getBlockNumber()) + 1;
1189
- const validator = createValidatorForAcceptingTxs(db, this.contractDataSource, verifier, {
1190
- timestamp: nextSlotTimestamp,
1191
- blockNumber,
1192
- l1ChainId: this.l1ChainId,
1193
- rollupVersion: this.version,
1194
- setupAllowList: this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions()),
1195
- gasFees: await this.getCurrentBaseFees(),
1196
- skipFeeEnforcement,
1197
- txsPermitted: !this.config.disableTransactions,
1198
- });
753
+ const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
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(
759
+ db,
760
+ this.contractDataSource,
761
+ verifier,
762
+ {
763
+ timestamp: nextSlotTimestamp,
764
+ blockNumber,
765
+ l1ChainId: this.l1ChainId,
766
+ rollupVersion: this.version,
767
+ setupAllowList: [
768
+ ...(await getDefaultAllowedSetupFunctions()),
769
+ ...(this.config.txPublicSetupAllowListExtend ?? []),
770
+ ],
771
+ gasFees: await this.getCurrentMinFees(),
772
+ skipFeeEnforcement,
773
+ isSimulation,
774
+ txsPermitted: !this.config.disableTransactions,
775
+ maxTxL2Gas: networkTxGasLimits.l2Gas,
776
+ maxTxDAGas: networkTxGasLimits.daGas,
777
+ },
778
+ this.log.getBindings(),
779
+ );
1199
780
 
1200
781
  return await validator.validateTx(tx);
1201
782
  }
@@ -1208,7 +789,18 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1208
789
 
1209
790
  public async setConfig(config: Partial<AztecNodeAdminConfig>): Promise<void> {
1210
791
  const newConfig = { ...this.config, ...config };
1211
- 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);
1212
804
  this.slasherClient?.updateConfig(config);
1213
805
  this.validatorsSentinel?.updateConfig(config);
1214
806
  await this.p2pClient.updateP2PConfig(config);
@@ -1217,7 +809,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1217
809
  archiver.updateConfig(config);
1218
810
  }
1219
811
  if (newConfig.realProofs !== this.config.realProofs) {
1220
- 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
+ }
1221
821
  }
1222
822
 
1223
823
  this.config = newConfig;
@@ -1228,7 +828,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1228
828
  classRegistry: ProtocolContractAddress.ContractClassRegistry,
1229
829
  feeJuice: ProtocolContractAddress.FeeJuice,
1230
830
  instanceRegistry: ProtocolContractAddress.ContractInstanceRegistry,
1231
- multiCallEntrypoint: ProtocolContractAddress.MultiCallEntrypoint,
831
+ multiCallEntrypoint: STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS,
1232
832
  });
1233
833
  }
1234
834
 
@@ -1242,8 +842,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1242
842
 
1243
843
  public getValidatorStats(
1244
844
  validatorAddress: EthAddress,
1245
- fromSlot?: bigint,
1246
- toSlot?: bigint,
845
+ fromSlot?: SlotNumber,
846
+ toSlot?: SlotNumber,
1247
847
  ): Promise<SingleValidatorStats | undefined> {
1248
848
  return this.validatorsSentinel?.getValidatorStats(validatorAddress, fromSlot, toSlot) ?? Promise.resolve(undefined);
1249
849
  }
@@ -1264,7 +864,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1264
864
  }
1265
865
 
1266
866
  // And it has an L2 block hash
1267
- const l2BlockHash = await archiver.getL2Tips().then(tips => tips.latest.hash);
867
+ const l2BlockHash = await archiver.getL2Tips().then(tips => tips.proposed.hash);
1268
868
  if (!l2BlockHash) {
1269
869
  this.metrics.recordSnapshotError();
1270
870
  throw new Error(`Archiver has no latest L2 block hash downloaded. Cannot start snapshot.`);
@@ -1292,13 +892,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1292
892
  return Promise.resolve();
1293
893
  }
1294
894
 
1295
- public async rollbackTo(targetBlock: number, force?: boolean): Promise<void> {
895
+ public async rollbackTo(targetBlock: BlockNumber, force?: boolean, resumeSync = true): Promise<void> {
1296
896
  const archiver = this.blockSource as Archiver;
1297
897
  if (!('rollbackTo' in archiver)) {
1298
898
  throw new Error('Archiver implementation does not support rollbacks.');
1299
899
  }
1300
900
 
1301
- const finalizedBlock = await archiver.getL2Tips().then(tips => tips.finalized.number);
901
+ const finalizedBlock = await archiver.getL2Tips().then(tips => tips.finalized.block.number);
1302
902
  if (targetBlock < finalizedBlock) {
1303
903
  if (force) {
1304
904
  this.log.warn(`Clearing world state database to allow rolling back behind finalized block ${finalizedBlock}`);
@@ -1322,9 +922,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1322
922
  this.log.error(`Error during rollback`, err);
1323
923
  throw err;
1324
924
  } finally {
1325
- this.log.info(`Resuming world state and archiver sync.`);
1326
- this.worldStateSynchronizer.resumeSync();
1327
- 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
+ }
1328
932
  }
1329
933
  }
1330
934
 
@@ -1341,11 +945,39 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1341
945
  return Promise.resolve();
1342
946
  }
1343
947
 
1344
- public getSlashPayloads(): Promise<SlashPayloadRound[]> {
1345
- if (!this.slasherClient) {
1346
- 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();
1347
962
  }
1348
- 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');
1349
981
  }
1350
982
 
1351
983
  public getSlashOffenses(round: bigint | 'all' | 'current'): Promise<Offense[]> {
@@ -1353,48 +985,165 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1353
985
  throw new Error(`Slasher client not enabled`);
1354
986
  }
1355
987
  if (round === 'all') {
1356
- return this.slasherClient.getPendingOffenses();
988
+ return this.slasherClient.getOffenses();
1357
989
  } else {
1358
990
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1359
991
  }
1360
992
  }
1361
993
 
1362
- /**
1363
- * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1364
- * @param blockNumber - The block number at which to get the data.
1365
- * @returns An instance of a committed MerkleTreeOperations
1366
- */
1367
- async #getWorldState(blockNumber: L2BlockNumber) {
1368
- if (typeof blockNumber === 'number' && blockNumber < INITIAL_L2_BLOCK_NUM - 1) {
1369
- throw new Error('Invalid block number to get world state for: ' + blockNumber);
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.');
1003
+ }
1004
+
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
+ }
1370
1037
  }
1371
1038
 
1372
- let blockSyncedTo: number = 0;
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');
1059
+ }
1060
+
1061
+ // Update the validator client (coinbase, feeRecipient, attester keys)
1062
+ this.validatorClient.reloadKeystore(newManager);
1063
+
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);
1068
+ }
1069
+
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
+ }
1077
+
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
+
1373
1101
  try {
1374
- // Attempt to sync the world state if necessary
1375
- blockSyncedTo = await this.#syncWorldState();
1376
- } catch (err) {
1377
- this.log.error(`Error getting world state: ${err}`);
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 });
1378
1117
  }
1118
+ }
1379
1119
 
1380
- // using a snapshot could be less efficient than using the committed db
1381
- if (blockNumber === 'latest' /*|| blockNumber === blockSyncedTo*/) {
1382
- this.log.debug(`Using committed db for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1383
- return this.worldStateSynchronizer.getCommitted();
1384
- } else if (blockNumber <= blockSyncedTo) {
1385
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1386
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1387
- } else {
1388
- throw new Error(`Block ${blockNumber} not yet synced`);
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
+ }
1133
+
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');
1389
1137
  }
1138
+ await this.automineSequencer.warpBy(duration);
1390
1139
  }
1391
1140
 
1392
1141
  /**
1393
- * Ensure we fully sync the world state
1394
- * @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.
1395
1145
  */
1396
- async #syncWorldState(): Promise<number> {
1397
- const blockSourceHeight = await this.blockSource.getBlockNumber();
1398
- return this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
1146
+ protected getWorldState(block: BlockParameter) {
1147
+ return this.worldStateQueries.getWorldState(block);
1399
1148
  }
1400
1149
  }