@aztec/aztec-node 0.0.1-commit.27d773e65 → 0.0.1-commit.2b2662070

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,19 +1,22 @@
1
1
  import { Archiver, createArchiver } from '@aztec/archiver';
2
- import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
2
+ import { BBCircuitVerifier, BatchChonkVerifier, QueuedIVCVerifier } from '@aztec/bb-prover';
3
+ import { TestCircuitVerifier } from '@aztec/bb-prover/test';
3
4
  import { type BlobClientInterface, createBlobClientWithFileStores } from '@aztec/blob-client/client';
4
5
  import { Blob } from '@aztec/blob-lib';
5
6
  import { ARCHIVE_HEIGHT, type L1_TO_L2_MSG_TREE_HEIGHT, type NOTE_HASH_TREE_HEIGHT } from '@aztec/constants';
6
7
  import { EpochCache, type EpochCacheInterface } from '@aztec/epoch-cache';
7
8
  import { createEthereumChain } from '@aztec/ethereum/chain';
8
- import { getPublicClient } from '@aztec/ethereum/client';
9
+ import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
9
10
  import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
10
11
  import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
12
+ import type { L1TxUtils } from '@aztec/ethereum/l1-tx-utils';
11
13
  import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
12
- import { compactArray, pick, unique } from '@aztec/foundation/collection';
14
+ import { chunkBy, compactArray, pick, unique } from '@aztec/foundation/collection';
13
15
  import { Fr } from '@aztec/foundation/curves/bn254';
14
16
  import { EthAddress } from '@aztec/foundation/eth-address';
15
17
  import { BadRequestError } from '@aztec/foundation/json-rpc';
16
18
  import { type Logger, createLogger } from '@aztec/foundation/log';
19
+ import { retryUntil } from '@aztec/foundation/retry';
17
20
  import { count } from '@aztec/foundation/string';
18
21
  import { DateProvider, Timer } from '@aztec/foundation/timer';
