@aztec/aztec-node 0.0.1-commit.6d3c34e → 0.0.1-commit.7035c9bd6

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,21 +1,15 @@
1
1
  import { Archiver, createArchiver } from '@aztec/archiver';
2
2
  import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
3
3
  import { type BlobClientInterface, createBlobClientWithFileStores } from '@aztec/blob-client/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';
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
7
  import { createEthereumChain } from '@aztec/ethereum/chain';
14
- import { getPublicClient } from '@aztec/ethereum/client';
8
+ import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
15
9
  import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
16
10
  import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
17
11
  import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
18
- import { compactArray, pick } from '@aztec/foundation/collection';
12
+ import { chunkBy, compactArray, pick, unique } from '@aztec/foundation/collection';
19
13
  import { Fr } from '@aztec/foundation/curves/bn254';
20
14
  import { EthAddress } from '@aztec/foundation/eth-address';
21
15
  import { BadRequestError } from '@aztec/foundation/json-rpc';
@@ -23,15 +17,20 @@ import { type Logger, createLogger } from '@aztec/foundation/log';
23
17
  import { count } from '@aztec/foundation/string';
24
18
  import { DateProvider, Timer } from '@aztec/foundation/timer';
25
19
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
26
- import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
20
+ import { type KeyStore, KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
27
21
  import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
22
+ import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
28
23
  import {
29
- createForwarderL1TxUtilsFromEthSigner,
30
- createL1TxUtilsWithBlobsFromEthSigner,
31
- } from '@aztec/node-lib/factories';
32
- import { type P2P, type P2PClientDeps, createP2PClient, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
24
+ type P2P,
25
+ type P2PClientDeps,
26
+ createP2PClient,
27
+ createTxValidatorForAcceptingTxsOverRPC,
28
+ getDefaultAllowedSetupFunctions,
29
+ } from '@aztec/p2p';
33
30
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
34
- import { BlockBuilder, GlobalVariableBuilder, SequencerClient, type SequencerPublisher } from '@aztec/sequencer-client';
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';
35
34
  import { PublicProcessorFactory } from '@aztec/simulator/server';
36
35
  import {
37
36
  AttestationsBlockWatcher,
@@ -43,13 +42,12 @@ import {
43
42
  import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
44
43
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
45
44
  import {
45
+ type BlockData,
46
+ BlockHash,
46
47
  type BlockParameter,
47
48
  type DataInBlock,
48
- type L2Block,
49
- L2BlockHash,
50
- L2BlockNew,
49
+ L2Block,
51
50
  type L2BlockSource,
52
- type PublishedL2Block,
53
51
  } from '@aztec/stdlib/block';
54
52
  import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
55
53
  import type {
@@ -78,9 +76,9 @@ import {
78
76
  type WorldStateSynchronizer,
79
77
  tryStop,
80
78
  } from '@aztec/stdlib/interfaces/server';
81
- import type { LogFilter, SiloedTag, Tag, 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';
82
81
  import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
83
- import { P2PClientType } from '@aztec/stdlib/p2p';
84
82
  import type { Offense, SlashPayloadRound } from '@aztec/stdlib/slashing';
85
83
  import type { NullifierLeafPreimage, PublicDataTreeLeaf, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
86
84
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
@@ -112,11 +110,11 @@ import {
112
110
  ValidatorClient,
113
111
  createBlockProposalHandler,
114
112
  createValidatorClient,
115
- createValidatorForAcceptingTxs,
116
113
  } from '@aztec/validator-client';
114
+ import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
117
115
  import { createWorldStateSynchronizer } from '@aztec/world-state';
118
116
 
119
- import { createPublicClient, fallback, http } from 'viem';
117
+ import { createPublicClient } from 'viem';
120
118
 
121
119
  import { createSentinel } from '../sentinel/factory.js';
122
120
  import { Sentinel } from '../sentinel/sentinel.js';
@@ -128,6 +126,7 @@ import { NodeMetrics } from './node_metrics.js';
128
126
  */
129
127
  export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
130
128
  private metrics: NodeMetrics;
129
+ private initialHeaderHashPromise: Promise<BlockHash> | undefined = undefined;
131
130
 
132
131
  // Prevent two snapshot operations to happen simultaneously
133
132
  private isUploadingSnapshot = false;
@@ -143,6 +142,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
143
142
  protected readonly l1ToL2MessageSource: L1ToL2MessageSource,
144
143
  protected readonly worldStateSynchronizer: WorldStateSynchronizer,
145
144
  protected readonly sequencer: SequencerClient | undefined,
145
+ protected readonly proverNode: ProverNode | undefined,
146
146
  protected readonly slasherClient: SlasherClientInterface | undefined,
147
147
  protected readonly validatorsSentinel: Sentinel | undefined,
148
148
  protected readonly epochPruneWatcher: EpochPruneWatcher | undefined,
@@ -155,12 +155,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
155
155
  private telemetry: TelemetryClient = getTelemetryClient(),
156
156
  private log = createLogger('node'),
157
157
  private blobClient?: BlobClientInterface,
158
+ private validatorClient?: ValidatorClient,
159
+ private keyStoreManager?: KeystoreManager,
160
+ private debugLogStore: DebugLogStore = new NullDebugLogStore(),
158
161
  ) {
159
162
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
160
163
  this.tracer = telemetry.getTracer('AztecNodeService');
161
164
 
162
165
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
163
166
  this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
167
+
168
+ // A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
169
+ // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
170
+ // memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
171
+ if (debugLogStore.isEnabled && config.realProofs) {
172
+ throw new Error('debugLogStore should never be enabled when realProofs are set');
173
+ }
164
174
  }
165
175
 
166
176
  public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
@@ -184,11 +194,14 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
184
194
  logger?: Logger;
185
195
  publisher?: SequencerPublisher;
186
196
  dateProvider?: DateProvider;
187
- p2pClientDeps?: P2PClientDeps<P2PClientType.Full>;
197
+ p2pClientDeps?: P2PClientDeps;
198
+ proverNodeDeps?: Partial<ProverNodeDeps>;
199
+ slashingProtectionDb?: SlashingProtectionDatabase;
188
200
  } = {},
189
201
  options: {
190
202
  prefilledPublicData?: PublicDataTreeLeaf[];
191
203
  dontStartSequencer?: boolean;
204
+ dontStartProverNode?: boolean;
192
205
  } = {},
193
206
  ): Promise<AztecNodeService> {
194
207
  const config = { ...inputConfig }; // Copy the config so we dont mutate the input object
@@ -198,16 +211,29 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
198
211
  const dateProvider = deps.dateProvider ?? new DateProvider();
199
212
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
200
213
 
201
- // Build a key store from file if given or from environment otherwise
214
+ // Build a key store from file if given or from environment otherwise.
215
+ // We keep the raw KeyStore available so we can merge with prover keys if enableProverNode is set.
202
216
  let keyStoreManager: KeystoreManager | undefined;
203
217
  const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
204
218
  if (keyStoreProvided) {
205
219
  const keyStores = loadKeystores(config.keyStoreDirectory!);
206
220
  keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
207
221
  } else {
208
- const keyStore = createKeyStoreForValidator(config);
209
- if (keyStore) {
210
- keyStoreManager = new KeystoreManager(keyStore);
222
+ const rawKeyStores: KeyStore[] = [];
223
+ const validatorKeyStore = createKeyStoreForValidator(config);
224
+ if (validatorKeyStore) {
225
+ rawKeyStores.push(validatorKeyStore);
226
+ }
227
+ if (config.enableProverNode) {
228
+ const proverKeyStore = createKeyStoreForProver(config);
229
+ if (proverKeyStore) {
230
+ rawKeyStores.push(proverKeyStore);
231
+ }
232
+ }
233
+ if (rawKeyStores.length > 0) {
234
+ keyStoreManager = new KeystoreManager(
235
+ rawKeyStores.length === 1 ? rawKeyStores[0] : mergeKeystores(rawKeyStores),
236
+ );
211
237
  }
212
238
  }
213
239
 
@@ -218,10 +244,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
218
244
  if (keyStoreManager === undefined) {
219
245
  throw new Error('Failed to create key store, a requirement for running a validator');
220
246
  }
221
- if (!keyStoreProvided) {
222
- log.warn(
223
- 'KEY STORE CREATED FROM ENVIRONMENT, IT IS RECOMMENDED TO USE A FILE-BASED KEY STORE IN PRODUCTION ENVIRONMENTS',
224
- );
247
+ if (!keyStoreProvided && process.env.NODE_ENV !== 'test') {
248
+ log.warn("Keystore created from env: it's recommended to use a file-based key store for production");
225
249
  }
226
250
  ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
227
251
  }
@@ -235,7 +259,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
235
259
 
236
260
  const publicClient = createPublicClient({
237
261
  chain: ethereumChain.chainInfo,
238
- transport: fallback(config.l1RpcUrls.map((url: string) => http(url, { batch: false }))),
262
+ transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
239
263
  pollingInterval: config.viemPollingIntervalMS,
240
264
  });
241
265
 
@@ -249,10 +273,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
249
273
  config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
250
274
 
251
275
  const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
252
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
276
+ const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
253
277
  rollupContract.getL1GenesisTime(),
254
278
  rollupContract.getSlotDuration(),
255
279
  rollupContract.getVersion(),
280
+ rollupContract.getManaLimit().then(Number),
256
281
  ] as const);
257
282
 
258
283
  config.rollupVersion ??= Number(rollupVersionFromRollup);
@@ -263,7 +288,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
263
288
  );
264
289
  }
265
290
 
266
- const blobClient = await createBlobClientWithFileStores(config, createLogger('node:blob-client:client'));
291
+ const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
267
292
 
268
293
  // attempt snapshot sync if possible
269
294
  await trySnapshotSync(config, log);
@@ -287,14 +312,28 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
287
312
  config.realProofs || config.debugForceTxProofVerification
288
313
  ? await BBCircuitVerifier.new(config)
289
314
  : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
315
+
316
+ let debugLogStore: DebugLogStore;
290
317
  if (!config.realProofs) {
291
318
  log.warn(`Aztec node is accepting fake proofs`);
319
+
320
+ debugLogStore = new InMemoryDebugLogStore();
321
+ log.info(
322
+ 'Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served',
323
+ );
324
+ } else {
325
+ debugLogStore = new NullDebugLogStore();
292
326
  }
327
+
293
328
  const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
294
329
 
330
+ const proverOnly = config.enableProverNode && config.disableValidator;
331
+ if (proverOnly) {
332
+ log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
333
+ }
334
+
295
335
  // create the tx pool and the p2p client, which will need the l2 block source
296
336
  const p2pClient = await createP2PClient(
297
- P2PClientType.Full,
298
337
  config,
299
338
  archiver,
300
339
  proofVerifier,
@@ -306,57 +345,60 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
306
345
  deps.p2pClientDeps,
307
346
  );
308
347
 
309
- // We should really not be modifying the config object
310
- config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
311
-
312
- // Create BlockBuilder for EpochPruneWatcher (slasher functionality)
313
- const blockBuilder = new BlockBuilder(
314
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
315
- worldStateSynchronizer,
316
- archiver,
317
- dateProvider,
318
- telemetry,
319
- );
348
+ // We'll accumulate sentinel watchers here
349
+ const watchers: Watcher[] = [];
320
350
 
321
- // Create FullNodeCheckpointsBuilder for validator and non-validator block proposal handling
351
+ // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
352
+ // Override maxTxsPerCheckpoint with the validator-specific limit if set.
322
353
  const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
323
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
354
+ {
355
+ ...config,
356
+ l1GenesisTime,
357
+ slotDuration: Number(slotDuration),
358
+ rollupManaLimit,
359
+ maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint,
360
+ },
361
+ worldStateSynchronizer,
324
362
  archiver,
325
363
  dateProvider,
326
364
  telemetry,
327
365
  );
