@aztec/aztec-node 0.0.1-commit.fce3e4f → 0.0.1-commit.ffe5b04ea

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.
@@ -1,43 +1,36 @@
1
1
  import { Archiver, createArchiver } from '@aztec/archiver';
2
2
  import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
3
- import { type BlobSinkClientInterface, createBlobSinkClient } from '@aztec/blob-sink/client';
4
- 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';
3
+ import { type BlobClientInterface, createBlobClientWithFileStores } from '@aztec/blob-client/client';
4
+ import { Blob } from '@aztec/blob-lib';
5
+ import { ARCHIVE_HEIGHT, type L1_TO_L2_MSG_TREE_HEIGHT, type NOTE_HASH_TREE_HEIGHT } from '@aztec/constants';
12
6
  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 { SlotNumber } from '@aztec/foundation/branded-types';
21
- import { compactArray, pick } from '@aztec/foundation/collection';
7
+ import { createEthereumChain } from '@aztec/ethereum/chain';
8
+ import { getPublicClient } from '@aztec/ethereum/client';
9
+ import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
10
+ import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
11
+ import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
12
+ import { compactArray, pick, unique } from '@aztec/foundation/collection';
13
+ import { Fr } from '@aztec/foundation/curves/bn254';
22
14
  import { EthAddress } from '@aztec/foundation/eth-address';
23
- import { Fr } from '@aztec/foundation/fields';
24
15
  import { BadRequestError } from '@aztec/foundation/json-rpc';
25
16
  import { type Logger, createLogger } from '@aztec/foundation/log';
26
17
  import { count } from '@aztec/foundation/string';
27
18
  import { DateProvider, Timer } from '@aztec/foundation/timer';
28
19
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
29
- import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
20
+ import { type KeyStore, KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
30
21
  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';
33
- import { ProtocolContractAddress } from '@aztec/protocol-contracts';
22
+ import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
34
23
  import {
35
- BlockBuilder,
36
- GlobalVariableBuilder,
37
- SequencerClient,
38
- type SequencerPublisher,
39
- createValidatorForAcceptingTxs,
40
- } from '@aztec/sequencer-client';
24
+ type P2P,
25
+ type P2PClientDeps,
26
+ createP2PClient,
27
+ createTxValidatorForAcceptingTxsOverRPC,
28
+ getDefaultAllowedSetupFunctions,
29
+ } from '@aztec/p2p';
30
+ import { ProtocolContractAddress } from '@aztec/protocol-contracts';
31
+ import { type ProverNode, type ProverNodeDeps, createProverNode } from '@aztec/prover-node';
32
+ import { createKeyStoreForProver } from '@aztec/prover-node/config';
33
+ import { GlobalVariableBuilder, SequencerClient, type SequencerPublisher } from '@aztec/sequencer-client';
41
34
  import { PublicProcessorFactory } from '@aztec/simulator/server';
42
35
  import {
43
36
  AttestationsBlockWatcher,
@@ -46,16 +39,17 @@ import {
46
39
  type Watcher,
47
40
  createSlasher,
48
41
  } from '@aztec/slasher';
49
- import { PublicSimulatorConfig } from '@aztec/stdlib/avm';
42
+ import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
50
43
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
51
44
  import {
52
- type InBlock,
53
- type L2Block,
54
- L2BlockHash,
55
- type L2BlockNumber,
45
+ type BlockData,
46
+ BlockHash,
47
+ type BlockParameter,
48
+ type DataInBlock,
49
+ L2Block,
56
50
  type L2BlockSource,
57
- type PublishedL2Block,
58
51
  } from '@aztec/stdlib/block';
52
+ import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
59
53
  import type {
60
54
  ContractClassPublic,
61
55
  ContractDataSource,
@@ -63,7 +57,7 @@ import type {
63
57
  NodeInfo,
64
58
  ProtocolContractAddresses,
65
59
  } from '@aztec/stdlib/contract';
66
- import type { GasFees } from '@aztec/stdlib/gas';
60
+ import { GasFees } from '@aztec/stdlib/gas';
67
61
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
68
62
  import {
69
63
  type AztecNode,
@@ -82,9 +76,9 @@ import {
82
76
  type WorldStateSynchronizer,
83
77
  tryStop,
84
78
  } from '@aztec/stdlib/interfaces/server';
85
- import type { LogFilter, PrivateLog, TxScopedL2Log } from '@aztec/stdlib/logs';
79
+ import type { DebugLogStore, LogFilter, SiloedTag, Tag, TxScopedL2Log } from '@aztec/stdlib/logs';
80
+ import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
86
81
  import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
87
- import { P2PClientType } from '@aztec/stdlib/p2p';
88
82
  import type { Offense, SlashPayloadRound } from '@aztec/stdlib/slashing';
89
83
  import type { NullifierLeafPreimage, PublicDataTreeLeaf, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
90
84
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
@@ -110,6 +104,8 @@ import {
110
104
  trackSpan,
111
105
  } from '@aztec/telemetry-client';
112
106
  import {
107
+ FullNodeCheckpointsBuilder as CheckpointsBuilder,
108
+ FullNodeCheckpointsBuilder,
113
109
  NodeKeystoreAdapter,
114
110
  ValidatorClient,
115
111
  createBlockProposalHandler,
@@ -129,6 +125,7 @@ import { NodeMetrics } from './node_metrics.js';
129
125
  */
130
126
  export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
131
127
  private metrics: NodeMetrics;
128
+ private initialHeaderHashPromise: Promise<BlockHash> | undefined = undefined;
132
129
 
133
130
  // Prevent two snapshot operations to happen simultaneously
134
131
  private isUploadingSnapshot = false;
@@ -144,6 +141,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
144
141
  protected readonly l1ToL2MessageSource: L1ToL2MessageSource,
145
142
  protected readonly worldStateSynchronizer: WorldStateSynchronizer,
146
143
  protected readonly sequencer: SequencerClient | undefined,
144
+ protected readonly proverNode: ProverNode | undefined,
147
145
  protected readonly slasherClient: SlasherClientInterface | undefined,
148
146
  protected readonly validatorsSentinel: Sentinel | undefined,
149
147
  protected readonly epochPruneWatcher: EpochPruneWatcher | undefined,
@@ -155,12 +153,23 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
155
153
  private proofVerifier: ClientProtocolCircuitVerifier,
156
154
  private telemetry: TelemetryClient = getTelemetryClient(),
157
155
  private log = createLogger('node'),
156
+ private blobClient?: BlobClientInterface,
157
+ private validatorClient?: ValidatorClient,
158
+ private keyStoreManager?: KeystoreManager,
159
+ private debugLogStore: DebugLogStore = new NullDebugLogStore(),
158
160
  ) {
159
161
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
160
162
  this.tracer = telemetry.getTracer('AztecNodeService');
161
163
 
162
164
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
163
165
  this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
166
+
167
+ // A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
168
+ // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
169
+ // memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
170
+ if (debugLogStore.isEnabled && config.realProofs) {
171
+ throw new Error('debugLogStore should never be enabled when realProofs are set');
172
+ }
164
173
  }
165
174
 
166
175
  public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
@@ -184,12 +193,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
184
193
  logger?: Logger;
185
194
  publisher?: SequencerPublisher;
186
195
  dateProvider?: DateProvider;
187
- blobSinkClient?: BlobSinkClientInterface;
188
- p2pClientDeps?: P2PClientDeps<P2PClientType.Full>;
196
+ p2pClientDeps?: P2PClientDeps;
197
+ proverNodeDeps?: Partial<ProverNodeDeps>;
189
198
  } = {},
190
199
  options: {
191
200
  prefilledPublicData?: PublicDataTreeLeaf[];
192
201
  dontStartSequencer?: boolean;
202
+ dontStartProverNode?: boolean;
193
203
  } = {},
194
204
  ): Promise<AztecNodeService> {
195
205
  const config = { ...inputConfig }; // Copy the config so we dont mutate the input object
@@ -197,20 +207,31 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
197
207
  const packageVersion = getPackageVersion() ?? '';
198
208
  const telemetry = deps.telemetry ?? getTelemetryClient();
199
209
  const dateProvider = deps.dateProvider ?? new DateProvider();
200
- const blobSinkClient =
201
- deps.blobSinkClient ?? createBlobSinkClient(config, { logger: createLogger('node:blob-sink:client') });
202
210
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
203
211
 
204
- // Build a key store from file if given or from environment otherwise
212
+ // Build a key store from file if given or from environment otherwise.
213
+ // We keep the raw KeyStore available so we can merge with prover keys if enableProverNode is set.
205
214
  let keyStoreManager: KeystoreManager | undefined;
206
215
  const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
207
216
  if (keyStoreProvided) {
208
217
  const keyStores = loadKeystores(config.keyStoreDirectory!);
209
218
  keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
210
219
  } else {
211
- const keyStore = createKeyStoreForValidator(config);
212
- if (keyStore) {
213
- keyStoreManager = new KeystoreManager(keyStore);
220
+ const rawKeyStores: KeyStore[] = [];
221
+ const validatorKeyStore = createKeyStoreForValidator(config);
222
+ if (validatorKeyStore) {
223
+ rawKeyStores.push(validatorKeyStore);
224
+ }
225
+ if (config.enableProverNode) {
226
+ const proverKeyStore = createKeyStoreForProver(config);
227
+ if (proverKeyStore) {
228
+ rawKeyStores.push(proverKeyStore);
229
+ }
230
+ }
231
+ if (rawKeyStores.length > 0) {
232
+ keyStoreManager = new KeystoreManager(
233
+ rawKeyStores.length === 1 ? rawKeyStores[0] : mergeKeystores(rawKeyStores),
234
+ );
214
235
  }
215
236
  }
216
237
 
@@ -221,10 +242,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
221
242
  if (keyStoreManager === undefined) {
222
243
  throw new Error('Failed to create key store, a requirement for running a validator');
223
244
  }
224
- if (!keyStoreProvided) {
225
- log.warn(
226
- 'KEY STORE CREATED FROM ENVIRONMENT, IT IS RECOMMENDED TO USE A FILE-BASED KEY STORE IN PRODUCTION ENVIRONMENTS',
227
- );
245
+ if (!keyStoreProvided && process.env.NODE_ENV !== 'test') {
246
+ log.warn("Keystore created from env: it's recommended to use a file-based key store for production");
228
247
  }
229
248
  ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
230
249
  }
@@ -238,7 +257,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
238
257
 
239
258
  const publicClient = createPublicClient({
240
259
  chain: ethereumChain.chainInfo,
241
- transport: fallback(config.l1RpcUrls.map((url: string) => http(url))),
260
+ transport: fallback(config.l1RpcUrls.map((url: string) => http(url, { batch: false }))),
242
261
  pollingInterval: config.viemPollingIntervalMS,
243
262
  });
244
263
 
@@ -252,10 +271,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
252
271
  config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
253
272
 
254
273
  const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
255
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
274
+ const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
256
275
  rollupContract.getL1GenesisTime(),
257
276
  rollupContract.getSlotDuration(),
258
277
  rollupContract.getVersion(),
278
+ rollupContract.getManaLimit().then(Number),
259
279
  ] as const);
260
280
 
261
281
  config.rollupVersion ??= Number(rollupVersionFromRollup);
@@ -266,6 +286,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
266
286
  );
267
287
  }