19
22
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
@@ -30,7 +33,12 @@ import {
30
33
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
31
34
  import { type ProverNode, type ProverNodeDeps, createProverNode } from '@aztec/prover-node';
32
35
  import { createKeyStoreForProver } from '@aztec/prover-node/config';
33
- import { GlobalVariableBuilder, SequencerClient, type SequencerPublisher } from '@aztec/sequencer-client';
36
+ import {
37
+ FeeProviderImpl,
38
+ GlobalVariableBuilder,
39
+ SequencerClient,
40
+ type SequencerPublisher,
41
+ } from '@aztec/sequencer-client';
34
42
  import { PublicProcessorFactory } from '@aztec/simulator/server';
35
43
  import {
36
44
  AttestationsBlockWatcher,
@@ -57,13 +65,14 @@ import type {
57
65
  NodeInfo,
58
66
  ProtocolContractAddresses,
59
67
  } from '@aztec/stdlib/contract';
60
- import { GasFees } from '@aztec/stdlib/gas';
68
+ import { GasFees, type ManaUsageEstimate } from '@aztec/stdlib/gas';
61
69
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
62
70
  import {
63
71
  type AztecNode,
64
72
  type AztecNodeAdmin,
65
73
  type AztecNodeAdminConfig,
66
74
  AztecNodeAdminConfigSchema,
75
+ type AztecNodeDebug,
67
76
  type GetContractClassLogsResponse,
68
77
  type GetPublicLogsResponse,
69
78
  } from '@aztec/stdlib/interfaces/client';
@@ -79,11 +88,12 @@ import {
79
88
  import type { DebugLogStore, LogFilter, SiloedTag, Tag, TxScopedL2Log } from '@aztec/stdlib/logs';
80
89
  import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
81
90
  import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
82
- import type { Offense, SlashPayloadRound } from '@aztec/stdlib/slashing';
83
- import type { NullifierLeafPreimage, PublicDataTreeLeaf, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
91
+ import type { Offense } from '@aztec/stdlib/slashing';
92
+ import type { NullifierLeafPreimage, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
84
93
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
85
94
  import {
86
95
  type BlockHeader,
96
+ type FeeProvider,
87
97
  type GlobalVariableBuilder as GlobalVariableBuilderInterface,
88
98
  type IndexedTxEffect,
89
99
  PublicSimulationOutput,
@@ -95,6 +105,7 @@ import {
95
105
  } from '@aztec/stdlib/tx';
96
106
  import { getPackageVersion } from '@aztec/stdlib/update-checker';
97
107
  import type { SingleValidatorStats, ValidatorsStats } from '@aztec/stdlib/validators';
108
+ import type { GenesisData } from '@aztec/stdlib/world-state';
98
109
  import {
99
110
  Attributes,
100
111
  type TelemetryClient,
@@ -108,12 +119,13 @@ import {
108
119
  FullNodeCheckpointsBuilder,
109
120
  NodeKeystoreAdapter,
110
121
  ValidatorClient,
111
- createBlockProposalHandler,
122
+ createProposalHandler,
112
123
  createValidatorClient,
113
124
  } from '@aztec/validator-client';
125
+ import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
114
126
  import { createWorldStateSynchronizer } from '@aztec/world-state';
115
127
 
116
- import { createPublicClient, fallback, http } from 'viem';
128
+ import { createPublicClient } from 'viem';
117
129
 
118
130
  import { createSentinel } from '../sentinel/factory.js';
119
131
  import { Sentinel } from '../sentinel/sentinel.js';
@@ -123,7 +135,7 @@ import { NodeMetrics } from './node_metrics.js';
123
135
  /**
124
136
  * The aztec node.
125
137
  */
126
- export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
138
+ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDebug, Traceable {
127
139
  private metrics: NodeMetrics;
128
140
  private initialHeaderHashPromise: Promise<BlockHash> | undefined = undefined;
129
141
 
@@ -148,9 +160,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
148
160
  protected readonly l1ChainId: number,
149
161
  protected readonly version: number,
150
162
  protected readonly globalVariableBuilder: GlobalVariableBuilderInterface,
163
+ protected readonly feeProvider: FeeProvider,
151
164
  protected readonly epochCache: EpochCacheInterface,
152
165
  protected readonly packageVersion: string,
153
- private proofVerifier: ClientProtocolCircuitVerifier,
166
+ private peerProofVerifier: ClientProtocolCircuitVerifier,
167
+ private rpcProofVerifier: ClientProtocolCircuitVerifier,
154
168
  private telemetry: TelemetryClient = getTelemetryClient(),
155
169
  private log = createLogger('node'),
156
170
  private blobClient?: BlobClientInterface,
@@ -172,6 +186,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
172
186
  }
173
187
  }
174
188
 
189
+ /** @internal Exposed for testing — returns the RPC proof verifier. */
190
+ public getProofVerifier(): ClientProtocolCircuitVerifier {
191
+ return this.rpcProofVerifier;
192
+ }
193
+
175
194
  public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
176
195
  const status = await this.worldStateSynchronizer.status();
177
196
  return status.syncSummary;
@@ -195,9 +214,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
195
214
  dateProvider?: DateProvider;
196
215
  p2pClientDeps?: P2PClientDeps;
197
216
  proverNodeDeps?: Partial<ProverNodeDeps>;
217
+ slashingProtectionDb?: SlashingProtectionDatabase;
198
218
  } = {},
199
219
  options: {
200
- prefilledPublicData?: PublicDataTreeLeaf[];
220
+ genesis?: GenesisData;
201
221
  dontStartSequencer?: boolean;
202
222
  dontStartProverNode?: boolean;
203
223
  } = {},
@@ -257,7 +277,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
257
277
 
258
278
  const publicClient = createPublicClient({
259
279
  chain: ethereumChain.chainInfo,
260
- transport: fallback(config.l1RpcUrls.map((url: string) => http(url, { batch: false }))),
280
+ transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
261
281
  pollingInterval: config.viemPollingIntervalMS,
262
282
  });
263
283
 
@@ -271,10 +291,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
271
291
  config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
272
292
 
273
293
  const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
274
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
294
+ const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
275
295
  rollupContract.getL1GenesisTime(),
276
296
  rollupContract.getSlotDuration(),
277
297
  rollupContract.getVersion(),
298
+ rollupContract.getManaLimit().then(Number),
278
299
  ] as const);
279
300
 
280
301
  config.rollupVersion ??= Number(rollupVersionFromRollup);
@@ -299,16 +320,18 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
299
320
  );
300
321
 
301
322
  // now create the merkle trees and the world state synchronizer
302
- const worldStateSynchronizer = await createWorldStateSynchronizer(
303
- config,
304
- archiver,
305
- options.prefilledPublicData,
306
- telemetry,
307
- );
308
- const circuitVerifier =
309
- config.realProofs || config.debugForceTxProofVerification
310
- ? await BBCircuitVerifier.new(config)
311
- : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
323
+ const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.genesis, telemetry);
324
+ const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
325
+ let peerProofVerifier: ClientProtocolCircuitVerifier;
326
+ let rpcProofVerifier: ClientProtocolCircuitVerifier;
327
+ if (useRealVerifiers) {
328
+ peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
329
+ const rpcVerifier = await BBCircuitVerifier.new(config);
330
+ rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
331
+ } else {
332
+ peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
333
+ rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
334
+ }
312
335
 
313
336
  let debugLogStore: DebugLogStore;
314
337
  if (!config.realProofs) {
@@ -322,8 +345,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
322
345
  debugLogStore = new NullDebugLogStore();
323
346
  }
324
347
 
325
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
326
-
327
348
  const proverOnly = config.enableProverNode && config.disableValidator;
328
349
  if (proverOnly) {
329
350
  log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
@@ -333,7 +354,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
333
354
  const p2pClient = await createP2PClient(
334
355
  config,
335
356
  archiver,
336
- proofVerifier,
357
+ peerProofVerifier,
337
358
  worldStateSynchronizer,
338
359
  epochCache,
339
360
  packageVersion,
@@ -342,15 +363,19 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
342
363
  deps.p2pClientDeps,
343
364
  );
344
365
 
345
- // We should really not be modifying the config object
346
- config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
347
-
348
366
  // We'll accumulate sentinel watchers here
349
367
  const watchers: Watcher[] = [];
350
368
 
351
- // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation
369
+ // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
370
+ // Override maxTxsPerCheckpoint with the validator-specific limit if set.
352
371
  const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
353
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
372
+ {
373
+ ...config,
374
+ l1GenesisTime,
375
+ slotDuration: Number(slotDuration),
376
+ rollupManaLimit,
377
+ maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint,
378
+ },
354
379
  worldStateSynchronizer,
355
380
  archiver,
356
381
  dateProvider,
@@ -372,6 +397,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
372
397
  l1ToL2MessageSource: archiver,
373
398
  keyStoreManager,
374
399
  blobClient,
400
+ slashingProtectionDb: deps.slashingProtectionDb,
375
401
  });