328
366
 
329
- // We'll accumulate sentinel watchers here
330
- const watchers: Watcher[] = [];
367
+ let validatorClient: ValidatorClient | undefined;
331
368
 
332
- // Create validator client if required
333
- const validatorClient = createValidatorClient(config, {
334
- checkpointsBuilder: validatorCheckpointsBuilder,
335
- worldState: worldStateSynchronizer,
336
- p2pClient,
337
- telemetry,
338
- dateProvider,
339
- epochCache,
340
- blockSource: archiver,
341
- l1ToL2MessageSource: archiver,
342
- keyStoreManager,
343
- blobClient,
344
- });
369
+ if (!proverOnly) {
370
+ // Create validator client if required
371
+ validatorClient = await createValidatorClient(config, {
372
+ checkpointsBuilder: validatorCheckpointsBuilder,
373
+ worldState: worldStateSynchronizer,
374
+ p2pClient,
375
+ telemetry,
376
+ dateProvider,
377
+ epochCache,
378
+ blockSource: archiver,
379
+ l1ToL2MessageSource: archiver,
380
+ keyStoreManager,
381
+ blobClient,
382
+ slashingProtectionDb: deps.slashingProtectionDb,
383
+ });
345
384
 
346
- // If we have a validator client, register it as a source of offenses for the slasher,
347
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
348
- // like attestations or auths will fail.
349
- if (validatorClient) {
350
- watchers.push(validatorClient);
351
- if (!options.dontStartSequencer) {
352
- await validatorClient.registerHandlers();
385
+ // If we have a validator client, register it as a source of offenses for the slasher,
386
+ // and have it register callbacks on the p2p client *before* we start it, otherwise messages
387
+ // like attestations or auths will fail.
388
+ if (validatorClient) {
389
+ watchers.push(validatorClient);
390
+ if (!options.dontStartSequencer) {
391
+ await validatorClient.registerHandlers();
392
+ }
353
393
  }
354
394
  }
355
395
 
356
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
357
- // create a BlockProposalHandler to reexecute block proposals for monitoring
358
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
359
- log.info('Setting up block proposal reexecution for monitoring');
396
+ // If there's no validator client, create a BlockProposalHandler to handle block proposals
397
+ // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
398
+ // while non-reexecution is used for validating the proposals and collecting their txs.
399
+ if (!validatorClient) {
400
+ const reexecute = !!config.alwaysReexecuteBlockProposals;
401
+ log.info(`Setting up block proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
360
402
  createBlockProposalHandler(config, {
361
403
  checkpointsBuilder: validatorCheckpointsBuilder,
362
404
  worldState: worldStateSynchronizer,
@@ -366,7 +408,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
366
408
  p2pClient,
367
409
  dateProvider,
368
410
  telemetry,
369
- }).registerForReexecution(p2pClient);
411
+ }).register(p2pClient, reexecute);
370
412
  }
371
413
 
372
414
  // Start world state and wait for it to sync to the archiver.
@@ -375,29 +417,33 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
375
417
  // Start p2p. Note that it depends on world state to be running.
376
418
  await p2pClient.start();
377
419
 
378
- const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
379
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
380
- watchers.push(validatorsSentinel);
381
- }
382
-
420
+ let validatorsSentinel: Awaited<ReturnType<typeof createSentinel>> | undefined;
383
421
  let epochPruneWatcher: EpochPruneWatcher | undefined;
384
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
385
- epochPruneWatcher = new EpochPruneWatcher(
386
- archiver,
387
- archiver,
388
- epochCache,
389
- p2pClient.getTxProvider(),
390
- blockBuilder,
391
- config,
392
- );
393
- watchers.push(epochPruneWatcher);
394
- }
395
-
396
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
397
422
  let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
398
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
399
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
400
- watchers.push(attestationsBlockWatcher);
423
+
424
+ if (!proverOnly) {
425
+ validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
426
+ if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
427
+ watchers.push(validatorsSentinel);
428
+ }
429
+
430
+ if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
431
+ epochPruneWatcher = new EpochPruneWatcher(
432
+ archiver,
433
+ archiver,
434
+ epochCache,
435
+ p2pClient.getTxProvider(),
436
+ validatorCheckpointsBuilder,
437
+ config,
438
+ );
439
+ watchers.push(epochPruneWatcher);
440
+ }
441
+
442
+ // We assume we want to slash for invalid attestations unless all max penalties are set to 0
443
+ if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
444
+ attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
445
+ watchers.push(attestationsBlockWatcher);
446
+ }
401
447
  }
402
448
 
403
449
  // Start p2p-related services once the archiver has completed sync
@@ -434,27 +480,29 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
434
480
  );
435
481
  await slasherClient.start();
436
482
 
437
- const l1TxUtils = config.publisherForwarderAddress
438
- ? await createForwarderL1TxUtilsFromEthSigner(
483
+ const l1TxUtils = config.sequencerPublisherForwarderAddress
484
+ ? await createForwarderL1TxUtilsFromSigners(
439
485
  publicClient,
440
486
  keyStoreManager!.createAllValidatorPublisherSigners(),
441
- config.publisherForwarderAddress,
487
+ config.sequencerPublisherForwarderAddress,
442
488
  { ...config, scope: 'sequencer' },
443
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider },
489
+ { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
444
490
  )
445
- : await createL1TxUtilsWithBlobsFromEthSigner(
491
+ : await createL1TxUtilsFromSigners(
446
492
  publicClient,
447
493
  keyStoreManager!.createAllValidatorPublisherSigners(),
448
494
  { ...config, scope: 'sequencer' },
449
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider },
495
+ { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
450
496
  );
451
497
 
452
498
  // Create and start the sequencer client
453
499
  const checkpointsBuilder = new CheckpointsBuilder(
454
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
500
+ { ...config, l1GenesisTime, slotDuration: Number(slotDuration), rollupManaLimit },
501
+ worldStateSynchronizer,
455
502
  archiver,
456
503
  dateProvider,
457
504
  telemetry,
505
+ debugLogStore,
458
506
  );
459
507
 
460
508
  sequencer = await SequencerClient.new(config, {
@@ -482,6 +530,29 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
482
530
  log.warn(`Sequencer created but not started`);
483
531
  }
484
532
 
533
+ // Create prover node subsystem if enabled
534
+ let proverNode: ProverNode | undefined;
535
+ if (config.enableProverNode) {
536
+ proverNode = await createProverNode(config, {
537
+ ...deps.proverNodeDeps,
538
+ telemetry,
539
+ dateProvider,
540
+ archiver,
541
+ worldStateSynchronizer,
542
+ p2pClient,
543
+ epochCache,
544
+ blobClient,
545
+ keyStoreManager,
546
+ });
547
+
548
+ if (!options.dontStartProverNode) {
549
+ await proverNode.start();
550
+ log.info(`Prover node subsystem started`);
551
+ } else {
552
+ log.info(`Prover node subsystem created but not started`);
553
+ }
554
+ }
555
+
485
556
  const globalVariableBuilder = new GlobalVariableBuilder({
486
557
  ...config,
487
558
  rollupVersion: BigInt(config.rollupVersion),
@@ -489,7 +560,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
489
560
  slotDuration: Number(slotDuration),
490
561
  });
491
562
 
492
- return new AztecNodeService(
563
+ const node = new AztecNodeService(
493
564
  config,
494
565
  p2pClient,
495
566
  archiver,
@@ -498,6 +569,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
498
569
  archiver,
499
570
  worldStateSynchronizer,
500
571
  sequencer,
572
+ proverNode,
501
573
  slasherClient,
502
574
  validatorsSentinel,
503
575
  epochPruneWatcher,
@@ -510,7 +582,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
510
582
  telemetry,
511
583
  log,
512
584
  blobClient,
585
+ validatorClient,
586
+ keyStoreManager,
587
+ debugLogStore,
513
588
  );
589
+
590
+ return node;
514
591
  }
515
592
 
516
593
  /**
@@ -521,6 +598,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
521
598
  return this.sequencer;
522
599
  }
523
600
 
601
+ /** Returns the prover node subsystem, if enabled. */
602
+ public getProverNode(): ProverNode | undefined {
603
+ return this.proverNode;
604
+ }
605
+
524
606
  public getBlockSource(): L2BlockSource {
525
607
  return this.blockSource;
526
608
  }
@@ -546,7 +628,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
546
628
  }
547
629
 
548
630
  public async getAllowedPublicSetup(): Promise<AllowedElement[]> {
549
- return this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
631
+ return [...(await getDefaultAllowedSetupFunctions()), ...(this.config.txPublicSetupAllowListExtend ?? [])];
550
632
  }
551
633
 
552
634
  /**
@@ -574,19 +656,26 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
574
656
  enr,
575
657
  l1ContractAddresses: contractAddresses,
576
658
  protocolContractAddresses: protocolContractAddresses,
659
+ realProofs: !!this.config.realProofs,
577
660
  };
578
661
 
579
662
  return nodeInfo;
580
663
  }
581
664
 
582
665
  /**
583
- * Get a block specified by its number.
584
- * @param number - The block number being requested.
666
+ * Get a block specified by its block number, block hash, or 'latest'.
667
+ * @param block - The block parameter (block number, block hash, or 'latest').
585
668
  * @returns The requested block.
586
669
  */
587
- public async getBlock(number: BlockParameter): Promise<L2Block | undefined> {
588
- const blockNumber = number === 'latest' ? await this.getBlockNumber() : (number as BlockNumber);
589
- return await this.blockSource.getBlock(blockNumber);
670
+ public async getBlock(block: BlockParameter): Promise<L2Block | undefined> {
671
+ if (BlockHash.isBlockHash(block)) {
672
+ return this.getBlockByHash(block);
673
+ }
674
+ const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
675
+ if (blockNumber === BlockNumber.ZERO) {
676
+ return this.buildInitialBlock();
677
+ }
678
+ return await this.blockSource.getL2Block(blockNumber);
590
679
  }
591
680
 
592
681
  /**
@@ -594,9 +683,17 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
594
683
  * @param blockHash - The block hash being requested.
595
684
  * @returns The requested block.
596
685
  */
597
- public async getBlockByHash(blockHash: Fr): Promise<L2Block | undefined> {
598
- const publishedBlock = await this.blockSource.getPublishedBlockByHash(blockHash);
599
- return publishedBlock?.block;
686
+ public async getBlockByHash(blockHash: BlockHash): Promise<L2Block | undefined> {
687
+ const initialBlockHash = await this.#getInitialHeaderHash();
688
+ if (blockHash.equals(initialBlockHash)) {
689
+ return this.buildInitialBlock();
690
+ }
691
+ return await this.blockSource.getL2BlockByHash(blockHash);
692
+ }
693
+
694
+ private buildInitialBlock(): L2Block {
695
+ const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
696
+ return L2Block.empty(initialHeader);
600
697
  }
601
698
 
602
699
  /**
@@ -605,8 +702,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
605
702
  * @returns The requested block.
606
703
  */
607
704
  public async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
608
- const publishedBlock = await this.blockSource.getPublishedBlockByArchive(archive);
609
- return publishedBlock?.block;
705
+ return await this.blockSource.getL2BlockByArchive(archive);
610
706
  }
611
707
 
612
708
  /**
@@ -616,23 +712,19 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
616
712
  * @returns The blocks requested.
617
713
  */
618
714
  public async getBlocks(from: BlockNumber, limit: number): Promise<L2Block[]> {
619
- return (await this.blockSource.getBlocks(from, limit)) ?? [];
620
- }
621
-
622
- public async getPublishedBlocks(from: BlockNumber, limit: number): Promise<PublishedL2Block[]> {
623
- return (await this.blockSource.getPublishedBlocks(from, limit)) ?? [];
715
+ return (await this.blockSource.getBlocks(from, BlockNumber(limit))) ?? [];
624
716
  }
625
717
 
626
- public async getPublishedCheckpoints(from: CheckpointNumber, limit: number): Promise<PublishedCheckpoint[]> {
627
- return (await this.blockSource.getPublishedCheckpoints(from, limit)) ?? [];
718
+ public async getCheckpoints(from: CheckpointNumber, limit: number): Promise<PublishedCheckpoint[]> {
719
+ return (await this.blockSource.getCheckpoints(from, limit)) ?? [];
628
720
  }
629
721
 
630
- public async getL2BlocksNew(from: BlockNumber, limit: number): Promise<L2BlockNew[]> {
631
- return (await this.blockSource.getL2BlocksNew(from, limit)) ?? [];
722
+ public async getCheckpointedBlocks(from: BlockNumber, limit: number) {
723
+ return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
632
724
  }
633
725
 
634
- public async getCheckpointedBlocks(from: BlockNumber, limit: number, proven?: boolean) {
635
- return (await this.blockSource.getCheckpointedBlocks(from, limit, proven)) ?? [];
726
+ public getCheckpointsDataForEpoch(epochNumber: EpochNumber) {
727
+ return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
636
728
  }
637
729
 
638
730
  /**
@@ -663,6 +755,14 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
663
755
  return await this.blockSource.getProvenBlockNumber();
664
756
  }
665
757
 
758
+ public async getCheckpointedBlockNumber(): Promise<BlockNumber> {
759
+ return await this.blockSource.getCheckpointedL2BlockNumber();
760
+ }
761
+
762
+ public getCheckpointNumber(): Promise<CheckpointNumber> {
763
+ return this.blockSource.getCheckpointNumber();
764
+ }
765
+
666
766
  /**
667
767
  * Method to fetch the version of the package.
668
768
  * @returns The node package version
@@ -695,12 +795,51 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
695
795
  return this.contractDataSource.getContract(address);
696
796
  }
697
797
 
698
- public getPrivateLogsByTags(tags: SiloedTag[]): Promise<TxScopedL2Log[][]> {
699
- return this.logsSource.getPrivateLogsByTags(tags);
700
- }
701
-
702
- public getPublicLogsByTagsFromContract(contractAddress: AztecAddress, tags: Tag[]): Promise<TxScopedL2Log[][]> {
703
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags);
798
+ public async getPrivateLogsByTags(
799
+ tags: SiloedTag[],
800
+ page?: number,
801
+ referenceBlock?: BlockHash,
802
+ ): Promise<TxScopedL2Log[][]> {
803
+ let upToBlockNumber: BlockNumber | undefined;
804
+ if (referenceBlock) {
805
+ const initialBlockHash = await this.#getInitialHeaderHash();
806
+ if (referenceBlock.equals(initialBlockHash)) {
807
+ upToBlockNumber = BlockNumber(0);
808
+ } else {
809
+ const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
810
+ if (!header) {
811
+ throw new Error(
812
+ `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
813
+ );
814
+ }
815
+ upToBlockNumber = header.globalVariables.blockNumber;
816
+ }
817
+ }
818
+ return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
819
+ }
820
+
821
+ public async getPublicLogsByTagsFromContract(
822
+ contractAddress: AztecAddress,
823
+ tags: Tag[],
824
+ page?: number,
825
+ referenceBlock?: BlockHash,
826
+ ): Promise<TxScopedL2Log[][]> {
827
+ let upToBlockNumber: BlockNumber | undefined;
828
+ if (referenceBlock) {
829
+ const initialBlockHash = await this.#getInitialHeaderHash();
830
+ if (referenceBlock.equals(initialBlockHash)) {
831
+ upToBlockNumber = BlockNumber(0);
832
+ } else {
833
+ const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
834
+ if (!header) {
835
+ throw new Error(
836
+ `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
837
+ );
838
+ }
839
+ upToBlockNumber = header.globalVariables.blockNumber;
840
+ }
841
+ }
842
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
704
843
  }
705
844
 
706
845
  /**
@@ -742,26 +881,36 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
742
881
  }
743
882
 
744
883
  await this.p2pClient!.sendTx(tx);
745
- this.metrics.receivedTx(timer.ms(), true);
746
- this.log.info(`Received tx ${txHash}`, { txHash });
884
+ const duration = timer.ms();
885
+ this.metrics.receivedTx(duration, true);
886
+ this.log.info(`Received tx ${txHash} in ${duration}ms`, { txHash });
747
887
  }
748
888
 
749
889
  public async getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
750
- let txReceipt = new TxReceipt(txHash, TxStatus.DROPPED, 'Tx dropped by P2P node.');
751
-
752
- // We first check if the tx is in pending (instead of first checking if it is mined) because if we first check
753
- // for mined and then for pending there could be a race condition where the tx is mined between the two checks
754
- // and we would incorrectly return a TxReceipt with status DROPPED
755
- if ((await this.p2pClient.getTxStatus(txHash)) === 'pending') {
756
- txReceipt = new TxReceipt(txHash, TxStatus.PENDING, '');
757
- }
890
+ // Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
891
+ // as a fallback if we don't find a settled receipt in the archiver.
892
+ const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
893
+ const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
758
894
 
895
+ // Then get the actual tx from the archiver, which tracks every tx in a mined block.
759
896
  const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
897
+
898
+ let receipt: TxReceipt;
760
899
  if (settledTxReceipt) {
761
- txReceipt = settledTxReceipt;
900
+ receipt = settledTxReceipt;
901
+ } else if (isKnownToPool) {
902
+ // If the tx is in the pool but not in the archiver, it's pending.
903
+ // This handles race conditions between archiver and p2p, where the archiver
904
+ // has pruned the block in which a tx was mined, but p2p has not caught up yet.
905
+ receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
906
+ } else {
907
+ // Otherwise, if we don't know the tx, we consider it dropped.
908
+ receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
762
909
  }
763
910
 
764
- return txReceipt;
911
+ this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
912
+
913
+ return receipt;
765
914
  }
766
915
 
767
916
  public getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined> {
@@ -778,6 +927,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
778
927
  await tryStop(this.slasherClient);
779
928
  await tryStop(this.proofVerifier);
780
929
  await tryStop(this.sequencer);
930
+ await tryStop(this.proverNode);
781
931
  await tryStop(this.p2pClient);
782
932
  await tryStop(this.worldStateSynchronizer);
783
933
  await tryStop(this.blockSource);
@@ -826,121 +976,95 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
826
976
  return compactArray(await Promise.all(txHashes.map(txHash => this.getTxByHash(txHash))));
827
977
  }
828
978
 
829
- /**
830
- * Find the indexes of the given leaves in the given tree along with a block metadata pointing to the block in which
831
- * the leaves were inserted.
832
- * @param blockNumber - The block number at which to get the data or 'latest' for latest data.
833
- * @param treeId - The tree to search in.
834
- * @param leafValues - The values to search for.
835
- * @returns The indices of leaves and the block metadata of a block in which the leaves were inserted.
836
- */
837
979
  public async findLeavesIndexes(
838
- blockNumber: BlockParameter,
980
+ referenceBlock: BlockParameter,
839
981
  treeId: MerkleTreeId,
840
982
  leafValues: Fr[],
841
983
  ): Promise<(DataInBlock<bigint> | undefined)[]> {
842
- const committedDb = await this.#getWorldState(blockNumber);
984
+ const committedDb = await this.getWorldState(referenceBlock);
843
985
  const maybeIndices = await committedDb.findLeafIndices(
844
986
  treeId,
845
987
  leafValues.map(x => x.toBuffer()),
846
988
  );
847
- // We filter out undefined values
848
- const indices = maybeIndices.filter(x => x !== undefined) as bigint[];
989
+ // Filter out undefined values to query block numbers only for found leaves
990
+ const definedIndices = maybeIndices.filter(x => x !== undefined);
849
991
 
850
- // Now we find the block numbers for the indices
851
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
992
+ // Now we find the block numbers for the defined indices
993
+ const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
852
994
 
853
- // If any of the block numbers are undefined, we throw an error.
854
- for (let i = 0; i < indices.length; i++) {
855
- if (blockNumbers[i] === undefined) {
856
- throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
995
+ // Build a map from leaf index to block number
996
+ const indexToBlockNumber = new Map<bigint, BlockNumber>();
997
+ for (let i = 0; i < definedIndices.length; i++) {
998
+ const blockNumber = blockNumbers[i];
999
+ if (blockNumber === undefined) {
1000
+ throw new Error(
1001
+ `Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`,
1002
+ );
857
1003
  }
1004
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
858
1005
  }
859
1006
 
860
1007
  // Get unique block numbers in order to optimize num calls to getLeafValue function.
861
- const uniqueBlockNumbers = [...new Set(blockNumbers.filter(x => x !== undefined))];
1008
+ const uniqueBlockNumbers = [...new Set(indexToBlockNumber.values())];
862
1009
 
863
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
864
- // (note that block number corresponds to the leaf index in the archive tree).
1010
+ // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
865
1011
  const blockHashes = await Promise.all(
866
1012
  uniqueBlockNumbers.map(blockNumber => {
867
1013
  return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
868
1014
  }),
869
1015
  );
870
1016
 
871
- // If any of the block hashes are undefined, we throw an error.
1017
+ // Build a map from block number to block hash
1018
+ const blockNumberToHash = new Map<BlockNumber, Fr>();
872
1019
  for (let i = 0; i < uniqueBlockNumbers.length; i++) {
873
- if (blockHashes[i] === undefined) {
1020
+ const blockHash = blockHashes[i];
1021
+ if (blockHash === undefined) {
874
1022
  throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
875
1023
  }
1024
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
876
1025
  }
877
1026
 
878
1027
  // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
879
- return maybeIndices.map((index, i) => {
1028
+ return maybeIndices.map(index => {
880
1029
  if (index === undefined) {
881
1030
  return undefined;
882
1031
  }
883
- const blockNumber = blockNumbers[i];
1032
+ const blockNumber = indexToBlockNumber.get(index);
884
1033
  if (blockNumber === undefined) {
885
- return undefined;
1034
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
886
1035
  }
887
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
888
- const blockHash = blockHashes[blockHashIndex];
889
- if (!blockHash) {
890
- return undefined;
1036
+ const blockHash = blockNumberToHash.get(blockNumber);
1037
+ if (blockHash === undefined) {
1038
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
891
1039
  }
892
1040
  return {
893
- l2BlockNumber: BlockNumber(Number(blockNumber)),
894
- l2BlockHash: L2BlockHash.fromField(blockHash),
1041
+ l2BlockNumber: blockNumber,
1042
+ l2BlockHash: new BlockHash(blockHash),
895
1043
  data: index,
896
1044
  };
897
1045
  });
898
1046
  }
899
1047
 
900
- /**
901
- * Returns a sibling path for the given index in the nullifier tree.
902
- * @param blockNumber - The block number at which to get the data.
903
- * @param leafIndex - The index of the leaf for which the sibling path is required.
904
- * @returns The sibling path for the leaf index.
905
- */
906
- public async getNullifierSiblingPath(
907
- blockNumber: BlockParameter,
908
- leafIndex: bigint,
909
- ): Promise<SiblingPath<typeof NULLIFIER_TREE_HEIGHT>> {
910
- const committedDb = await this.#getWorldState(blockNumber);
911
- return committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, leafIndex);
912
- }
913
-
914
- /**
915
- * Returns a sibling path for the given index in the data tree.
916
- * @param blockNumber - The block number at which to get the data.
917
- * @param leafIndex - The index of the leaf for which the sibling path is required.
918
- * @returns The sibling path for the leaf index.
919
- */
920
- public async getNoteHashSiblingPath(
921
- blockNumber: BlockParameter,
922
- leafIndex: bigint,
923
- ): Promise<SiblingPath<typeof NOTE_HASH_TREE_HEIGHT>> {
924
- const committedDb = await this.#getWorldState(blockNumber);
925
- return committedDb.getSiblingPath(MerkleTreeId.NOTE_HASH_TREE, leafIndex);
926
- }
927
-
928
- public async getArchiveMembershipWitness(
929
- blockNumber: BlockParameter,
930
- archive: Fr,
1048
+ public async getBlockHashMembershipWitness(
1049
+ referenceBlock: BlockParameter,
1050
+ blockHash: BlockHash,
931
1051
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
932
- const committedDb = await this.#getWorldState(blockNumber);
933
- const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [archive]);
1052
+ // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
1053
+ // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1054
+ // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1055
+ const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1056
+ const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
1057
+ const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
934
1058
  return pathAndIndex === undefined
935
1059
  ? undefined
936
1060
  : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
937
1061
  }
938
1062
 
939
1063
  public async getNoteHashMembershipWitness(
940
- blockNumber: BlockParameter,
1064
+ referenceBlock: BlockParameter,
941
1065
  noteHash: Fr,
942
1066
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
943
- const committedDb = await this.#getWorldState(blockNumber);
1067
+ const committedDb = await this.getWorldState(referenceBlock);
944
1068
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
945
1069
  MerkleTreeId.NOTE_HASH_TREE,
946
1070
  [noteHash],
@@ -950,17 +1074,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
950
1074
  : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
951
1075
  }
952
1076
 
953
- /**
954
- * Returns the index and a sibling path for a leaf in the committed l1 to l2 data tree.
955
- * @param blockNumber - The block number at which to get the data.
956
- * @param l1ToL2Message - The l1ToL2Message to get the index / sibling path for.
957
- * @returns A tuple of the index and the sibling path of the L1ToL2Message (undefined if not found).
958
- */
959
1077
  public async getL1ToL2MessageMembershipWitness(
960
- blockNumber: BlockParameter,
1078
+ referenceBlock: BlockParameter,
961
1079
  l1ToL2Message: Fr,
962
1080
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
963
- const db = await this.#getWorldState(blockNumber);
1081
+ const db = await this.getWorldState(referenceBlock);
964
1082
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
965
1083
  if (!witness) {
966
1084
  return undefined;
@@ -970,11 +1088,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
970
1088
  return [witness.index, witness.path];
971
1089
  }
972
1090
 
973
- public async getL1ToL2MessageBlock(l1ToL2Message: Fr): Promise<BlockNumber | undefined> {
1091
+ public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
974
1092
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
975
- return messageIndex
976
- ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex))
977
- : undefined;
1093
+ return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
978
1094
  }
979
1095
 
980
1096
  /**
@@ -993,64 +1109,21 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
993
1109
  * @returns The L2 to L1 messages (empty array if the epoch is not found).
994
1110
  */
995
1111
  public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
996
- // Assumes `getBlocksForEpoch` returns blocks in ascending order of block number.
997
- const blocks = await this.blockSource.getBlocksForEpoch(epoch);
998
- const blocksInCheckpoints: L2Block[][] = [];
999
- let previousSlotNumber = SlotNumber.ZERO;
1000
- let checkpointIndex = -1;
1001
- for (const block of blocks) {
1002
- const slotNumber = block.header.globalVariables.slotNumber;
1003
- if (slotNumber !== previousSlotNumber) {
1004
- checkpointIndex++;
1005
- blocksInCheckpoints.push([]);
1006
- previousSlotNumber = slotNumber;
1007
- }
1008
- blocksInCheckpoints[checkpointIndex].push(block);
1009
- }
1112
+ // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1113
+ const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1114
+ const blocksInCheckpoints = chunkBy(checkpointedBlocks, cb => cb.block.header.globalVariables.slotNumber).map(
1115
+ group => group.map(cb => cb.block),
1116
+ );
1010
1117
  return blocksInCheckpoints.map(blocks =>
1011
1118
  blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1012
1119
  );
1013
1120
  }
1014
1121
 
1015
- /**
1016
- * Returns a sibling path for a leaf in the committed blocks tree.
1017
- * @param blockNumber - The block number at which to get the data.
1018
- * @param leafIndex - Index of the leaf in the tree.
1019
- * @returns The sibling path.
1020
- */
1021
- public async getArchiveSiblingPath(
1022
- blockNumber: BlockParameter,
1023
- leafIndex: bigint,
1024
- ): Promise<SiblingPath<typeof ARCHIVE_HEIGHT>> {
1025
- const committedDb = await this.#getWorldState(blockNumber);
1026
- return committedDb.getSiblingPath(MerkleTreeId.ARCHIVE, leafIndex);
1027
- }
1028
-
1029
- /**
1030
- * Returns a sibling path for a leaf in the committed public data tree.
1031
- * @param blockNumber - The block number at which to get the data.
1032
- * @param leafIndex - Index of the leaf in the tree.
1033
- * @returns The sibling path.
1034
- */
1035
- public async getPublicDataSiblingPath(
1036
- blockNumber: BlockParameter,
1037
- leafIndex: bigint,
1038
- ): Promise<SiblingPath<typeof PUBLIC_DATA_TREE_HEIGHT>> {
1039
- const committedDb = await this.#getWorldState(blockNumber);
1040
- return committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, leafIndex);
1041
- }
1042
-
1043
- /**
1044
- * Returns a nullifier membership witness for a given nullifier at a given block.
1045
- * @param blockNumber - The block number at which to get the index.
1046
- * @param nullifier - Nullifier we try to find witness for.
1047
- * @returns The nullifier membership witness (if found).
1048
- */
1049
1122
  public async getNullifierMembershipWitness(
1050
- blockNumber: BlockParameter,
1123
+ referenceBlock: BlockParameter,
1051
1124
  nullifier: Fr,
1052
1125
  ): Promise<NullifierMembershipWitness | undefined> {
1053
- const db = await this.#getWorldState(blockNumber);
1126
+ const db = await this.getWorldState(referenceBlock);
1054
1127
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
1055
1128
  if (!witness) {
1056
1129
  return undefined;
@@ -1065,32 +1138,20 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1065
1138
  return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
1066
1139
  }
1067
1140
 
1068
- /**
1069
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1070
- * @param blockNumber - The block number at which to get the index.
1071
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1072
- * @returns The low nullifier membership witness (if found).
1073
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1074
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1075
- * we are trying to prove non-inclusion for.
1076
- *
1077
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1078
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1079
- * index of the nullifier itself when it already exists in the tree.
1080
- * TODO: This is a confusing behavior and we should eventually address that.
1081
- */
1082
1141
  public async getLowNullifierMembershipWitness(
1083
- blockNumber: BlockParameter,
1142
+ referenceBlock: BlockParameter,
1084
1143
  nullifier: Fr,
1085
1144
  ): Promise<NullifierMembershipWitness | undefined> {
1086
- const committedDb = await this.#getWorldState(blockNumber);
1145
+ const committedDb = await this.getWorldState(referenceBlock);
1087
1146
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1088
1147
  if (!findResult) {
1089
1148
  return undefined;
1090
1149
  }
1091
1150
  const { index, alreadyPresent } = findResult;
1092
1151
  if (alreadyPresent) {
1093
- this.log.warn(`Nullifier ${nullifier.toBigInt()} already exists in the tree`);
1152
+ throw new Error(
1153
+ `Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`,
1154
+ );
1094
1155
  }
1095
1156
  const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
1096
1157
 
@@ -1098,8 +1159,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1098
1159
  return new NullifierMembershipWitness(BigInt(index), preimageData as NullifierLeafPreimage, siblingPath);
1099
1160
  }
1100
1161
 
1101
- async getPublicDataWitness(blockNumber: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1102
- const committedDb = await this.#getWorldState(blockNumber);
1162
+ async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1163
+ const committedDb = await this.getWorldState(referenceBlock);
1103
1164
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1104
1165
  if (!lowLeafResult) {
1105
1166
  return undefined;
@@ -1113,19 +1174,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1113
1174
  }
1114
1175
  }
1115
1176
 
1116
- /**
1117
- * Gets the storage value at the given contract storage slot.
1118
- *
1119
- * @remarks The storage slot here refers to the slot as it is defined in Noir not the index in the merkle tree.
1120
- * Aztec's version of `eth_getStorageAt`.
1121
- *
1122
- * @param contract - Address of the contract to query.
1123
- * @param slot - Slot to query.
1124
- * @param blockNumber - The block number at which to get the data or 'latest'.
1125
- * @returns Storage value at the given contract slot.
1126
- */
1127
- public async getPublicStorageAt(blockNumber: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1128
- const committedDb = await this.#getWorldState(blockNumber);
1177
+ public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1178
+ const committedDb = await this.getWorldState(referenceBlock);
1129
1179
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1130
1180
 
1131
1181
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
@@ -1139,24 +1189,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1139
1189
  return preimage.leaf.value;
1140
1190
  }
1141
1191
 
1142
- /**
1143
- * Returns the currently committed block header, or the initial header if no blocks have been produced.
1144
- * @returns The current committed block header.
1145
- */
1146
- public async getBlockHeader(blockNumber: BlockParameter = 'latest'): Promise<BlockHeader | undefined> {
1147
- return blockNumber === BlockNumber.ZERO ||
1148
- (blockNumber === 'latest' && (await this.blockSource.getBlockNumber()) === BlockNumber.ZERO)
1149
- ? this.worldStateSynchronizer.getCommitted().getInitialHeader()
1150
- : this.blockSource.getBlockHeader(blockNumber === 'latest' ? blockNumber : (blockNumber as BlockNumber));
1151
- }
1152
-
1153
- /**
1154
- * Get a block header specified by its hash.
1155
- * @param blockHash - The block hash being requested.
1156
- * @returns The requested block header.
1157
- */
1158
- public async getBlockHeaderByHash(blockHash: Fr): Promise<BlockHeader | undefined> {
1159
- return await this.blockSource.getBlockHeaderByHash(blockHash);
1192
+ public async getBlockHeader(block: BlockParameter = 'latest'): Promise<BlockHeader | undefined> {
1193
+ if (BlockHash.isBlockHash(block)) {
1194
+ const initialBlockHash = await this.#getInitialHeaderHash();
1195
+ if (block.equals(initialBlockHash)) {
1196
+ // Block source doesn't handle initial header so we need to handle the case separately.
1197
+ return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1198
+ }
1199
+ return this.blockSource.getBlockHeaderByHash(block);
1200
+ } else {
1201
+ // Block source doesn't handle initial header so we need to handle the case separately.
1202
+ const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
1203
+ if (blockNumber === BlockNumber.ZERO) {
1204
+ return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1205
+ }
1206
+ return this.blockSource.getBlockHeader(block);
1207
+ }
1160
1208
  }
1161
1209
 
1162
1210
  /**
@@ -1168,6 +1216,14 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1168
1216
  return await this.blockSource.getBlockHeaderByArchive(archive);
1169
1217
  }
1170
1218
 
1219
+ public getBlockData(number: BlockNumber): Promise<BlockData | undefined> {
1220
+ return this.blockSource.getBlockData(number);
1221
+ }
1222
+
1223
+ public getBlockDataByArchive(archive: Fr): Promise<BlockData | undefined> {
1224
+ return this.blockSource.getBlockDataByArchive(archive);
1225
+ }
1226
+
1171
1227
  /**
1172
1228
  * Simulates the public part of a transaction with the current state.
1173
1229
  * @param tx - The transaction to simulate.
@@ -1191,7 +1247,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1191
1247
  }
1192
1248
 
1193
1249
  const txHash = tx.getTxHash();
1194
- const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1250
+ const latestBlockNumber = await this.blockSource.getBlockNumber();
1251
+ const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1195
1252
 
1196
1253
  // If sequencer is not initialized, we just set these values to zero for simulation.
1197
1254
  const coinbase = EthAddress.ZERO;
@@ -1206,6 +1263,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1206
1263
  this.contractDataSource,
1207
1264
  new DateProvider(),
1208
1265
  this.telemetry,
1266
+ this.log.getBindings(),
1209
1267
  );
1210
1268
 
1211
1269
  this.log.verbose(`Simulating public calls for tx ${txHash}`, {
@@ -1214,6 +1272,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1214
1272
  blockNumber,
1215
1273
  });
1216
1274
 
1275
+ // Ensure world-state has caught up with the latest block we loaded from the archiver
1276
+ await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1217
1277
  const merkleTreeFork = await this.worldStateSynchronizer.fork();
1218
1278
  try {
1219
1279
  const config = PublicSimulatorConfig.from({
@@ -1229,7 +1289,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1229
1289
  const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1230
1290
 
1231
1291
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1232
- const [processedTxs, failedTxs, _usedTxs, returns] = await processor.process([tx]);
1292
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1233
1293
  // REFACTOR: Consider returning the error rather than throwing
1234
1294
  if (failedTxs.length) {
1235
1295
  this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
@@ -1243,6 +1303,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1243
1303
  processedTx.txEffect,
1244
1304
  returns,
1245
1305
  processedTx.gasUsed,
1306
+ debugLogs,
1246
1307
  );
1247
1308
  } finally {
1248
1309
  await merkleTreeFork.close();
@@ -1256,19 +1317,32 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1256
1317
  const db = this.worldStateSynchronizer.getCommitted();
1257
1318
  const verifier = isSimulation ? undefined : this.proofVerifier;
1258
1319
 
1259
- // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
1320
+ // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1260
1321
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1261
1322
  const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1262
- const validator = createValidatorForAcceptingTxs(db, this.contractDataSource, verifier, {
1263
- timestamp: nextSlotTimestamp,
1264
- blockNumber,
1265
- l1ChainId: this.l1ChainId,
1266
- rollupVersion: this.version,
1267
- setupAllowList: this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions()),
1268
- gasFees: await this.getCurrentMinFees(),
1269
- skipFeeEnforcement,
1270
- txsPermitted: !this.config.disableTransactions,
1271
- });
1323
+ const l1Constants = await this.blockSource.getL1Constants();
1324
+ const validator = createTxValidatorForAcceptingTxsOverRPC(
1325
+ db,
1326
+ this.contractDataSource,
1327
+ verifier,
1328
+ {
1329
+ timestamp: nextSlotTimestamp,
1330
+ blockNumber,
1331
+ l1ChainId: this.l1ChainId,
1332
+ rollupVersion: this.version,
1333
+ setupAllowList: [
1334
+ ...(await getDefaultAllowedSetupFunctions()),
1335
+ ...(this.config.txPublicSetupAllowListExtend ?? []),
1336
+ ],
1337
+ gasFees: await this.getCurrentMinFees(),
1338
+ skipFeeEnforcement,
1339
+ txsPermitted: !this.config.disableTransactions,
1340
+ rollupManaLimit: l1Constants.rollupManaLimit,
1341
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1342
+ maxBlockDAGas: this.config.validateMaxDABlockGas,
1343
+ },
1344
+ this.log.getBindings(),
1345
+ );
1272
1346
 
1273
1347
  return await validator.validateTx(tx);
1274
1348
  }
@@ -1432,16 +1506,107 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1432
1506
  }
1433
1507
  }
1434
1508
 
1509
+ public async reloadKeystore(): Promise<void> {
1510
+ if (!this.config.keyStoreDirectory?.length) {
1511
+ throw new BadRequestError(
1512
+ 'Cannot reload keystore: node is not using a file-based keystore. ' +
1513
+ 'Set KEY_STORE_DIRECTORY to use file-based keystores.',
1514
+ );
1515
+ }
1516
+ if (!this.validatorClient) {
1517
+ throw new BadRequestError('Cannot reload keystore: validator is not enabled.');
1518
+ }
1519
+
1520
+ this.log.info('Reloading keystore from disk');
1521
+
1522
+ // Re-read and validate keystore files
1523
+ const keyStores = loadKeystores(this.config.keyStoreDirectory);
1524
+ const newManager = new KeystoreManager(mergeKeystores(keyStores));
1525
+ await newManager.validateSigners();
1526
+ ValidatorClient.validateKeyStoreConfiguration(newManager, this.log);
1527
+
1528
+ // Validate that every validator's publisher keys overlap with the L1 signers
1529
+ // that were initialized at startup. Publishers cannot be hot-reloaded, so a
1530
+ // validator with a publisher key that doesn't match any existing L1 signer
1531
+ // would silently fail on every proposer slot.
1532
+ if (this.keyStoreManager && this.sequencer) {
1533
+ const oldAdapter = NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager);
1534
+ const availablePublishers = new Set(
1535
+ oldAdapter
1536
+ .getAttesterAddresses()
1537
+ .flatMap(a => oldAdapter.getPublisherAddresses(a).map(p => p.toString().toLowerCase())),
1538
+ );
1539
+
1540
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
1541
+ for (const attester of newAdapter.getAttesterAddresses()) {
1542
+ const pubs = newAdapter.getPublisherAddresses(attester);
1543
+ if (pubs.length > 0 && !pubs.some(p => availablePublishers.has(p.toString().toLowerCase()))) {
1544
+ throw new BadRequestError(
1545
+ `Cannot reload keystore: validator ${attester} has publisher keys ` +
1546
+ `[${pubs.map(p => p.toString()).join(', ')}] but none match the L1 signers initialized at startup ` +
1547
+ `[${[...availablePublishers].join(', ')}]. Publishers cannot be hot-reloaded — ` +
1548
+ `use an existing publisher key or restart the node.`,
1549
+ );
1550
+ }
1551
+ }
1552
+ }
1553
+
1554
+ // Build adapters for old and new keystores to compute diff
1555
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
1556
+ const newAddresses = newAdapter.getAttesterAddresses();
1557
+ const oldAddresses = this.keyStoreManager
1558
+ ? NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager).getAttesterAddresses()
1559
+ : [];
1560
+
1561
+ const oldSet = new Set(oldAddresses.map(a => a.toString()));
1562
+ const newSet = new Set(newAddresses.map(a => a.toString()));
1563
+ const added = newAddresses.filter(a => !oldSet.has(a.toString()));
1564
+ const removed = oldAddresses.filter(a => !newSet.has(a.toString()));
1565
+
1566
+ if (added.length > 0) {
1567
+ this.log.info(`Keystore reload: adding attester keys: ${added.map(a => a.toString()).join(', ')}`);
1568
+ }
1569
+ if (removed.length > 0) {
1570
+ this.log.info(`Keystore reload: removing attester keys: ${removed.map(a => a.toString()).join(', ')}`);
1571
+ }
1572
+ if (added.length === 0 && removed.length === 0) {
1573
+ this.log.info('Keystore reload: attester keys unchanged');
1574
+ }
1575
+
1576
+ // Update the validator client (coinbase, feeRecipient, attester keys)
1577
+ this.validatorClient.reloadKeystore(newManager);
1578
+
1579
+ // Update the publisher factory's keystore so newly-added validators
1580
+ // can be matched to existing publisher keys when proposing blocks.
1581
+ if (this.sequencer) {
1582
+ this.sequencer.updatePublisherNodeKeyStore(newAdapter);
1583
+ }
1584
+
1585
+ // Update slasher's "don't-slash-self" list with new validator addresses
1586
+ if (this.slasherClient && !this.config.slashSelfAllowed) {
1587
+ const slashValidatorsNever = unique(
1588
+ [...(this.config.slashValidatorsNever ?? []), ...newAddresses].map(a => a.toString()),
1589
+ ).map(EthAddress.fromString);
1590
+ this.slasherClient.updateConfig({ slashValidatorsNever });
1591
+ }
1592
+
1593
+ this.keyStoreManager = newManager;
1594
+ this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1595
+ }
1596
+
1597
+ #getInitialHeaderHash(): Promise<BlockHash> {
1598
+ if (!this.initialHeaderHashPromise) {
1599
+ this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
1600
+ }
1601
+ return this.initialHeaderHashPromise;
1602
+ }
1603
+
1435
1604
  /**
1436
1605
  * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1437
- * @param blockNumber - The block number at which to get the data.
1606
+ * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1438
1607
  * @returns An instance of a committed MerkleTreeOperations
1439
1608
  */
1440
- async #getWorldState(blockNumber: BlockParameter) {
1441
- if (typeof blockNumber === 'number' && blockNumber < INITIAL_L2_BLOCK_NUM - 1) {
1442
- throw new Error('Invalid block number to get world state for: ' + blockNumber);
1443
- }
1444
-
1609
+ protected async getWorldState(block: BlockParameter) {
1445
1610
  let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1446
1611
  try {
1447
1612
  // Attempt to sync the world state if necessary
@@ -1450,16 +1615,70 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1450
1615
  this.log.error(`Error getting world state: ${err}`);
1451
1616
  }
1452
1617
 
1453
- // using a snapshot could be less efficient than using the committed db
1454
- if (blockNumber === 'latest' /*|| blockNumber === blockSyncedTo*/) {
1455
- this.log.debug(`Using committed db for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1618
+ if (block === 'latest') {
1619
+ this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
1456
1620
  return this.worldStateSynchronizer.getCommitted();
1457
- } else if (blockNumber <= blockSyncedTo) {
1458
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1459
- return this.worldStateSynchronizer.getSnapshot(blockNumber as BlockNumber);
1621
+ }
1622
+
1623
+ // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1624
+ let blockNumber: BlockNumber;
1625
+ if (BlockHash.isBlockHash(block)) {
1626
+ const initialBlockHash = await this.#getInitialHeaderHash();
1627
+ if (block.equals(initialBlockHash)) {
1628
+ // Block source doesn't handle initial header so we need to handle the case separately.
1629
+ return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1630
+ }
1631
+
1632
+ const header = await this.blockSource.getBlockHeaderByHash(block);
1633
+ if (!header) {
1634
+ throw new Error(
1635
+ `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.`,
1636
+ );
1637
+ }
1638
+
1639
+ blockNumber = header.getBlockNumber();
1460
1640
  } else {
1461
- throw new Error(`Block ${blockNumber} not yet synced`);
1641
+ blockNumber = block as BlockNumber;
1642
+ }
1643
+
1644
+ // Check it's within world state sync range
1645
+ if (blockNumber > blockSyncedTo) {
1646
+ throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1647
+ }
1648
+ this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1649
+
1650
+ const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
1651
+
1652
+ // Double-check world-state synced to the same block hash as was requested
1653
+ if (BlockHash.isBlockHash(block)) {
1654
+ const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1655
+ if (!blockHash || !new BlockHash(blockHash).equals(block)) {
1656
+ throw new Error(
1657
+ `Block hash ${block.toString()} not found in world state at block number ${blockNumber}. If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
1658
+ );
1659
+ }
1660
+ }
1661
+
1662
+ return snapshot;
1663
+ }
1664
+
1665
+ /** Resolves a block parameter to a block number. */
1666
+ protected async resolveBlockNumber(block: BlockParameter): Promise<BlockNumber> {
1667
+ if (block === 'latest') {
1668
+ return BlockNumber(await this.blockSource.getBlockNumber());
1669
+ }
1670
+ if (BlockHash.isBlockHash(block)) {
1671
+ const initialBlockHash = await this.#getInitialHeaderHash();
1672
+ if (block.equals(initialBlockHash)) {
1673
+ return BlockNumber.ZERO;
1674
+ }
1675
+ const header = await this.blockSource.getBlockHeaderByHash(block);
1676
+ if (!header) {
1677
+ throw new Error(`Block hash ${block.toString()} not found.`);
1678
+ }
1679
+ return header.getBlockNumber();
1462
1680
  }
1681
+ return block as BlockNumber;
1463
1682
  }
1464
1683
 
1465
1684
  /**