268
288
 
289
+ const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
290
+
269
291
  // attempt snapshot sync if possible
270
292
  await trySnapshotSync(config, log);
271
293
 
@@ -273,7 +295,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
273
295
 
274
296
  const archiver = await createArchiver(
275
297
  config,
276
- { blobSinkClient, epochCache, telemetry, dateProvider },
298
+ { blobClient, epochCache, telemetry, dateProvider },
277
299
  { blockUntilSync: !config.skipArchiverInitialSync },
278
300
  );
279
301
 
@@ -284,17 +306,32 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
284
306
  options.prefilledPublicData,
285
307
  telemetry,
286
308
  );
287
- const circuitVerifier = config.realProofs
288
- ? await BBCircuitVerifier.new(config)
289
- : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
309
+ const circuitVerifier =
310
+ config.realProofs || config.debugForceTxProofVerification
311
+ ? await BBCircuitVerifier.new(config)
312
+ : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
313
+
314
+ let debugLogStore: DebugLogStore;
290
315
  if (!config.realProofs) {
291
316
  log.warn(`Aztec node is accepting fake proofs`);
317
+
318
+ debugLogStore = new InMemoryDebugLogStore();
319
+ log.info(
320
+ 'Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served',
321
+ );
322
+ } else {
323
+ debugLogStore = new NullDebugLogStore();
292
324
  }
325
+
293
326
  const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
294
327
 
328
+ const proverOnly = config.enableProverNode && config.disableValidator;
329
+ if (proverOnly) {
330
+ log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
331
+ }
332
+
295
333
  // create the tx pool and the p2p client, which will need the l2 block source
296
334
  const p2pClient = await createP2PClient(
297
- P2PClientType.Full,
298
335
  config,
299
336
  archiver,
300
337
  proofVerifier,
@@ -306,55 +343,69 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
306
343
  deps.p2pClientDeps,
307
344
  );
308
345
 
309
- // We should really not be modifying the config object
310
- config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
346
+ // We'll accumulate sentinel watchers here
347
+ const watchers: Watcher[] = [];
311
348
 
312
- const blockBuilder = new BlockBuilder(
313
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
349
+ // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
350
+ // Override maxTxsPerCheckpoint with the validator-specific limit if set.
351
+ const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
352
+ {
353
+ ...config,
354
+ l1GenesisTime,
355
+ slotDuration: Number(slotDuration),
356
+ rollupManaLimit,
357
+ maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint,
358
+ },
314
359
  worldStateSynchronizer,
315
360
  archiver,
316
361
  dateProvider,
317
362
  telemetry,
318
363
  );
319
364
 
320
- // We'll accumulate sentinel watchers here
321
- const watchers: Watcher[] = [];
365
+ let validatorClient: ValidatorClient | undefined;
322
366
 