376
402
 
377
403
  // If we have a validator client, register it as a source of offenses for the slasher,
@@ -379,26 +405,35 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
379
405
  // like attestations or auths will fail.
380
406
  if (validatorClient) {
381
407
  watchers.push(validatorClient);
408
+
409
+ const vc = validatorClient;
410
+ const getValidatorAddresses = () => vc.getValidatorAddresses().map(a => a.toString());
411
+ validatorClient.getProposalHandler().register(p2pClient, true, archiver, getValidatorAddresses);
412
+
382
413
  if (!options.dontStartSequencer) {
383
414
  await validatorClient.registerHandlers();
384
415
  }
385
416
  }
417
+ }
386
418
 
387
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
388
- // create a BlockProposalHandler to reexecute block proposals for monitoring
389
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
390
- log.info('Setting up block proposal reexecution for monitoring');
391
- createBlockProposalHandler(config, {
392
- checkpointsBuilder: validatorCheckpointsBuilder,
393
- worldState: worldStateSynchronizer,
394
- epochCache,
395
- blockSource: archiver,
396
- l1ToL2MessageSource: archiver,
397
- p2pClient,
398
- dateProvider,
399
- telemetry,
400
- }).registerForReexecution(p2pClient);
401
- }
419
+ // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
420
+ // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
421
+ // while non-reexecution is used for validating the proposals and collecting their txs.
422
+ // Checkpoint proposals rebuild blobs if the blob client can upload blobs.
423
+ if (!validatorClient) {
424
+ const reexecute = !!config.alwaysReexecuteBlockProposals;
425
+ log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
426
+ createProposalHandler(config, {
427
+ checkpointsBuilder: validatorCheckpointsBuilder,
428
+ worldState: worldStateSynchronizer,
429
+ epochCache,
430
+ blockSource: archiver,
431
+ l1ToL2MessageSource: archiver,
432
+ p2pClient,
433
+ blobClient,
434
+ dateProvider,
435
+ telemetry,
436
+ }).register(p2pClient, reexecute, archiver);
402
437
  }
403
438
 
404
439
  // Start world state and wait for it to sync to the archiver.
@@ -440,7 +475,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
440
475
  void archiver
441
476
  .waitForInitialSync()
442
477
  .then(async () => {
443
- await p2pClient.start();
444
478
  await validatorsSentinel?.start();
445
479
  await epochPruneWatcher?.start();
446
480
  await attestationsBlockWatcher?.start();
@@ -448,6 +482,17 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
448
482
  })
449
483
  .catch(err => log.error('Failed to start p2p services after archiver sync', err));
450
484
 
485
+ const globalVariableBuilderConfig = {
486
+ l1Contracts: config.l1Contracts,
487
+ ethereumSlotDuration: config.ethereumSlotDuration,
488
+ rollupVersion: BigInt(config.rollupVersion),
489
+ l1GenesisTime,
490
+ slotDuration: Number(slotDuration),
491
+ };
492
+
493
+ const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, globalVariableBuilderConfig);
494
+ const feeProvider = new FeeProviderImpl(dateProvider, publicClient, globalVariableBuilderConfig);
495
+
451
496
  // Validator enabled, create/start relevant service
452
497
  let sequencer: SequencerClient | undefined;
453
498
  let slasherClient: SlasherClientInterface | undefined;
@@ -485,9 +530,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
485
530
  { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
486
531
  );
487
532
 
533
+ // Create a funder L1TxUtils from the keystore funding account (if configured)
534
+ const fundingSigner = keyStoreManager?.createFundingSigner();
535
+ let funderL1TxUtils: L1TxUtils | undefined;
536
+ if (fundingSigner) {
537
+ const [funder] = await createL1TxUtilsFromSigners(
538
+ publicClient,
539
+ [fundingSigner],
540
+ { ...config, scope: 'sequencer' },
541
+ { telemetry, logger: log.createChild('l1-tx-utils:funder'), dateProvider },
542
+ );
543
+ funderL1TxUtils = funder;
544
+ }
545
+
488
546
  // Create and start the sequencer client
489
547
  const checkpointsBuilder = new CheckpointsBuilder(
490
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
548
+ { ...config, l1GenesisTime, slotDuration: Number(slotDuration), rollupManaLimit },
491
549
  worldStateSynchronizer,
492
550
  archiver,
493
551
  dateProvider,
@@ -499,6 +557,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
499
557
  ...deps,
500
558
  epochCache,
501
559
  l1TxUtils,
560
+ funderL1TxUtils,
502
561
  validatorClient,
503
562
  p2pClient,
504
563
  worldStateSynchronizer,
@@ -510,6 +569,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
510
569
  dateProvider,
511
570
  blobClient,
512
571
  nodeKeyStore: keyStoreManager!,
572
+ globalVariableBuilder,
513
573
  });
514
574
  }
515
575
 
@@ -543,13 +603,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
543
603
  }
544
604
  }
545
605
 
546
- const globalVariableBuilder = new GlobalVariableBuilder({
547
- ...config,
548
- rollupVersion: BigInt(config.rollupVersion),
549
- l1GenesisTime,
550
- slotDuration: Number(slotDuration),
551
- });
552
-
553
606
  const node = new AztecNodeService(
554
607
  config,
555
608
  p2pClient,
@@ -566,9 +619,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
566
619
  ethereumChain.chainInfo.id,
567
620
  config.rollupVersion,
568
621
  globalVariableBuilder,
622
+ feeProvider,
569
623
  epochCache,
570
624
  packageVersion,
571
- proofVerifier,
625
+ peerProofVerifier,
626
+ rpcProofVerifier,
572
627
  telemetry,
573
628
  log,
574
629
  blobClient,
@@ -618,7 +673,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
618
673
  }
619
674
 
620
675
  public async getAllowedPublicSetup(): Promise<AllowedElement[]> {
621
- return this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
676
+ return [...(await getDefaultAllowedSetupFunctions()), ...(this.config.txPublicSetupAllowListExtend ?? [])];
622
677
  }
623
678
 
624
679
  /**
@@ -713,12 +768,17 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
713
768
  return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
714
769
  }
715
770
 
716
- /**
717
- * Method to fetch the current min L2 fees.
718
- * @returns The current min L2 fees.
719
- */
771
+ public getCheckpointsDataForEpoch(epochNumber: EpochNumber) {
772
+ return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
773
+ }
774
+
720
775
  public async getCurrentMinFees(): Promise<GasFees> {
721
- return await this.globalVariableBuilder.getCurrentMinFees();
776
+ return await this.feeProvider.getCurrentMinFees();
777
+ }
778
+
779
+ /** Returns predicted min fees for the current slot and next N slots. */
780
+ public async getPredictedMinFees(manaUsage?: ManaUsageEstimate): Promise<GasFees[]> {
781
+ return await this.feeProvider.getPredictedMinFees(manaUsage);
722
782
  }
723
783
 
724
784
  public async getMaxPriorityFees(): Promise<GasFees> {
@@ -745,6 +805,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
745
805
  return await this.blockSource.getCheckpointedL2BlockNumber();
746
806
  }
747
807
 