323
- // Create validator client if required
324
- const validatorClient = createValidatorClient(config, {
325
- p2pClient,
326
- telemetry,
327
- dateProvider,
328
- epochCache,
329
- blockBuilder,
330
- blockSource: archiver,
331
- l1ToL2MessageSource: archiver,
332
- keyStoreManager,
333
- });
367
+ if (!proverOnly) {
368
+ // Create validator client if required
369
+ validatorClient = await createValidatorClient(config, {
370
+ checkpointsBuilder: validatorCheckpointsBuilder,
371
+ worldState: worldStateSynchronizer,
372
+ p2pClient,
373
+ telemetry,
374
+ dateProvider,
375
+ epochCache,
376
+ blockSource: archiver,
377
+ l1ToL2MessageSource: archiver,
378
+ keyStoreManager,
379
+ blobClient,
380
+ });
334
381
 
335
- // If we have a validator client, register it as a source of offenses for the slasher,
336
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
337
- // like attestations or auths will fail.
338
- if (validatorClient) {
339
- watchers.push(validatorClient);
340
- if (!options.dontStartSequencer) {
341
- await validatorClient.registerHandlers();
382
+ // If we have a validator client, register it as a source of offenses for the slasher,
383
+ // and have it register callbacks on the p2p client *before* we start it, otherwise messages
384
+ // like attestations or auths will fail.
385
+ if (validatorClient) {
386
+ watchers.push(validatorClient);
387
+ if (!options.dontStartSequencer) {
388
+ await validatorClient.registerHandlers();
389
+ }
342
390
  }
343
391
  }
344
392
 
345
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
346
- // create a BlockProposalHandler to reexecute block proposals for monitoring
347
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
348
- log.info('Setting up block proposal reexecution for monitoring');
393
+ // If there's no validator client, create a BlockProposalHandler to handle block proposals
394
+ // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
395
+ // while non-reexecution is used for validating the proposals and collecting their txs.
396
+ if (!validatorClient) {
397
+ const reexecute = !!config.alwaysReexecuteBlockProposals;
398
+ log.info(`Setting up block proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
349
399
  createBlockProposalHandler(config, {
350
- blockBuilder,
400
+ checkpointsBuilder: validatorCheckpointsBuilder,
401
+ worldState: worldStateSynchronizer,
351
402
  epochCache,
352
403
  blockSource: archiver,
353
404
  l1ToL2MessageSource: archiver,
354
405
  p2pClient,
355
406
  dateProvider,
356
407
  telemetry,
357
- }).registerForReexecution(p2pClient);
408
+ }).register(p2pClient, reexecute);
358
409
  }
359
410
 
360
411
  // Start world state and wait for it to sync to the archiver.
@@ -363,29 +414,33 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
363
414
  // Start p2p. Note that it depends on world state to be running.
364
415
  await p2pClient.start();
365
416
 
366
- const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
367
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
368
- watchers.push(validatorsSentinel);
369
- }
370
-
417
+ let validatorsSentinel: Awaited<ReturnType<typeof createSentinel>> | undefined;
371
418
  let epochPruneWatcher: EpochPruneWatcher | undefined;
372
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
373
- epochPruneWatcher = new EpochPruneWatcher(
374
- archiver,
375
- archiver,
376
- epochCache,
377
- p2pClient.getTxProvider(),
378
- blockBuilder,
379
- config,
380
- );
381
- watchers.push(epochPruneWatcher);
382
- }
383
-
384
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
385
419
  let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
386
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
387
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
388
- watchers.push(attestationsBlockWatcher);
420
+
421
+ if (!proverOnly) {
422
+ validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
423
+ if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
424
+ watchers.push(validatorsSentinel);
425
+ }
426
+
427
+ if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
428
+ epochPruneWatcher = new EpochPruneWatcher(
429
+ archiver,
430
+ archiver,
431
+ epochCache,
432
+ p2pClient.getTxProvider(),
433
+ validatorCheckpointsBuilder,
434
+ config,
435
+ );
436
+ watchers.push(epochPruneWatcher);
437
+ }
438
+
439
+ // We assume we want to slash for invalid attestations unless all max penalties are set to 0
440
+ if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
441
+ attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
442
+ watchers.push(attestationsBlockWatcher);
443
+ }
389
444
  }
390
445
 
391
446
  // Start p2p-related services once the archiver has completed sync
@@ -403,7 +458,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
403
458
  // Validator enabled, create/start relevant service
404
459
  let sequencer: SequencerClient | undefined;
405
460
  let slasherClient: SlasherClientInterface | undefined;
406
- if (!config.disableValidator) {
461
+ if (!config.disableValidator && validatorClient) {
407
462
  // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
408
463
  // as they are executed when the node is selected as proposer.
409
464
  const validatorAddresses = keyStoreManager
@@ -422,14 +477,31 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
422
477
  );
423
478
  await slasherClient.start();
424
479
 
425
- const l1TxUtils = await createL1TxUtilsWithBlobsFromEthSigner(
426
- publicClient,
427
- keyStoreManager!.createAllValidatorPublisherSigners(),
428
- { ...config, scope: 'sequencer' },
429
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider },
430
- );
480
+ const l1TxUtils = config.sequencerPublisherForwarderAddress
481
+ ? await createForwarderL1TxUtilsFromSigners(
482
+ publicClient,
483
+ keyStoreManager!.createAllValidatorPublisherSigners(),
484
+ config.sequencerPublisherForwarderAddress,
485
+ { ...config, scope: 'sequencer' },
486
+ { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
487
+ )
488
+ : await createL1TxUtilsFromSigners(
489
+ publicClient,
490
+ keyStoreManager!.createAllValidatorPublisherSigners(),
491
+ { ...config, scope: 'sequencer' },
492
+ { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
493
+ );
431
494
 
432
495
  // Create and start the sequencer client
496
+ const checkpointsBuilder = new CheckpointsBuilder(
497
+ { ...config, l1GenesisTime, slotDuration: Number(slotDuration), rollupManaLimit },
498
+ worldStateSynchronizer,
499
+ archiver,
500
+ dateProvider,
501
+ telemetry,
502
+ debugLogStore,
503
+ );
504
+
433
505
  sequencer = await SequencerClient.new(config, {
434
506
  ...deps,
435
507
  epochCache,
@@ -438,12 +510,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
438
510
  p2pClient,
439
511
  worldStateSynchronizer,
440
512
  slasherClient,
441
- blockBuilder,
513
+ checkpointsBuilder,
442
514
  l2BlockSource: archiver,
443
515
  l1ToL2MessageSource: archiver,
444
516
  telemetry,
445
517
  dateProvider,
446
- blobSinkClient,
518
+ blobClient,
447
519
  nodeKeyStore: keyStoreManager!,
448
520
  });
449
521
  }
@@ -455,7 +527,37 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
455
527
  log.warn(`Sequencer created but not started`);
456
528
  }
457
529
 
458
- return new AztecNodeService(
530
+ // Create prover node subsystem if enabled
531
+ let proverNode: ProverNode | undefined;
532
+ if (config.enableProverNode) {
533
+ proverNode = await createProverNode(config, {
534
+ ...deps.proverNodeDeps,
535
+ telemetry,
536
+ dateProvider,
537
+ archiver,
538
+ worldStateSynchronizer,
539
+ p2pClient,
540
+ epochCache,
541
+ blobClient,
542
+ keyStoreManager,
543
+ });
544
+
545
+ if (!options.dontStartProverNode) {
546
+ await proverNode.start();
547
+ log.info(`Prover node subsystem started`);
548
+ } else {
549
+ log.info(`Prover node subsystem created but not started`);
550
+ }
551
+ }
552
+
553
+ const globalVariableBuilder = new GlobalVariableBuilder({
554
+ ...config,
555
+ rollupVersion: BigInt(config.rollupVersion),
556
+ l1GenesisTime,
557
+ slotDuration: Number(slotDuration),
558
+ });
559
+
560
+ const node = new AztecNodeService(
459
561
  config,
460
562
  p2pClient,
461
563
  archiver,
@@ -464,18 +566,25 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
464
566
  archiver,
465
567
  worldStateSynchronizer,
466
568
  sequencer,
569
+ proverNode,
467
570
  slasherClient,
468
571
  validatorsSentinel,
469
572
  epochPruneWatcher,
470
573
  ethereumChain.chainInfo.id,
471
574
  config.rollupVersion,
472
- new GlobalVariableBuilder(config),
575
+ globalVariableBuilder,
473
576
  epochCache,
474
577
  packageVersion,
475
578
  proofVerifier,
476
579
  telemetry,
477
580
  log,
581
+ blobClient,
582
+ validatorClient,
583
+ keyStoreManager,
584
+ debugLogStore,
478
585
  );
586
+
587
+ return node;
479
588
  }
480
589
 
481
590
  /**
@@ -486,6 +595,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
486
595
  return this.sequencer;
487
596
  }
488
597
 
598
+ /** Returns the prover node subsystem, if enabled. */
599
+ public getProverNode(): ProverNode | undefined {
600
+ return this.proverNode;
601
+ }
602
+
489
603
  public getBlockSource(): L2BlockSource {
490
604
  return this.blockSource;
491
605
  }
@@ -511,7 +625,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
511
625
  }
512
626
 
513
627
  public async getAllowedPublicSetup(): Promise<AllowedElement[]> {
514
- return this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
628
+ return [...(await getDefaultAllowedSetupFunctions()), ...(this.config.txPublicSetupAllowListExtend ?? [])];
515
629
  }
516
630
 
517
631
  /**
@@ -539,19 +653,26 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
539
653
  enr,
540
654
  l1ContractAddresses: contractAddresses,
541
655
  protocolContractAddresses: protocolContractAddresses,
656
+ realProofs: !!this.config.realProofs,
542
657
  };
543
658
 
544
659
  return nodeInfo;
545
660
  }
546
661
 
547
662
  /**
548
- * Get a block specified by its number.
549
- * @param number - The block number being requested.
663
+ * Get a block specified by its block number, block hash, or 'latest'.
664
+ * @param block - The block parameter (block number, block hash, or 'latest').
550
665
  * @returns The requested block.
551
666
  */
552
- public async getBlock(number: L2BlockNumber): Promise<L2Block | undefined> {
553
- const blockNumber = number === 'latest' ? await this.getBlockNumber() : number;
554
- return await this.blockSource.getBlock(blockNumber);
667
+ public async getBlock(block: BlockParameter): Promise<L2Block | undefined> {
668
+ if (BlockHash.isBlockHash(block)) {
669
+ return this.getBlockByHash(block);
670
+ }
671
+ const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
672
+ if (blockNumber === BlockNumber.ZERO) {
673
+ return this.buildInitialBlock();
674
+ }
675
+ return await this.blockSource.getL2Block(blockNumber);
555
676
  }
556
677
 
557
678
  /**
@@ -559,9 +680,17 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
559
680
  * @param blockHash - The block hash being requested.
560
681
  * @returns The requested block.
561
682
  */
562
- public async getBlockByHash(blockHash: Fr): Promise<L2Block | undefined> {
563
- const publishedBlock = await this.blockSource.getPublishedBlockByHash(blockHash);
564
- return publishedBlock?.block;
683
+ public async getBlockByHash(blockHash: BlockHash): Promise<L2Block | undefined> {
684
+ const initialBlockHash = await this.#getInitialHeaderHash();
685
+ if (blockHash.equals(initialBlockHash)) {
686
+ return this.buildInitialBlock();
687
+ }
688
+ return await this.blockSource.getL2BlockByHash(blockHash);
689
+ }
690
+
691
+ private buildInitialBlock(): L2Block {
692
+ const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
693
+ return L2Block.empty(initialHeader);
565
694
  }
566
695
 
567
696
  /**
@@ -570,8 +699,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
570
699
  * @returns The requested block.
571
700
  */
572
701
  public async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
573
- const publishedBlock = await this.blockSource.getPublishedBlockByArchive(archive);
574
- return publishedBlock?.block;
702
+ return await this.blockSource.getL2BlockByArchive(archive);
575
703
  }
576
704
 
577
705
  /**
@@ -580,34 +708,54 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
580
708
  * @param limit - The maximum number of blocks to obtain.
581
709
  * @returns The blocks requested.
582
710
  */
583
- public async getBlocks(from: number, limit: number): Promise<L2Block[]> {
584
- return (await this.blockSource.getBlocks(from, limit)) ?? [];
711
+ public async getBlocks(from: BlockNumber, limit: number): Promise<L2Block[]> {
712
+ return (await this.blockSource.getBlocks(from, BlockNumber(limit))) ?? [];
713
+ }
714
+
715
+ public async getCheckpoints(from: CheckpointNumber, limit: number): Promise<PublishedCheckpoint[]> {
716
+ return (await this.blockSource.getCheckpoints(from, limit)) ?? [];
585
717
  }
586
718
 
587
- public async getPublishedBlocks(from: number, limit: number): Promise<PublishedL2Block[]> {
588
- return (await this.blockSource.getPublishedBlocks(from, limit)) ?? [];
719
+ public async getCheckpointedBlocks(from: BlockNumber, limit: number) {
720
+ return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
589
721
  }
590
722
 
591
723
  /**
592
- * Method to fetch the current base fees.
593
- * @returns The current base fees.
724
+ * Method to fetch the current min L2 fees.
725
+ * @returns The current min L2 fees.
594
726
  */
595
- public async getCurrentBaseFees(): Promise<GasFees> {
596
- return await this.globalVariableBuilder.getCurrentBaseFees();
727
+ public async getCurrentMinFees(): Promise<GasFees> {
728
+ return await this.globalVariableBuilder.getCurrentMinFees();
729
+ }
730
+
731
+ public async getMaxPriorityFees(): Promise<GasFees> {
732
+ for await (const tx of this.p2pClient.iteratePendingTxs()) {
733
+ return tx.getGasSettings().maxPriorityFeesPerGas;
734
+ }
735
+
736
+ return GasFees.from({ feePerDaGas: 0n, feePerL2Gas: 0n });
597
737
  }
598
738
 
599
739
  /**
600
740
  * Method to fetch the latest block number synchronized by the node.
601
741
  * @returns The block number.
602
742
  */
603
- public async getBlockNumber(): Promise<number> {
743
+ public async getBlockNumber(): Promise<BlockNumber> {
604
744
  return await this.blockSource.getBlockNumber();
605
745
  }
606
746
 
607
- public async getProvenBlockNumber(): Promise<number> {
747
+ public async getProvenBlockNumber(): Promise<BlockNumber> {
608
748
  return await this.blockSource.getProvenBlockNumber();
609
749
  }
610
750
 
751
+ public async getCheckpointedBlockNumber(): Promise<BlockNumber> {
752
+ return await this.blockSource.getCheckpointedL2BlockNumber();
753
+ }
754
+
755
+ public getCheckpointNumber(): Promise<CheckpointNumber> {
756
+ return this.blockSource.getCheckpointNumber();
757
+ }
758
+
611
759
  /**
612
760
  * Method to fetch the version of the package.
613
761
  * @returns The node package version
@@ -640,25 +788,43 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
640
788
  return this.contractDataSource.getContract(address);
641
789
  }
642
790
 
643
- /**
644
- * Retrieves all private logs from up to `limit` blocks, starting from the block number `from`.
645
- * @param from - The block number from which to begin retrieving logs.
646
- * @param limit - The maximum number of blocks to retrieve logs from.
647
- * @returns An array of private logs from the specified range of blocks.
648
- */
649
- public getPrivateLogs(from: number, limit: number): Promise<PrivateLog[]> {
650
- return this.logsSource.getPrivateLogs(from, limit);
651
- }
652
-
653
- /**
654
- * Gets all logs that match any of the received tags (i.e. logs with their first field equal to a tag).
655
- * @param tags - The tags to filter the logs by.
656
- * @param logsPerTag - The maximum number of logs to return for each tag. By default no limit is set
657
- * @returns For each received tag, an array of matching logs is returned. An empty array implies no logs match
658
- * that tag.
659
- */
660
- public getLogsByTags(tags: Fr[], logsPerTag?: number): Promise<TxScopedL2Log[][]> {
661
- return this.logsSource.getLogsByTags(tags, logsPerTag);
791
+ public async getPrivateLogsByTags(
792
+ tags: SiloedTag[],
793
+ page?: number,
794
+ referenceBlock?: BlockHash,
795
+ ): Promise<TxScopedL2Log[][]> {
796
+ if (referenceBlock) {
797
+ const initialBlockHash = await this.#getInitialHeaderHash();
798
+ if (!referenceBlock.equals(initialBlockHash)) {
799
+ const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
800
+ if (!header) {
801
+ throw new Error(
802
+ `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
803
+ );
804
+ }
805
+ }
806
+ }
807
+ return this.logsSource.getPrivateLogsByTags(tags, page);
808
+ }
809
+
810
+ public async getPublicLogsByTagsFromContract(
811
+ contractAddress: AztecAddress,
812
+ tags: Tag[],
813
+ page?: number,
814
+ referenceBlock?: BlockHash,
815
+ ): Promise<TxScopedL2Log[][]> {
816
+ if (referenceBlock) {
817
+ const initialBlockHash = await this.#getInitialHeaderHash();
818
+ if (!referenceBlock.equals(initialBlockHash)) {
819
+ const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
820
+ if (!header) {
821
+ throw new Error(
822
+ `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
823
+ );
824
+ }
825
+ }
826
+ }
827
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
662
828
  }
663
829
 
664
830
  /**
@@ -700,26 +866,36 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
700
866
  }
701
867
 
702
868
  await this.p2pClient!.sendTx(tx);
703
- this.metrics.receivedTx(timer.ms(), true);
704
- this.log.info(`Received tx ${txHash}`, { txHash });
869
+ const duration = timer.ms();
870
+ this.metrics.receivedTx(duration, true);
871
+ this.log.info(`Received tx ${txHash} in ${duration}ms`, { txHash });
705
872
  }
706
873
 
707
874
  public async getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
708
- let txReceipt = new TxReceipt(txHash, TxStatus.DROPPED, 'Tx dropped by P2P node.');
709
-
710
- // We first check if the tx is in pending (instead of first checking if it is mined) because if we first check
711
- // for mined and then for pending there could be a race condition where the tx is mined between the two checks
712
- // and we would incorrectly return a TxReceipt with status DROPPED
713
- if ((await this.p2pClient.getTxStatus(txHash)) === 'pending') {
714
- txReceipt = new TxReceipt(txHash, TxStatus.PENDING, '');
715
- }
875
+ // Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
876
+ // as a fallback if we don't find a settled receipt in the archiver.
877
+ const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
878
+ const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
716
879
 
880
+ // Then get the actual tx from the archiver, which tracks every tx in a mined block.
717
881
  const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
882
+
883
+ let receipt: TxReceipt;
718
884
  if (settledTxReceipt) {
719
- txReceipt = settledTxReceipt;
885
+ receipt = settledTxReceipt;
886
+ } else if (isKnownToPool) {
887
+ // If the tx is in the pool but not in the archiver, it's pending.
888
+ // This handles race conditions between archiver and p2p, where the archiver
889
+ // has pruned the block in which a tx was mined, but p2p has not caught up yet.
890
+ receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
891
+ } else {
892
+ // Otherwise, if we don't know the tx, we consider it dropped.
893
+ receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
720
894
  }
721
895
 
722
- return txReceipt;
896
+ this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
897
+
898
+ return receipt;
723
899
  }
724
900
 
725
901
  public getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined> {
@@ -736,13 +912,23 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
736
912
  await tryStop(this.slasherClient);
737
913
  await tryStop(this.proofVerifier);
738
914
  await tryStop(this.sequencer);
915
+ await tryStop(this.proverNode);
739
916
  await tryStop(this.p2pClient);
740
917
  await tryStop(this.worldStateSynchronizer);
741
918
  await tryStop(this.blockSource);
919
+ await tryStop(this.blobClient);
742
920
  await tryStop(this.telemetry);
743
921
  this.log.info(`Stopped Aztec Node`);
744
922
  }
745
923
 
924
+ /**
925
+ * Returns the blob client used by this node.
926
+ * @internal - Exposed for testing purposes only.
927
+ */
928
+ public getBlobClient(): BlobClientInterface | undefined {
929
+ return this.blobClient;
930
+ }
931
+
746
932
  /**
747
933
  * Method to retrieve pending txs.
748
934
  * @param limit - The number of items to returns
@@ -775,20 +961,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
775
961
  return compactArray(await Promise.all(txHashes.map(txHash => this.getTxByHash(txHash))));
776
962
  }
777
963
 
778
- /**
779
- * Find the indexes of the given leaves in the given tree along with a block metadata pointing to the block in which
780
- * the leaves were inserted.
781
- * @param blockNumber - The block number at which to get the data or 'latest' for latest data.
782
- * @param treeId - The tree to search in.
783
- * @param leafValues - The values to search for.
784
- * @returns The indices of leaves and the block metadata of a block in which the leaves were inserted.
785
- */
786
964
  public async findLeavesIndexes(
787
- blockNumber: L2BlockNumber,
965
+ referenceBlock: BlockParameter,
788
966
  treeId: MerkleTreeId,
789
967
  leafValues: Fr[],
790
- ): Promise<(InBlock<bigint> | undefined)[]> {
791
- const committedDb = await this.#getWorldState(blockNumber);
968
+ ): Promise<(DataInBlock<bigint> | undefined)[]> {
969
+ const committedDb = await this.#getWorldState(referenceBlock);
792
970
  const maybeIndices = await committedDb.findLeafIndices(
793
971
  treeId,
794
972
  leafValues.map(x => x.toBuffer()),
@@ -813,7 +991,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
813
991
  // (note that block number corresponds to the leaf index in the archive tree).
814
992
  const blockHashes = await Promise.all(
815
993
  uniqueBlockNumbers.map(blockNumber => {
816
- return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, blockNumber!);
994
+ return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
817
995
  }),
818
996
  );
819
997
 
@@ -824,7 +1002,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
824
1002
  }
825
1003
  }
826
1004
 
827
- // Create InBlock objects by combining indices, blockNumbers and blockHashes and return them.
1005
+ // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
828
1006
  return maybeIndices.map((index, i) => {
829
1007
  if (index === undefined) {
830
1008
  return undefined;
@@ -839,57 +1017,29 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
839
1017
  return undefined;
840
1018
  }
841
1019
  return {
842
- l2BlockNumber: Number(blockNumber),
843
- l2BlockHash: L2BlockHash.fromField(blockHash),
1020
+ l2BlockNumber: BlockNumber(Number(blockNumber)),
1021
+ l2BlockHash: new BlockHash(blockHash),
844
1022
  data: index,
845
1023
  };
846
1024
  });
847
1025
  }
848
1026
 
849
- /**
850
- * Returns a sibling path for the given index in the nullifier tree.
851
- * @param blockNumber - The block number at which to get the data.
852
- * @param leafIndex - The index of the leaf for which the sibling path is required.
853
- * @returns The sibling path for the leaf index.
854
- */
855
- public async getNullifierSiblingPath(
856
- blockNumber: L2BlockNumber,
857
- leafIndex: bigint,
858
- ): Promise<SiblingPath<typeof NULLIFIER_TREE_HEIGHT>> {
859
- const committedDb = await this.#getWorldState(blockNumber);
860
- return committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, leafIndex);
861
- }
862
-
863
- /**
864
- * Returns a sibling path for the given index in the data tree.
865
- * @param blockNumber - The block number at which to get the data.
866
- * @param leafIndex - The index of the leaf for which the sibling path is required.
867
- * @returns The sibling path for the leaf index.
868
- */
869
- public async getNoteHashSiblingPath(
870
- blockNumber: L2BlockNumber,
871
- leafIndex: bigint,
872
- ): Promise<SiblingPath<typeof NOTE_HASH_TREE_HEIGHT>> {
873
- const committedDb = await this.#getWorldState(blockNumber);
874
- return committedDb.getSiblingPath(MerkleTreeId.NOTE_HASH_TREE, leafIndex);
875
- }
876
-
877
- public async getArchiveMembershipWitness(
878
- blockNumber: L2BlockNumber,
879
- archive: Fr,
1027
+ public async getBlockHashMembershipWitness(
1028
+ referenceBlock: BlockParameter,
1029
+ blockHash: BlockHash,
880
1030
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
881
- const committedDb = await this.#getWorldState(blockNumber);
882
- const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [archive]);
1031
+ const committedDb = await this.#getWorldState(referenceBlock);
1032
+ const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
883
1033
  return pathAndIndex === undefined
884
1034
  ? undefined
885
1035
  : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
886
1036
  }
887
1037
 
888
1038
  public async getNoteHashMembershipWitness(
889
- blockNumber: L2BlockNumber,
1039
+ referenceBlock: BlockParameter,
890
1040
  noteHash: Fr,
891
1041
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
892
- const committedDb = await this.#getWorldState(blockNumber);
1042
+ const committedDb = await this.#getWorldState(referenceBlock);
893
1043
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
894
1044
  MerkleTreeId.NOTE_HASH_TREE,
895
1045
  [noteHash],
@@ -899,17 +1049,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
899
1049
  : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
900
1050
  }
901
1051
 
902
- /**
903
- * Returns the index and a sibling path for a leaf in the committed l1 to l2 data tree.
904
- * @param blockNumber - The block number at which to get the data.
905
- * @param l1ToL2Message - The l1ToL2Message to get the index / sibling path for.
906
- * @returns A tuple of the index and the sibling path of the L1ToL2Message (undefined if not found).
907
- */
908
1052
  public async getL1ToL2MessageMembershipWitness(
909
- blockNumber: L2BlockNumber,
1053
+ referenceBlock: BlockParameter,
910
1054
  l1ToL2Message: Fr,
911
1055
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
912
- const db = await this.#getWorldState(blockNumber);
1056
+ const db = await this.#getWorldState(referenceBlock);
913
1057
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
914
1058
  if (!witness) {
915
1059
  return undefined;
@@ -919,9 +1063,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
919
1063
  return [witness.index, witness.path];
920
1064
  }
921
1065
 
922
- public async getL1ToL2MessageBlock(l1ToL2Message: Fr): Promise<number | undefined> {
1066
+ public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
923
1067
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
924
- return messageIndex ? InboxLeaf.l2BlockFromIndex(messageIndex) : undefined;
1068
+ return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
925
1069
  }
926
1070
 
927
1071
  /**
@@ -935,54 +1079,36 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
935
1079
  }
936
1080
 
937
1081
  /**
938
- * Returns all the L2 to L1 messages in a block.
939
- * @param blockNumber - The block number at which to get the data.
940
- * @returns The L2 to L1 messages (undefined if the block number is not found).
941
- */
942
- public async getL2ToL1Messages(blockNumber: L2BlockNumber): Promise<Fr[][] | undefined> {
943
- const block = await this.blockSource.getBlock(blockNumber === 'latest' ? await this.getBlockNumber() : blockNumber);
944
- return block?.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs);
945
- }
946
-
947
- /**
948
- * Returns a sibling path for a leaf in the committed blocks tree.
949
- * @param blockNumber - The block number at which to get the data.
950
- * @param leafIndex - Index of the leaf in the tree.
951
- * @returns The sibling path.
1082
+ * Returns all the L2 to L1 messages in an epoch.
1083
+ * @param epoch - The epoch at which to get the data.
1084
+ * @returns The L2 to L1 messages (empty array if the epoch is not found).
952
1085
  */
953
- public async getArchiveSiblingPath(
954
- blockNumber: L2BlockNumber,
955
- leafIndex: bigint,
956
- ): Promise<SiblingPath<typeof ARCHIVE_HEIGHT>> {
957
- const committedDb = await this.#getWorldState(blockNumber);
958
- return committedDb.getSiblingPath(MerkleTreeId.ARCHIVE, leafIndex);
959
- }
960
-
961
- /**
962
- * Returns a sibling path for a leaf in the committed public data tree.
963
- * @param blockNumber - The block number at which to get the data.
964
- * @param leafIndex - Index of the leaf in the tree.
965
- * @returns The sibling path.
966
- */
967
- public async getPublicDataSiblingPath(
968
- blockNumber: L2BlockNumber,
969
- leafIndex: bigint,
970
- ): Promise<SiblingPath<typeof PUBLIC_DATA_TREE_HEIGHT>> {
971
- const committedDb = await this.#getWorldState(blockNumber);
972
- return committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, leafIndex);
1086
+ public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
1087
+ // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1088
+ const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1089
+ const blocksInCheckpoints: L2Block[][] = [];
1090
+ let previousSlotNumber = SlotNumber.ZERO;
1091
+ let checkpointIndex = -1;
1092
+ for (const checkpointedBlock of checkpointedBlocks) {
1093
+ const block = checkpointedBlock.block;
1094
+ const slotNumber = block.header.globalVariables.slotNumber;
1095
+ if (slotNumber !== previousSlotNumber) {
1096
+ checkpointIndex++;
1097
+ blocksInCheckpoints.push([]);
1098
+ previousSlotNumber = slotNumber;
1099
+ }
1100
+ blocksInCheckpoints[checkpointIndex].push(block);
1101
+ }
1102
+ return blocksInCheckpoints.map(blocks =>
1103
+ blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1104
+ );
973
1105
  }
974
1106
 
975
- /**
976
- * Returns a nullifier membership witness for a given nullifier at a given block.
977
- * @param blockNumber - The block number at which to get the index.
978
- * @param nullifier - Nullifier we try to find witness for.
979
- * @returns The nullifier membership witness (if found).
980
- */
981
1107
  public async getNullifierMembershipWitness(
982
- blockNumber: L2BlockNumber,
1108
+ referenceBlock: BlockParameter,
983
1109
  nullifier: Fr,
984
1110
  ): Promise<NullifierMembershipWitness | undefined> {
985
- const db = await this.#getWorldState(blockNumber);
1111
+ const db = await this.#getWorldState(referenceBlock);
986
1112
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
987
1113
  if (!witness) {
988
1114
  return undefined;
@@ -999,7 +1125,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
999
1125
 
1000
1126
  /**
1001
1127
  * Returns a low nullifier membership witness for a given nullifier at a given block.
1002
- * @param blockNumber - The block number at which to get the index.
1128
+ * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1129
+ * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1003
1130
  * @param nullifier - Nullifier we try to find the low nullifier witness for.
1004
1131
  * @returns The low nullifier membership witness (if found).
1005
1132
  * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
@@ -1012,10 +1139,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1012
1139
  * TODO: This is a confusing behavior and we should eventually address that.
1013
1140
  */
1014
1141
  public async getLowNullifierMembershipWitness(
1015
- blockNumber: L2BlockNumber,
1142
+ referenceBlock: BlockParameter,
1016
1143
  nullifier: Fr,
1017
1144
  ): Promise<NullifierMembershipWitness | undefined> {
1018
- const committedDb = await this.#getWorldState(blockNumber);
1145
+ const committedDb = await this.#getWorldState(referenceBlock);
1019
1146
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1020
1147
  if (!findResult) {
1021
1148
  return undefined;
@@ -1030,8 +1157,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1030
1157
  return new NullifierMembershipWitness(BigInt(index), preimageData as NullifierLeafPreimage, siblingPath);
1031
1158
  }
1032
1159
 
1033
- async getPublicDataWitness(blockNumber: L2BlockNumber, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1034
- const committedDb = await this.#getWorldState(blockNumber);
1160
+ async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1161
+ const committedDb = await this.#getWorldState(referenceBlock);
1035
1162
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1036
1163
  if (!lowLeafResult) {
1037
1164
  return undefined;
@@ -1045,19 +1172,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1045
1172
  }
1046
1173
  }
1047
1174
 
1048
- /**
1049
- * Gets the storage value at the given contract storage slot.
1050
- *
1051
- * @remarks The storage slot here refers to the slot as it is defined in Noir not the index in the merkle tree.
1052
- * Aztec's version of `eth_getStorageAt`.
1053
- *
1054
- * @param contract - Address of the contract to query.
1055
- * @param slot - Slot to query.
1056
- * @param blockNumber - The block number at which to get the data or 'latest'.
1057
- * @returns Storage value at the given contract slot.
1058
- */
1059
- public async getPublicStorageAt(blockNumber: L2BlockNumber, contract: AztecAddress, slot: Fr): Promise<Fr> {
1060
- const committedDb = await this.#getWorldState(blockNumber);
1175
+ public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1176
+ const committedDb = await this.#getWorldState(referenceBlock);
1061
1177
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1062
1178
 
1063
1179
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
@@ -1071,23 +1187,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1071
1187
  return preimage.leaf.value;
1072
1188
  }
1073
1189
 
1074
- /**
1075
- * Returns the currently committed block header, or the initial header if no blocks have been produced.
1076
- * @returns The current committed block header.
1077
- */
1078
- public async getBlockHeader(blockNumber: L2BlockNumber = 'latest'): Promise<BlockHeader | undefined> {
1079
- return blockNumber === 0 || (blockNumber === 'latest' && (await this.blockSource.getBlockNumber()) === 0)
1080
- ? this.worldStateSynchronizer.getCommitted().getInitialHeader()
1081
- : this.blockSource.getBlockHeader(blockNumber);
1082
- }
1083
-
1084
- /**
1085
- * Get a block header specified by its hash.
1086
- * @param blockHash - The block hash being requested.
1087
- * @returns The requested block header.
1088
- */
1089
- public async getBlockHeaderByHash(blockHash: Fr): Promise<BlockHeader | undefined> {
1090
- return await this.blockSource.getBlockHeaderByHash(blockHash);
1190
+ public async getBlockHeader(block: BlockParameter = 'latest'): Promise<BlockHeader | undefined> {
1191
+ if (BlockHash.isBlockHash(block)) {
1192
+ const initialBlockHash = await this.#getInitialHeaderHash();
1193
+ if (block.equals(initialBlockHash)) {
1194
+ // Block source doesn't handle initial header so we need to handle the case separately.
1195
+ return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1196
+ }
1197
+ return this.blockSource.getBlockHeaderByHash(block);
1198
+ } else {
1199
+ // Block source doesn't handle initial header so we need to handle the case separately.
1200
+ const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
1201
+ if (blockNumber === BlockNumber.ZERO) {
1202
+ return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1203
+ }
1204
+ return this.blockSource.getBlockHeader(block);
1205
+ }
1091
1206
  }
1092
1207
 
1093
1208
  /**
@@ -1099,6 +1214,14 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1099
1214
  return await this.blockSource.getBlockHeaderByArchive(archive);
1100
1215
  }
1101
1216
 
1217
+ public getBlockData(number: BlockNumber): Promise<BlockData | undefined> {
1218
+ return this.blockSource.getBlockData(number);
1219
+ }
1220
+
1221
+ public getBlockDataByArchive(archive: Fr): Promise<BlockData | undefined> {
1222
+ return this.blockSource.getBlockDataByArchive(archive);
1223
+ }
1224
+
1102
1225
  /**
1103
1226
  * Simulates the public part of a transaction with the current state.
1104
1227
  * @param tx - The transaction to simulate.
@@ -1122,7 +1245,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1122
1245
  }
1123
1246
 
1124
1247
  const txHash = tx.getTxHash();
1125
- const blockNumber = (await this.blockSource.getBlockNumber()) + 1;
1248
+ const latestBlockNumber = await this.blockSource.getBlockNumber();
1249
+ const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1126
1250
 
1127
1251
  // If sequencer is not initialized, we just set these values to zero for simulation.
1128
1252
  const coinbase = EthAddress.ZERO;
@@ -1137,6 +1261,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1137
1261
  this.contractDataSource,
1138
1262
  new DateProvider(),
1139
1263
  this.telemetry,
1264
+ this.log.getBindings(),
1140
1265
  );
1141
1266
 
1142
1267
  this.log.verbose(`Simulating public calls for tx ${txHash}`, {
@@ -1145,6 +1270,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1145
1270
  blockNumber,
1146
1271
  });
1147
1272
 
1273
+ // Ensure world-state has caught up with the latest block we loaded from the archiver
1274
+ await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1148
1275
  const merkleTreeFork = await this.worldStateSynchronizer.fork();
1149
1276
  try {
1150
1277
  const config = PublicSimulatorConfig.from({
@@ -1152,13 +1279,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1152
1279
  collectDebugLogs: true,
1153
1280
  collectHints: false,
1154
1281
  collectCallMetadata: true,
1155
- maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads,
1156
1282
  collectStatistics: false,
1283
+ collectionLimits: CollectionLimitsConfig.from({
1284
+ maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads,
1285
+ }),
1157
1286
  });
1158
1287
  const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1159
1288
 
1160
1289
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1161
- const [processedTxs, failedTxs, _usedTxs, returns] = await processor.process([tx]);
1290
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1162
1291
  // REFACTOR: Consider returning the error rather than throwing
1163
1292
  if (failedTxs.length) {
1164
1293
  this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
@@ -1172,6 +1301,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1172
1301
  processedTx.txEffect,
1173
1302
  returns,
1174
1303
  processedTx.gasUsed,
1304
+ debugLogs,
1175
1305
  );
1176
1306
  } finally {
1177
1307
  await merkleTreeFork.close();
@@ -1185,19 +1315,28 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1185
1315
  const db = this.worldStateSynchronizer.getCommitted();
1186
1316
  const verifier = isSimulation ? undefined : this.proofVerifier;
1187
1317
 
1188
- // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
1318
+ // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1189
1319
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1190
- const blockNumber = (await this.blockSource.getBlockNumber()) + 1;
1191
- const validator = createValidatorForAcceptingTxs(db, this.contractDataSource, verifier, {
1192
- timestamp: nextSlotTimestamp,
1193
- blockNumber,
1194
- l1ChainId: this.l1ChainId,
1195
- rollupVersion: this.version,
1196
- setupAllowList: this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions()),
1197
- gasFees: await this.getCurrentBaseFees(),
1198
- skipFeeEnforcement,
1199
- txsPermitted: !this.config.disableTransactions,
1200
- });
1320
+ const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1321
+ const validator = createTxValidatorForAcceptingTxsOverRPC(
1322
+ db,
1323
+ this.contractDataSource,
1324
+ verifier,
1325
+ {
1326
+ timestamp: nextSlotTimestamp,
1327
+ blockNumber,
1328
+ l1ChainId: this.l1ChainId,
1329
+ rollupVersion: this.version,
1330
+ setupAllowList: [
1331
+ ...(await getDefaultAllowedSetupFunctions()),
1332
+ ...(this.config.txPublicSetupAllowListExtend ?? []),
1333
+ ],
1334
+ gasFees: await this.getCurrentMinFees(),
1335
+ skipFeeEnforcement,
1336
+ txsPermitted: !this.config.disableTransactions,
1337
+ },
1338
+ this.log.getBindings(),
1339
+ );
1201
1340
 
1202
1341
  return await validator.validateTx(tx);
1203
1342
  }
@@ -1266,7 +1405,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1266
1405
  }
1267
1406
 
1268
1407
  // And it has an L2 block hash
1269
- const l2BlockHash = await archiver.getL2Tips().then(tips => tips.latest.hash);
1408
+ const l2BlockHash = await archiver.getL2Tips().then(tips => tips.proposed.hash);
1270
1409
  if (!l2BlockHash) {
1271
1410
  this.metrics.recordSnapshotError();
1272
1411
  throw new Error(`Archiver has no latest L2 block hash downloaded. Cannot start snapshot.`);
@@ -1294,13 +1433,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1294
1433
  return Promise.resolve();
1295
1434
  }
1296
1435
 
1297
- public async rollbackTo(targetBlock: number, force?: boolean): Promise<void> {
1436
+ public async rollbackTo(targetBlock: BlockNumber, force?: boolean): Promise<void> {
1298
1437
  const archiver = this.blockSource as Archiver;
1299
1438
  if (!('rollbackTo' in archiver)) {
1300
1439
  throw new Error('Archiver implementation does not support rollbacks.');
1301
1440
  }
1302
1441
 
1303
- const finalizedBlock = await archiver.getL2Tips().then(tips => tips.finalized.number);
1442
+ const finalizedBlock = await archiver.getL2Tips().then(tips => tips.finalized.block.number);
1304
1443
  if (targetBlock < finalizedBlock) {
1305
1444
  if (force) {
1306
1445
  this.log.warn(`Clearing world state database to allow rolling back behind finalized block ${finalizedBlock}`);
@@ -1361,17 +1500,108 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1361
1500
  }
1362
1501
  }
1363
1502
 
1503
+ public async reloadKeystore(): Promise<void> {
1504
+ if (!this.config.keyStoreDirectory?.length) {
1505
+ throw new BadRequestError(
1506
+ 'Cannot reload keystore: node is not using a file-based keystore. ' +
1507
+ 'Set KEY_STORE_DIRECTORY to use file-based keystores.',
1508
+ );
1509
+ }
1510
+ if (!this.validatorClient) {
1511
+ throw new BadRequestError('Cannot reload keystore: validator is not enabled.');
1512
+ }
1513
+
1514
+ this.log.info('Reloading keystore from disk');
1515
+
1516
+ // Re-read and validate keystore files
1517
+ const keyStores = loadKeystores(this.config.keyStoreDirectory);
1518
+ const newManager = new KeystoreManager(mergeKeystores(keyStores));
1519
+ await newManager.validateSigners();
1520
+ ValidatorClient.validateKeyStoreConfiguration(newManager, this.log);
1521
+
1522
+ // Validate that every validator's publisher keys overlap with the L1 signers
1523
+ // that were initialized at startup. Publishers cannot be hot-reloaded, so a
1524
+ // validator with a publisher key that doesn't match any existing L1 signer
1525
+ // would silently fail on every proposer slot.
1526
+ if (this.keyStoreManager && this.sequencer) {
1527
+ const oldAdapter = NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager);
1528
+ const availablePublishers = new Set(
1529
+ oldAdapter
1530
+ .getAttesterAddresses()
1531
+ .flatMap(a => oldAdapter.getPublisherAddresses(a).map(p => p.toString().toLowerCase())),
1532
+ );
1533
+
1534
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
1535
+ for (const attester of newAdapter.getAttesterAddresses()) {
1536
+ const pubs = newAdapter.getPublisherAddresses(attester);
1537
+ if (pubs.length > 0 && !pubs.some(p => availablePublishers.has(p.toString().toLowerCase()))) {
1538
+ throw new BadRequestError(
1539
+ `Cannot reload keystore: validator ${attester} has publisher keys ` +
1540
+ `[${pubs.map(p => p.toString()).join(', ')}] but none match the L1 signers initialized at startup ` +
1541
+ `[${[...availablePublishers].join(', ')}]. Publishers cannot be hot-reloaded — ` +
1542
+ `use an existing publisher key or restart the node.`,
1543
+ );
1544
+ }
1545
+ }
1546
+ }
1547
+
1548
+ // Build adapters for old and new keystores to compute diff
1549
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
1550
+ const newAddresses = newAdapter.getAttesterAddresses();
1551
+ const oldAddresses = this.keyStoreManager
1552
+ ? NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager).getAttesterAddresses()
1553
+ : [];
1554
+
1555
+ const oldSet = new Set(oldAddresses.map(a => a.toString()));
1556
+ const newSet = new Set(newAddresses.map(a => a.toString()));
1557
+ const added = newAddresses.filter(a => !oldSet.has(a.toString()));
1558
+ const removed = oldAddresses.filter(a => !newSet.has(a.toString()));
1559
+
1560
+ if (added.length > 0) {
1561
+ this.log.info(`Keystore reload: adding attester keys: ${added.map(a => a.toString()).join(', ')}`);
1562
+ }
1563
+ if (removed.length > 0) {
1564
+ this.log.info(`Keystore reload: removing attester keys: ${removed.map(a => a.toString()).join(', ')}`);
1565
+ }
1566
+ if (added.length === 0 && removed.length === 0) {
1567
+ this.log.info('Keystore reload: attester keys unchanged');
1568
+ }
1569
+
1570
+ // Update the validator client (coinbase, feeRecipient, attester keys)
1571
+ this.validatorClient.reloadKeystore(newManager);
1572
+
1573
+ // Update the publisher factory's keystore so newly-added validators
1574
+ // can be matched to existing publisher keys when proposing blocks.
1575
+ if (this.sequencer) {
1576
+ this.sequencer.updatePublisherNodeKeyStore(newAdapter);
1577
+ }
1578
+
1579
+ // Update slasher's "don't-slash-self" list with new validator addresses
1580
+ if (this.slasherClient && !this.config.slashSelfAllowed) {
1581
+ const slashValidatorsNever = unique(
1582
+ [...(this.config.slashValidatorsNever ?? []), ...newAddresses].map(a => a.toString()),
1583
+ ).map(EthAddress.fromString);
1584
+ this.slasherClient.updateConfig({ slashValidatorsNever });
1585
+ }
1586
+
1587
+ this.keyStoreManager = newManager;
1588
+ this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1589
+ }
1590
+
1591
+ #getInitialHeaderHash(): Promise<BlockHash> {
1592
+ if (!this.initialHeaderHashPromise) {
1593
+ this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
1594
+ }
1595
+ return this.initialHeaderHashPromise;
1596
+ }
1597
+
1364
1598
  /**
1365
1599
  * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1366
- * @param blockNumber - The block number at which to get the data.
1600
+ * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1367
1601
  * @returns An instance of a committed MerkleTreeOperations
1368
1602
  */
1369
- async #getWorldState(blockNumber: L2BlockNumber) {
1370
- if (typeof blockNumber === 'number' && blockNumber < INITIAL_L2_BLOCK_NUM - 1) {
1371
- throw new Error('Invalid block number to get world state for: ' + blockNumber);
1372
- }
1373
-
1374
- let blockSyncedTo: number = 0;
1603
+ async #getWorldState(block: BlockParameter) {
1604
+ let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1375
1605
  try {
1376
1606
  // Attempt to sync the world state if necessary
1377
1607
  blockSyncedTo = await this.#syncWorldState();
@@ -1379,15 +1609,39 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1379
1609
  this.log.error(`Error getting world state: ${err}`);
1380
1610
  }
1381
1611
 
1382
- // using a snapshot could be less efficient than using the committed db
1383
- if (blockNumber === 'latest' /*|| blockNumber === blockSyncedTo*/) {
1384
- this.log.debug(`Using committed db for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1612
+ if (block === 'latest') {
1613
+ this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
1385
1614
  return this.worldStateSynchronizer.getCommitted();
1386
- } else if (blockNumber <= blockSyncedTo) {
1615
+ }
1616
+
1617
+ if (BlockHash.isBlockHash(block)) {
1618
+ const initialBlockHash = await this.#getInitialHeaderHash();
1619
+ if (block.equals(initialBlockHash)) {
1620
+ // Block source doesn't handle initial header so we need to handle the case separately.
1621
+ return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1622
+ }
1623
+
1624
+ const header = await this.blockSource.getBlockHeaderByHash(block);
1625
+ if (!header) {
1626
+ throw new Error(
1627
+ `Block hash ${block.toString()} not found when querying world state. If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
1628
+ );
1629
+ }
1630
+ const blockNumber = header.getBlockNumber();
1631
+ this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1632
+ return this.worldStateSynchronizer.getSnapshot(blockNumber);
1633
+ }
1634
+
1635
+ // Block number provided
1636
+ {
1637
+ const blockNumber = block as BlockNumber;
1638
+
1639
+ if (blockNumber > blockSyncedTo) {
1640
+ throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1641
+ }
1642
+
1387
1643
  this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1388
1644
  return this.worldStateSynchronizer.getSnapshot(blockNumber);
1389
- } else {
1390
- throw new Error(`Block ${blockNumber} not yet synced`);
1391
1645
  }
1392
1646
  }
1393
1647
 
@@ -1395,8 +1649,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1395
1649
  * Ensure we fully sync the world state
1396
1650
  * @returns A promise that fulfils once the world state is synced
1397
1651
  */
1398
- async #syncWorldState(): Promise<number> {
1652
+ async #syncWorldState(): Promise<BlockNumber> {
1399
1653
  const blockSourceHeight = await this.blockSource.getBlockNumber();
1400
- return this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
1654
+ return await this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
1401
1655
  }
1402
1656
  }