808
+ public getCheckpointNumber(): Promise<CheckpointNumber> {
809
+ return this.blockSource.getCheckpointNumber();
810
+ }
811
+
748
812
  /**
749
813
  * Method to fetch the version of the package.
750
814
  * @returns The node package version
@@ -782,18 +846,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
782
846
  page?: number,
783
847
  referenceBlock?: BlockHash,
784
848
  ): Promise<TxScopedL2Log[][]> {
849
+ let upToBlockNumber: BlockNumber | undefined;
785
850
  if (referenceBlock) {
786
851
  const initialBlockHash = await this.#getInitialHeaderHash();
787
- if (!referenceBlock.equals(initialBlockHash)) {
852
+ if (referenceBlock.equals(initialBlockHash)) {
853
+ upToBlockNumber = BlockNumber(0);
854
+ } else {
788
855
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
789
856
  if (!header) {
790
857
  throw new Error(
791
858
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
792
859
  );
793
860
  }
861
+ upToBlockNumber = header.globalVariables.blockNumber;
794
862
  }
795
863
  }
796
- return this.logsSource.getPrivateLogsByTags(tags, page);
864
+ return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
797
865
  }
798
866
 
799
867
  public async getPublicLogsByTagsFromContract(
@@ -802,18 +870,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
802
870
  page?: number,
803
871
  referenceBlock?: BlockHash,
804
872
  ): Promise<TxScopedL2Log[][]> {
873
+ let upToBlockNumber: BlockNumber | undefined;
805
874
  if (referenceBlock) {
806
875
  const initialBlockHash = await this.#getInitialHeaderHash();
807
- if (!referenceBlock.equals(initialBlockHash)) {
876
+ if (referenceBlock.equals(initialBlockHash)) {
877
+ upToBlockNumber = BlockNumber(0);
878
+ } else {
808
879
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
809
880
  if (!header) {
810
881
  throw new Error(
811
882
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
812
883
  );
813
884
  }
885
+ upToBlockNumber = header.globalVariables.blockNumber;
814
886
  }
815
887
  }
816
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
888
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
817
889
  }
818
890
 
819
891
  /**
@@ -899,7 +971,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
899
971
  await tryStop(this.validatorsSentinel);
900
972
  await tryStop(this.epochPruneWatcher);
901
973
  await tryStop(this.slasherClient);
902
- await tryStop(this.proofVerifier);
974
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
903
975
  await tryStop(this.sequencer);
904
976
  await tryStop(this.proverNode);
905
977
  await tryStop(this.p2pClient);
@@ -955,59 +1027,65 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
955
1027
  treeId: MerkleTreeId,
956
1028
  leafValues: Fr[],
957
1029
  ): Promise<(DataInBlock<bigint> | undefined)[]> {
958
- const committedDb = await this.#getWorldState(referenceBlock);
1030
+ const committedDb = await this.getWorldState(referenceBlock);
959
1031
  const maybeIndices = await committedDb.findLeafIndices(
960
1032
  treeId,
961
1033
  leafValues.map(x => x.toBuffer()),
962
1034
  );
963
- // We filter out undefined values
964
- const indices = maybeIndices.filter(x => x !== undefined) as bigint[];
1035
+ // Filter out undefined values to query block numbers only for found leaves
1036
+ const definedIndices = maybeIndices.filter(x => x !== undefined);
965
1037
 
966
- // Now we find the block numbers for the indices
967
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
1038
+ // Now we find the block numbers for the defined indices
1039
+ const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
968
1040
 
969
- // If any of the block numbers are undefined, we throw an error.
970
- for (let i = 0; i < indices.length; i++) {
971
- if (blockNumbers[i] === undefined) {
972
- throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
1041
+ // Build a map from leaf index to block number
1042
+ const indexToBlockNumber = new Map<bigint, BlockNumber>();
1043
+ for (let i = 0; i < definedIndices.length; i++) {
1044
+ const blockNumber = blockNumbers[i];
1045
+ if (blockNumber === undefined) {
1046
+ throw new Error(
1047
+ `Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`,
1048
+ );
973
1049
  }
1050
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
974
1051
  }
975
1052
 
976
1053
  // Get unique block numbers in order to optimize num calls to getLeafValue function.
977
- const uniqueBlockNumbers = [...new Set(blockNumbers.filter(x => x !== undefined))];
1054
+ const uniqueBlockNumbers = [...new Set(indexToBlockNumber.values())];
978
1055
 
979
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
980
- // (note that block number corresponds to the leaf index in the archive tree).
1056
+ // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
981
1057
  const blockHashes = await Promise.all(
982
1058
  uniqueBlockNumbers.map(blockNumber => {
983
1059
  return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
984
1060
  }),
985
1061
  );
986
1062
 
987
- // If any of the block hashes are undefined, we throw an error.
1063
+ // Build a map from block number to block hash
1064
+ const blockNumberToHash = new Map<BlockNumber, BlockHash>();
988
1065
  for (let i = 0; i < uniqueBlockNumbers.length; i++) {
989
- if (blockHashes[i] === undefined) {
1066
+ const blockHash = blockHashes[i];
1067
+ if (blockHash === undefined) {
990
1068
  throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
991
1069
  }
1070
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
992
1071
  }
993
1072
 
994
1073
  // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
995
- return maybeIndices.map((index, i) => {
1074
+ return maybeIndices.map(index => {
996
1075
  if (index === undefined) {
997
1076
  return undefined;
998
1077
  }
999
- const blockNumber = blockNumbers[i];
1078
+ const blockNumber = indexToBlockNumber.get(index);
1000
1079
  if (blockNumber === undefined) {
1001
- return undefined;
1080
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1002
1081
  }
1003
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
1004
- const blockHash = blockHashes[blockHashIndex];
1005
- if (!blockHash) {
1006
- return undefined;
1082
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
1083
+ if (l2BlockHash === undefined) {
1084
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
1007
1085
  }
1008
1086
  return {
1009
- l2BlockNumber: BlockNumber(Number(blockNumber)),
1010
- l2BlockHash: new BlockHash(blockHash),
1087
+ l2BlockNumber: blockNumber,
1088
+ l2BlockHash,
1011
1089
  data: index,
1012
1090
  };
1013
1091
  });
@@ -1017,7 +1095,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1017
1095
  referenceBlock: BlockParameter,
1018
1096
  blockHash: BlockHash,
1019
1097
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
1020
- const committedDb = await this.#getWorldState(referenceBlock);
1098
+ // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
1099
+ // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1100
+ // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1101
+ const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1102
+ if (referenceBlockNumber === BlockNumber.ZERO) {
1103
+ // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
1104
+ return undefined;
1105
+ }
1106
+ const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
1021
1107
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
1022
1108
  return pathAndIndex === undefined
1023
1109
  ? undefined
@@ -1028,7 +1114,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1028
1114
  referenceBlock: BlockParameter,
1029
1115
  noteHash: Fr,
1030
1116
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
1031
- const committedDb = await this.#getWorldState(referenceBlock);
1117
+ const committedDb = await this.getWorldState(referenceBlock);
1032
1118
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
1033
1119
  MerkleTreeId.NOTE_HASH_TREE,
1034
1120
  [noteHash],
@@ -1042,7 +1128,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1042
1128
  referenceBlock: BlockParameter,
1043
1129
  l1ToL2Message: Fr,
1044
1130
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
1045
- const db = await this.#getWorldState(referenceBlock);
1131
+ const db = await this.getWorldState(referenceBlock);
1046
1132
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
1047
1133
  if (!witness) {
1048
1134
  return undefined;
@@ -1052,11 +1138,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1052
1138
  return [witness.index, witness.path];
1053
1139
  }
1054
1140
 
1055
- public async getL1ToL2MessageBlock(l1ToL2Message: Fr): Promise<BlockNumber | undefined> {
1141
+ public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
1056
1142
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1057
- return messageIndex
1058
- ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex))
1059
- : undefined;
1143
+ return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1060
1144
  }
1061
1145
 
1062
1146
  /**
@@ -1077,19 +1161,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1077
1161
  public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
1078
1162
  // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1079
1163
  const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1080
- const blocksInCheckpoints: L2Block[][] = [];
1081
- let previousSlotNumber = SlotNumber.ZERO;
1082
- let checkpointIndex = -1;
1083
- for (const checkpointedBlock of checkpointedBlocks) {
1084
- const block = checkpointedBlock.block;
1085
- const slotNumber = block.header.globalVariables.slotNumber;
1086
- if (slotNumber !== previousSlotNumber) {
1087
- checkpointIndex++;
1088
- blocksInCheckpoints.push([]);
1089
- previousSlotNumber = slotNumber;
1090
- }
1091
- blocksInCheckpoints[checkpointIndex].push(block);
1092
- }
1164
+ const blocksInCheckpoints = chunkBy(checkpointedBlocks, cb => cb.block.header.globalVariables.slotNumber).map(
1165
+ group => group.map(cb => cb.block),
1166
+ );
1093
1167
  return blocksInCheckpoints.map(blocks =>
1094
1168
  blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1095
1169
  );
@@ -1099,7 +1173,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1099
1173
  referenceBlock: BlockParameter,
1100
1174
  nullifier: Fr,
1101
1175
  ): Promise<NullifierMembershipWitness | undefined> {
1102
- const db = await this.#getWorldState(referenceBlock);
1176
+ const db = await this.getWorldState(referenceBlock);
1103
1177
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
1104
1178
  if (!witness) {
1105
1179
  return undefined;
@@ -1114,33 +1188,20 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1114
1188
  return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
1115
1189
  }
1116
1190
 
1117
- /**
1118
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1119
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1120
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1121
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1122
- * @returns The low nullifier membership witness (if found).
1123
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1124
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1125
- * we are trying to prove non-inclusion for.
1126
- *
1127
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1128
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1129
- * index of the nullifier itself when it already exists in the tree.
1130
- * TODO: This is a confusing behavior and we should eventually address that.
1131
- */
1132
1191
  public async getLowNullifierMembershipWitness(
1133
1192
  referenceBlock: BlockParameter,
1134
1193
  nullifier: Fr,
1135
1194
  ): Promise<NullifierMembershipWitness | undefined> {
1136
- const committedDb = await this.#getWorldState(referenceBlock);
1195
+ const committedDb = await this.getWorldState(referenceBlock);
1137
1196
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1138
1197
  if (!findResult) {
1139
1198
  return undefined;
1140
1199
  }
1141
1200
  const { index, alreadyPresent } = findResult;
1142
1201
  if (alreadyPresent) {
1143
- this.log.warn(`Nullifier ${nullifier.toBigInt()} already exists in the tree`);
1202
+ throw new Error(
1203
+ `Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`,
1204
+ );
1144
1205
  }
1145
1206
  const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
1146
1207
 
@@ -1149,7 +1210,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1149
1210
  }
1150
1211
 
1151
1212
  async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1152
- const committedDb = await this.#getWorldState(referenceBlock);
1213
+ const committedDb = await this.getWorldState(referenceBlock);
1153
1214
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1154
1215
  if (!lowLeafResult) {
1155
1216
  return undefined;
@@ -1164,7 +1225,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1164
1225
  }
1165
1226
 
1166
1227
  public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1167
- const committedDb = await this.#getWorldState(referenceBlock);
1228
+ const committedDb = await this.getWorldState(referenceBlock);
1168
1229
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1169
1230
 
1170
1231
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
@@ -1278,7 +1339,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1278
1339
  const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1279
1340
 
1280
1341
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1281
- const [processedTxs, failedTxs, _usedTxs, returns, _blobFields, debugLogs] = await processor.process([tx]);
1342
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1282
1343
  // REFACTOR: Consider returning the error rather than throwing
1283
1344
  if (failedTxs.length) {
1284
1345
  this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
@@ -1304,11 +1365,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1304
1365
  { isSimulation, skipFeeEnforcement }: { isSimulation?: boolean; skipFeeEnforcement?: boolean } = {},
1305
1366
  ): Promise<TxValidationResult> {
1306
1367
  const db = this.worldStateSynchronizer.getCommitted();
1307
- const verifier = isSimulation ? undefined : this.proofVerifier;
1368
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1308
1369
 
1309
1370
  // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1310
1371
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1311
1372
  const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1373
+ const l1Constants = await this.blockSource.getL1Constants();
1312
1374
  const validator = createTxValidatorForAcceptingTxsOverRPC(
1313
1375
  db,
1314
1376
  this.contractDataSource,
@@ -1318,10 +1380,16 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1318
1380
  blockNumber,
1319
1381
  l1ChainId: this.l1ChainId,
1320
1382
  rollupVersion: this.version,
1321
- setupAllowList: this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions()),
1383
+ setupAllowList: [
1384
+ ...(await getDefaultAllowedSetupFunctions()),
1385
+ ...(this.config.txPublicSetupAllowListExtend ?? []),
1386
+ ],
1322
1387
  gasFees: await this.getCurrentMinFees(),
1323
1388
  skipFeeEnforcement,
1324
1389
  txsPermitted: !this.config.disableTransactions,
1390
+ rollupManaLimit: l1Constants.rollupManaLimit,
1391
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1392
+ maxBlockDAGas: this.config.validateMaxDABlockGas,
1325
1393
  },
1326
1394
  this.log.getBindings(),
1327
1395
  );
@@ -1346,7 +1414,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1346
1414
  archiver.updateConfig(config);
1347
1415
  }
1348
1416
  if (newConfig.realProofs !== this.config.realProofs) {
1349
- this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
1417
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
1418
+ if (newConfig.realProofs) {
1419
+ this.peerProofVerifier = await BatchChonkVerifier.new(newConfig, newConfig.bbChonkVerifyMaxBatch, 'peer');
1420
+ const rpcVerifier = await BBCircuitVerifier.new(newConfig);
1421
+ this.rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, newConfig.numConcurrentIVCVerifiers);
1422
+ } else {
1423
+ this.peerProofVerifier = new TestCircuitVerifier();
1424
+ this.rpcProofVerifier = new TestCircuitVerifier();
1425
+ }
1350
1426
  }
1351
1427
 
1352
1428
  this.config = newConfig;
@@ -1421,7 +1497,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1421
1497
  return Promise.resolve();
1422
1498
  }
1423
1499
 
1424
- public async rollbackTo(targetBlock: BlockNumber, force?: boolean): Promise<void> {
1500
+ public async rollbackTo(targetBlock: BlockNumber, force?: boolean, resumeSync = true): Promise<void> {
1425
1501
  const archiver = this.blockSource as Archiver;
1426
1502
  if (!('rollbackTo' in archiver)) {
1427
1503
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1451,9 +1527,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1451
1527
  this.log.error(`Error during rollback`, err);
1452
1528
  throw err;
1453
1529
  } finally {
1454
- this.log.info(`Resuming world state and archiver sync.`);
1455
- this.worldStateSynchronizer.resumeSync();
1456
- archiver.resume();
1530
+ if (resumeSync) {
1531
+ this.log.info(`Resuming world state and archiver sync.`);
1532
+ this.worldStateSynchronizer.resumeSync();
1533
+ archiver.resume();
1534
+ } else {
1535
+ this.log.info(`Sync left paused after rollback (resumeSync=false).`);
1536
+ }
1457
1537
  }
1458
1538
  }
1459
1539
 
@@ -1470,19 +1550,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1470
1550
  return Promise.resolve();
1471
1551
  }
1472
1552
 
1473
- public getSlashPayloads(): Promise<SlashPayloadRound[]> {
1474
- if (!this.slasherClient) {
1475
- throw new Error(`Slasher client not enabled`);
1476
- }
1477
- return this.slasherClient.getSlashPayloads();
1478
- }
1479
-
1480
1553
  public getSlashOffenses(round: bigint | 'all' | 'current'): Promise<Offense[]> {
1481
1554
  if (!this.slasherClient) {
1482
1555
  throw new Error(`Slasher client not enabled`);
1483
1556
  }
1484
1557
  if (round === 'all') {
1485
- return this.slasherClient.getPendingOffenses();
1558
+ return this.slasherClient.getOffenses();
1486
1559
  } else {
1487
1560
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1488
1561
  }
@@ -1576,6 +1649,40 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1576
1649
  this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1577
1650
  }
1578
1651
 
1652
+ public async mineBlock(): Promise<void> {
1653
+ if (!this.sequencer) {
1654
+ throw new BadRequestError('Cannot mine block: no sequencer is running');
1655
+ }
1656
+
1657
+ const currentBlockNumber = await this.getBlockNumber();
1658
+
1659
+ // Use slot duration + 50% buffer as the timeout so this works on running networks too
1660
+ const { slotDuration } = await this.blockSource.getL1Constants();
1661
+ const timeoutSeconds = Math.ceil(slotDuration * 1.5);
1662
+
1663
+ // Temporarily set minTxsPerBlock to 0 so the sequencer produces a block even with no txs
1664
+ const originalMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock;
1665
+ this.sequencer.updateConfig({ minTxsPerBlock: 0 });
1666
+
1667
+ try {
1668
+ // Trigger the sequencer to produce a block immediately
1669
+ void this.sequencer.trigger();
1670
+
1671
+ // Wait for the new L2 block to appear
1672
+ await retryUntil(
1673
+ async () => {
1674
+ const newBlockNumber = await this.getBlockNumber();
1675
+ return newBlockNumber > currentBlockNumber ? true : undefined;
1676
+ },
1677
+ 'mineBlock',
1678
+ timeoutSeconds,
1679
+ 0.1,
1680
+ );
1681
+ } finally {
1682
+ this.sequencer.updateConfig({ minTxsPerBlock: originalMinTxsPerBlock });
1683
+ }
1684
+ }
1685
+
1579
1686
  #getInitialHeaderHash(): Promise<BlockHash> {
1580
1687
  if (!this.initialHeaderHashPromise) {
1581
1688
  this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
@@ -1588,7 +1695,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1588
1695
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1589
1696
  * @returns An instance of a committed MerkleTreeOperations
1590
1697
  */
1591
- async #getWorldState(block: BlockParameter) {
1698
+ protected async getWorldState(block: BlockParameter) {
1592
1699
  let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1593
1700
  try {
1594
1701
  // Attempt to sync the world state if necessary
@@ -1602,6 +1709,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1602
1709
  return this.worldStateSynchronizer.getCommitted();
1603
1710
  }
1604
1711
 
1712
+ // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1713
+ let blockNumber: BlockNumber;
1605
1714
  if (BlockHash.isBlockHash(block)) {
1606
1715
  const initialBlockHash = await this.#getInitialHeaderHash();
1607
1716
  if (block.equals(initialBlockHash)) {
@@ -1615,22 +1724,50 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1615
1724
  `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.`,
1616
1725
  );
1617
1726
  }
1618
- const blockNumber = header.getBlockNumber();
1619
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1620
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1727
+
1728
+ blockNumber = header.getBlockNumber();
1729
+ } else {
1730
+ blockNumber = block as BlockNumber;
1731
+ }
1732
+
1733
+ // Check it's within world state sync range
1734
+ if (blockNumber > blockSyncedTo) {
1735
+ throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1621
1736
  }
1737
+ this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1622
1738
 
1623
- // Block number provided
1624
- {
1625
- const blockNumber = block as BlockNumber;
1739
+ const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
1626
1740
 
1627
- if (blockNumber > blockSyncedTo) {
1628
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1741
+ // Double-check world-state synced to the same block hash as was requested
1742
+ if (BlockHash.isBlockHash(block)) {
1743
+ const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1744
+ if (!blockHash || !block.equals(blockHash)) {
1745
+ throw new Error(
1746
+ `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.`,
1747
+ );
1629
1748
  }
1749
+ }
1750
+
1751
+ return snapshot;
1752
+ }
1630
1753
 
1631
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1632
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1754
+ /** Resolves a block parameter to a block number. */
1755
+ protected async resolveBlockNumber(block: BlockParameter): Promise<BlockNumber> {
1756
+ if (block === 'latest') {
1757
+ return BlockNumber(await this.blockSource.getBlockNumber());
1758
+ }
1759
+ if (BlockHash.isBlockHash(block)) {
1760
+ const initialBlockHash = await this.#getInitialHeaderHash();
1761
+ if (block.equals(initialBlockHash)) {
1762
+ return BlockNumber.ZERO;
1763
+ }
1764
+ const header = await this.blockSource.getBlockHeaderByHash(block);
1765
+ if (!header) {
1766
+ throw new Error(`Block hash ${block.toString()} not found.`);
1767
+ }
1768
+ return header.getBlockNumber();
1633
1769
  }
1770
+ return block as BlockNumber;
1634
1771
  }
1635
1772
 
1636
1773
  /**