@aztec/aztec-node 0.0.1-commit.96dac018d → 0.0.1-commit.9badcec54

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.
@@ -372,19 +372,21 @@ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
372
372
  }
373
373
  var _dec, _initProto;
374
374
  import { createArchiver } from '@aztec/archiver';
375
- import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
375
+ import { BBCircuitVerifier, BatchChonkVerifier, QueuedIVCVerifier } from '@aztec/bb-prover';
376
+ import { TestCircuitVerifier } from '@aztec/bb-prover/test';
376
377
  import { createBlobClientWithFileStores } from '@aztec/blob-client/client';
377
378
  import { Blob } from '@aztec/blob-lib';
378
379
  import { EpochCache } from '@aztec/epoch-cache';
379
380
  import { createEthereumChain } from '@aztec/ethereum/chain';
380
- import { getPublicClient } from '@aztec/ethereum/client';
381
+ import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
381
382
  import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
382
- import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
383
- import { compactArray, pick, unique } from '@aztec/foundation/collection';
383
+ import { BlockNumber } from '@aztec/foundation/branded-types';
384
+ import { chunkBy, compactArray, pick, unique } from '@aztec/foundation/collection';
384
385
  import { Fr } from '@aztec/foundation/curves/bn254';
385
386
  import { EthAddress } from '@aztec/foundation/eth-address';
386
387
  import { BadRequestError } from '@aztec/foundation/json-rpc';
387
388
  import { createLogger } from '@aztec/foundation/log';
389
+ import { retryUntil } from '@aztec/foundation/retry';
388
390
  import { count } from '@aztec/foundation/string';
389
391
  import { DateProvider, Timer } from '@aztec/foundation/timer';
390
392
  import { MembershipWitness } from '@aztec/foundation/trees';
@@ -395,7 +397,7 @@ import { createP2PClient, createTxValidatorForAcceptingTxsOverRPC, getDefaultAll
395
397
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
396
398
  import { createProverNode } from '@aztec/prover-node';
397
399
  import { createKeyStoreForProver } from '@aztec/prover-node/config';
398
- import { GlobalVariableBuilder, SequencerClient } from '@aztec/sequencer-client';
400
+ import { FeeProviderImpl, GlobalVariableBuilder, SequencerClient } from '@aztec/sequencer-client';
399
401
  import { PublicProcessorFactory } from '@aztec/simulator/server';
400
402
  import { AttestationsBlockWatcher, EpochPruneWatcher, createSlasher } from '@aztec/slasher';
401
403
  import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
@@ -407,14 +409,13 @@ import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
407
409
  import { tryStop } from '@aztec/stdlib/interfaces/server';
408
410
  import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
409
411
  import { InboxLeaf } from '@aztec/stdlib/messaging';
410
- import { P2PClientType } from '@aztec/stdlib/p2p';
411
412
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
412
413
  import { PublicSimulationOutput, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
413
414
  import { getPackageVersion } from '@aztec/stdlib/update-checker';
414
415
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
415
- import { FullNodeCheckpointsBuilder as CheckpointsBuilder, FullNodeCheckpointsBuilder, NodeKeystoreAdapter, ValidatorClient, createBlockProposalHandler, createValidatorClient } from '@aztec/validator-client';
416
+ import { FullNodeCheckpointsBuilder as CheckpointsBuilder, FullNodeCheckpointsBuilder, NodeKeystoreAdapter, ValidatorClient, createProposalHandler, createValidatorClient } from '@aztec/validator-client';
416
417
  import { createWorldStateSynchronizer } from '@aztec/world-state';
417
- import { createPublicClient, fallback, http } from 'viem';
418
+ import { createPublicClient } from 'viem';
418
419
  import { createSentinel } from '../sentinel/factory.js';
419
420
  import { createKeyStoreForValidator } from './config.js';
420
421
  import { NodeMetrics } from './node_metrics.js';
@@ -439,9 +440,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
439
440
  l1ChainId;
440
441
  version;
441
442
  globalVariableBuilder;
443
+ feeProvider;
442
444
  epochCache;
443
445
  packageVersion;
444
- proofVerifier;
446
+ peerProofVerifier;
447
+ rpcProofVerifier;
445
448
  telemetry;
446
449
  log;
447
450
  blobClient;
@@ -462,7 +465,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
462
465
  // Prevent two snapshot operations to happen simultaneously
463
466
  isUploadingSnapshot;
464
467
  tracer;
465
- constructor(config, p2pClient, blockSource, logsSource, contractDataSource, l1ToL2MessageSource, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, epochPruneWatcher, l1ChainId, version, globalVariableBuilder, epochCache, packageVersion, proofVerifier, telemetry = getTelemetryClient(), log = createLogger('node'), blobClient, validatorClient, keyStoreManager, debugLogStore = new NullDebugLogStore()){
468
+ constructor(config, p2pClient, blockSource, logsSource, contractDataSource, l1ToL2MessageSource, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, epochPruneWatcher, l1ChainId, version, globalVariableBuilder, feeProvider, epochCache, packageVersion, peerProofVerifier, rpcProofVerifier, telemetry = getTelemetryClient(), log = createLogger('node'), blobClient, validatorClient, keyStoreManager, debugLogStore = new NullDebugLogStore()){
466
469
  this.config = config;
467
470
  this.p2pClient = p2pClient;
468
471
  this.blockSource = blockSource;
@@ -478,9 +481,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
478
481
  this.l1ChainId = l1ChainId;
479
482
  this.version = version;
480
483
  this.globalVariableBuilder = globalVariableBuilder;
484
+ this.feeProvider = feeProvider;
481
485
  this.epochCache = epochCache;
482
486
  this.packageVersion = packageVersion;
483
- this.proofVerifier = proofVerifier;
487
+ this.peerProofVerifier = peerProofVerifier;
488
+ this.rpcProofVerifier = rpcProofVerifier;
484
489
  this.telemetry = telemetry;
485
490
  this.log = log;
486
491
  this.blobClient = blobClient;
@@ -500,6 +505,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
500
505
  throw new Error('debugLogStore should never be enabled when realProofs are set');
501
506
  }
502
507
  }
508
+ /** @internal Exposed for testing — returns the RPC proof verifier. */ getProofVerifier() {
509
+ return this.rpcProofVerifier;
510
+ }
503
511
  async getWorldStateSyncStatus() {
504
512
  const status = await this.worldStateSynchronizer.status();
505
513
  return status.syncSummary;
@@ -560,9 +568,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
560
568
  }
561
569
  const publicClient = createPublicClient({
562
570
  chain: ethereumChain.chainInfo,
563
- transport: fallback(config.l1RpcUrls.map((url)=>http(url, {
564
- batch: false
565
- }))),
571
+ transport: makeL1HttpTransport(config.l1RpcUrls, {
572
+ timeout: config.l1HttpTimeoutMS
573
+ }),
566
574
  pollingInterval: config.viemPollingIntervalMS
567
575
  });
568
576
  const l1ContractsAddresses = await RegistryContract.collectAddresses(publicClient, config.l1Contracts.registryAddress, config.rollupVersion ?? 'canonical');
@@ -572,10 +580,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
572
580
  ...l1ContractsAddresses
573
581
  };
574
582
  const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
575
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
583
+ const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
576
584
  rollupContract.getL1GenesisTime(),
577
585
  rollupContract.getSlotDuration(),
578
- rollupContract.getVersion()
586
+ rollupContract.getVersion(),
587
+ rollupContract.getManaLimit().then(Number)
579
588
  ]);
580
589
  config.rollupVersion ??= Number(rollupVersionFromRollup);
581
590
  if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
@@ -596,8 +605,18 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
596
605
  blockUntilSync: !config.skipArchiverInitialSync
597
606
  });
598
607
  // now create the merkle trees and the world state synchronizer
599
- const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.prefilledPublicData, telemetry);
600
- const circuitVerifier = config.realProofs || config.debugForceTxProofVerification ? await BBCircuitVerifier.new(config) : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
608
+ const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.genesis, telemetry);
609
+ const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
610
+ let peerProofVerifier;
611
+ let rpcProofVerifier;
612
+ if (useRealVerifiers) {
613
+ peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
614
+ const rpcVerifier = await BBCircuitVerifier.new(config);
615
+ rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
616
+ } else {
617
+ peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
618
+ rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
619
+ }
601
620
  let debugLogStore;
602
621
  if (!config.realProofs) {
603
622
  log.warn(`Aztec node is accepting fake proofs`);
@@ -606,83 +625,109 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
606
625
  } else {
607
626
  debugLogStore = new NullDebugLogStore();
608
627
  }
609
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
628
+ const proverOnly = config.enableProverNode && config.disableValidator;
629
+ if (proverOnly) {
630
+ log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
631
+ }
610
632
  // create the tx pool and the p2p client, which will need the l2 block source
611
- const p2pClient = await createP2PClient(P2PClientType.Full, config, archiver, proofVerifier, worldStateSynchronizer, epochCache, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
612
- // We should really not be modifying the config object
613
- config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
614
- // Create FullNodeCheckpointsBuilder for validator and non-validator block proposal handling
633
+ const p2pClient = await createP2PClient(config, archiver, peerProofVerifier, worldStateSynchronizer, epochCache, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
634
+ // We'll accumulate sentinel watchers here
635
+ const watchers = [];
636
+ // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
637
+ // Override maxTxsPerCheckpoint with the validator-specific limit if set.
615
638
  const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder({
616
639
  ...config,
617
640
  l1GenesisTime,
618
- slotDuration: Number(slotDuration)
641
+ slotDuration: Number(slotDuration),
642
+ rollupManaLimit,
643
+ maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint
619
644
  }, worldStateSynchronizer, archiver, dateProvider, telemetry);
620
- // We'll accumulate sentinel watchers here
621
- const watchers = [];
622
- // Create validator client if required
623
- const validatorClient = await createValidatorClient(config, {
624
- checkpointsBuilder: validatorCheckpointsBuilder,
625
- worldState: worldStateSynchronizer,
626
- p2pClient,
627
- telemetry,
628
- dateProvider,
629
- epochCache,
630
- blockSource: archiver,
631
- l1ToL2MessageSource: archiver,
632
- keyStoreManager,
633
- blobClient
634
- });
635
- // If we have a validator client, register it as a source of offenses for the slasher,
636
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
637
- // like attestations or auths will fail.
638
- if (validatorClient) {
639
- watchers.push(validatorClient);
640
- if (!options.dontStartSequencer) {
641
- await validatorClient.registerHandlers();
645
+ let validatorClient;
646
+ if (!proverOnly) {
647
+ // Create validator client if required
648
+ validatorClient = await createValidatorClient(config, {
649
+ checkpointsBuilder: validatorCheckpointsBuilder,
650
+ worldState: worldStateSynchronizer,
651
+ p2pClient,
652
+ telemetry,
653
+ dateProvider,
654
+ epochCache,
655
+ blockSource: archiver,
656
+ l1ToL2MessageSource: archiver,
657
+ keyStoreManager,
658
+ blobClient,
659
+ slashingProtectionDb: deps.slashingProtectionDb
660
+ });
661
+ // If we have a validator client, register it as a source of offenses for the slasher,
662
+ // and have it register callbacks on the p2p client *before* we start it, otherwise messages
663
+ // like attestations or auths will fail.
664
+ if (validatorClient) {
665
+ watchers.push(validatorClient);
666
+ const vc = validatorClient;
667
+ const getValidatorAddresses = ()=>vc.getValidatorAddresses().map((a)=>a.toString());
668
+ validatorClient.getProposalHandler().register(p2pClient, true, archiver, getValidatorAddresses);
669
+ if (!options.dontStartSequencer) {
670
+ await validatorClient.registerHandlers();
671
+ }
642
672
  }
643
673
  }
644
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
645
- // create a BlockProposalHandler to reexecute block proposals for monitoring
646
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
647
- log.info('Setting up block proposal reexecution for monitoring');
648
- createBlockProposalHandler(config, {
674
+ // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
675
+ // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
676
+ // while non-reexecution is used for validating the proposals and collecting their txs.
677
+ // Checkpoint proposals rebuild blobs if the blob client can upload blobs.
678
+ if (!validatorClient) {
679
+ const reexecute = !!config.alwaysReexecuteBlockProposals;
680
+ log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
681
+ createProposalHandler(config, {
649
682
  checkpointsBuilder: validatorCheckpointsBuilder,
650
683
  worldState: worldStateSynchronizer,
651
684
  epochCache,
652
685
  blockSource: archiver,
653
686
  l1ToL2MessageSource: archiver,
654
687
  p2pClient,
688
+ blobClient,
655
689
  dateProvider,
656
690
  telemetry
657
- }).registerForReexecution(p2pClient);
691
+ }).register(p2pClient, reexecute, archiver);
658
692
  }
659
693
  // Start world state and wait for it to sync to the archiver.
660
694
  await worldStateSynchronizer.start();
661
695
  // Start p2p. Note that it depends on world state to be running.
662
696
  await p2pClient.start();
663
- const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
664
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
665
- watchers.push(validatorsSentinel);
666
- }
697
+ let validatorsSentinel;
667
698
  let epochPruneWatcher;
668
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
669
- epochPruneWatcher = new EpochPruneWatcher(archiver, archiver, epochCache, p2pClient.getTxProvider(), validatorCheckpointsBuilder, config);
670
- watchers.push(epochPruneWatcher);
671
- }
672
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
673
699
  let attestationsBlockWatcher;
674
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
675
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
676
- watchers.push(attestationsBlockWatcher);
700
+ if (!proverOnly) {
701
+ validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
702
+ if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
703
+ watchers.push(validatorsSentinel);
704
+ }
705
+ if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
706
+ epochPruneWatcher = new EpochPruneWatcher(archiver, archiver, epochCache, p2pClient.getTxProvider(), validatorCheckpointsBuilder, config);
707
+ watchers.push(epochPruneWatcher);
708
+ }
709
+ // We assume we want to slash for invalid attestations unless all max penalties are set to 0
710
+ if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
711
+ attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
712
+ watchers.push(attestationsBlockWatcher);
713
+ }
677
714
  }
678
715
  // Start p2p-related services once the archiver has completed sync
679
716
  void archiver.waitForInitialSync().then(async ()=>{
680
- await p2pClient.start();
681
717
  await validatorsSentinel?.start();
682
718
  await epochPruneWatcher?.start();
683
719
  await attestationsBlockWatcher?.start();
684
720
  log.info(`All p2p services started`);
685
721
  }).catch((err)=>log.error('Failed to start p2p services after archiver sync', err));
722
+ const globalVariableBuilderConfig = {
723
+ l1Contracts: config.l1Contracts,
724
+ ethereumSlotDuration: config.ethereumSlotDuration,
725
+ rollupVersion: BigInt(config.rollupVersion),
726
+ l1GenesisTime,
727
+ slotDuration: Number(slotDuration)
728
+ };
729
+ const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, globalVariableBuilderConfig);
730
+ const feeProvider = new FeeProviderImpl(dateProvider, publicClient, globalVariableBuilderConfig);
686
731
  // Validator enabled, create/start relevant service
687
732
  let sequencer;
688
733
  let slasherClient;
@@ -709,16 +754,34 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
709
754
  dateProvider,
710
755
  kzg: Blob.getViemKzgInstance()
711
756
  });
757
+ // Create a funder L1TxUtils from the keystore funding account (if configured)
758
+ const fundingSigner = keyStoreManager?.createFundingSigner();
759
+ let funderL1TxUtils;
760
+ if (fundingSigner) {
761
+ const [funder] = await createL1TxUtilsFromSigners(publicClient, [
762
+ fundingSigner
763
+ ], {
764
+ ...config,
765
+ scope: 'sequencer'
766
+ }, {
767
+ telemetry,
768
+ logger: log.createChild('l1-tx-utils:funder'),
769
+ dateProvider
770
+ });
771
+ funderL1TxUtils = funder;
772
+ }
712
773
  // Create and start the sequencer client
713
774
  const checkpointsBuilder = new CheckpointsBuilder({
714
775
  ...config,
715
776
  l1GenesisTime,
716
- slotDuration: Number(slotDuration)
777
+ slotDuration: Number(slotDuration),
778
+ rollupManaLimit
717
779
  }, worldStateSynchronizer, archiver, dateProvider, telemetry, debugLogStore);
718
780
  sequencer = await SequencerClient.new(config, {
719
781
  ...deps,
720
782
  epochCache,
721
783
  l1TxUtils,
784
+ funderL1TxUtils,
722
785
  validatorClient,
723
786
  p2pClient,
724
787
  worldStateSynchronizer,
@@ -729,7 +792,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
729
792
  telemetry,
730
793
  dateProvider,
731
794
  blobClient,
732
- nodeKeyStore: keyStoreManager
795
+ nodeKeyStore: keyStoreManager,
796
+ globalVariableBuilder
733
797
  });
734
798
  }
735
799
  if (!options.dontStartSequencer && sequencer) {
@@ -759,13 +823,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
759
823
  log.info(`Prover node subsystem created but not started`);
760
824
  }
761
825
  }
762
- const globalVariableBuilder = new GlobalVariableBuilder({
763
- ...config,
764
- rollupVersion: BigInt(config.rollupVersion),
765
- l1GenesisTime,
766
- slotDuration: Number(slotDuration)
767
- });
768
- const node = new AztecNodeService(config, p2pClient, archiver, archiver, archiver, archiver, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, epochPruneWatcher, ethereumChain.chainInfo.id, config.rollupVersion, globalVariableBuilder, epochCache, packageVersion, proofVerifier, telemetry, log, blobClient, validatorClient, keyStoreManager, debugLogStore);
826
+ const node = new AztecNodeService(config, p2pClient, archiver, archiver, archiver, archiver, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, epochPruneWatcher, ethereumChain.chainInfo.id, config.rollupVersion, globalVariableBuilder, feeProvider, epochCache, packageVersion, peerProofVerifier, rpcProofVerifier, telemetry, log, blobClient, validatorClient, keyStoreManager, debugLogStore);
769
827
  return node;
770
828
  }
771
829
  /**
@@ -796,7 +854,10 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
796
854
  return Promise.resolve(this.p2pClient.getEnr()?.encodeTxt());
797
855
  }
798
856
  async getAllowedPublicSetup() {
799
- return this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
857
+ return [
858
+ ...await getDefaultAllowedSetupFunctions(),
859
+ ...this.config.txPublicSetupAllowListExtend ?? []
860
+ ];
800
861
  }
801
862
  /**
802
863
  * Method to determine if the node is ready to accept transactions.
@@ -874,11 +935,14 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
874
935
  async getCheckpointedBlocks(from, limit) {
875
936
  return await this.blockSource.getCheckpointedBlocks(from, limit) ?? [];
876
937
  }
877
- /**
878
- * Method to fetch the current min L2 fees.
879
- * @returns The current min L2 fees.
880
- */ async getCurrentMinFees() {
881
- return await this.globalVariableBuilder.getCurrentMinFees();
938
+ getCheckpointsDataForEpoch(epochNumber) {
939
+ return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
940
+ }
941
+ async getCurrentMinFees() {
942
+ return await this.feeProvider.getCurrentMinFees();
943
+ }
944
+ /** Returns predicted min fees for the current slot and next N slots. */ async getPredictedMinFees(manaUsage) {
945
+ return await this.feeProvider.getPredictedMinFees(manaUsage);
882
946
  }
883
947
  async getMaxPriorityFees() {
884
948
  for await (const tx of this.p2pClient.iteratePendingTxs()){
@@ -901,6 +965,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
901
965
  async getCheckpointedBlockNumber() {
902
966
  return await this.blockSource.getCheckpointedL2BlockNumber();
903
967
  }
968
+ getCheckpointNumber() {
969
+ return this.blockSource.getCheckpointNumber();
970
+ }
904
971
  /**
905
972
  * Method to fetch the version of the package.
906
973
  * @returns The node package version
@@ -926,28 +993,36 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
926
993
  return this.contractDataSource.getContract(address);
927
994
  }
928
995
  async getPrivateLogsByTags(tags, page, referenceBlock) {
996
+ let upToBlockNumber;
929
997
  if (referenceBlock) {
930
998
  const initialBlockHash = await this.#getInitialHeaderHash();
931
- if (!referenceBlock.equals(initialBlockHash)) {
999
+ if (referenceBlock.equals(initialBlockHash)) {
1000
+ upToBlockNumber = BlockNumber(0);
1001
+ } else {
932
1002
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
933
1003
  if (!header) {
934
1004
  throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
935
1005
  }
1006
+ upToBlockNumber = header.globalVariables.blockNumber;
936
1007
  }
937
1008
  }
938
- return this.logsSource.getPrivateLogsByTags(tags, page);
1009
+ return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
939
1010
  }
940
1011
  async getPublicLogsByTagsFromContract(contractAddress, tags, page, referenceBlock) {
1012
+ let upToBlockNumber;
941
1013
  if (referenceBlock) {
942
1014
  const initialBlockHash = await this.#getInitialHeaderHash();
943
- if (!referenceBlock.equals(initialBlockHash)) {
1015
+ if (referenceBlock.equals(initialBlockHash)) {
1016
+ upToBlockNumber = BlockNumber(0);
1017
+ } else {
944
1018
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
945
1019
  if (!header) {
946
1020
  throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
947
1021
  }
1022
+ upToBlockNumber = header.globalVariables.blockNumber;
948
1023
  }
949
1024
  }
950
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
1025
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
951
1026
  }
952
1027
  /**
953
1028
  * Gets public logs based on the provided filter.
@@ -982,8 +1057,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
982
1057
  throw new Error(`Invalid tx: ${reason}`);
983
1058
  }
984
1059
  await this.p2pClient.sendTx(tx);
985
- this.metrics.receivedTx(timer.ms(), true);
986
- this.log.info(`Received tx ${txHash}`, {
1060
+ const duration = timer.ms();
1061
+ this.metrics.receivedTx(duration, true);
1062
+ this.log.info(`Received tx ${txHash} in ${duration}ms`, {
987
1063
  txHash
988
1064
  });
989
1065
  }
@@ -1019,7 +1095,10 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1019
1095
  await tryStop(this.validatorsSentinel);
1020
1096
  await tryStop(this.epochPruneWatcher);
1021
1097
  await tryStop(this.slasherClient);
1022
- await tryStop(this.proofVerifier);
1098
+ await Promise.all([
1099
+ tryStop(this.peerProofVerifier),
1100
+ tryStop(this.rpcProofVerifier)
1101
+ ]);
1023
1102
  await tryStop(this.sequencer);
1024
1103
  await tryStop(this.proverNode);
1025
1104
  await tryStop(this.p2pClient);
@@ -1061,70 +1140,82 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1061
1140
  return compactArray(await Promise.all(txHashes.map((txHash)=>this.getTxByHash(txHash))));
1062
1141
  }
1063
1142
  async findLeavesIndexes(referenceBlock, treeId, leafValues) {
1064
- const committedDb = await this.#getWorldState(referenceBlock);
1143
+ const committedDb = await this.getWorldState(referenceBlock);
1065
1144
  const maybeIndices = await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
1066
- // We filter out undefined values
1067
- const indices = maybeIndices.filter((x)=>x !== undefined);
1068
- // Now we find the block numbers for the indices
1069
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
1070
- // If any of the block numbers are undefined, we throw an error.
1071
- for(let i = 0; i < indices.length; i++){
1072
- if (blockNumbers[i] === undefined) {
1073
- throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
1145
+ // Filter out undefined values to query block numbers only for found leaves
1146
+ const definedIndices = maybeIndices.filter((x)=>x !== undefined);
1147
+ // Now we find the block numbers for the defined indices
1148
+ const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
1149
+ // Build a map from leaf index to block number
1150
+ const indexToBlockNumber = new Map();
1151
+ for(let i = 0; i < definedIndices.length; i++){
1152
+ const blockNumber = blockNumbers[i];
1153
+ if (blockNumber === undefined) {
1154
+ throw new Error(`Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`);
1074
1155
  }
1156
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
1075
1157
  }
1076
1158
  // Get unique block numbers in order to optimize num calls to getLeafValue function.
1077
1159
  const uniqueBlockNumbers = [
1078
- ...new Set(blockNumbers.filter((x)=>x !== undefined))
1160
+ ...new Set(indexToBlockNumber.values())
1079
1161
  ];
1080
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
1081
- // (note that block number corresponds to the leaf index in the archive tree).
1162
+ // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
1082
1163
  const blockHashes = await Promise.all(uniqueBlockNumbers.map((blockNumber)=>{
1083
1164
  return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1084
1165
  }));
1085
- // If any of the block hashes are undefined, we throw an error.
1166
+ // Build a map from block number to block hash
1167
+ const blockNumberToHash = new Map();
1086
1168
  for(let i = 0; i < uniqueBlockNumbers.length; i++){
1087
- if (blockHashes[i] === undefined) {
1169
+ const blockHash = blockHashes[i];
1170
+ if (blockHash === undefined) {
1088
1171
  throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
1089
1172
  }
1173
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
1090
1174
  }
1091
1175
  // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
1092
- return maybeIndices.map((index, i)=>{
1176
+ return maybeIndices.map((index)=>{
1093
1177
  if (index === undefined) {
1094
1178
  return undefined;
1095
1179
  }
1096
- const blockNumber = blockNumbers[i];
1180
+ const blockNumber = indexToBlockNumber.get(index);
1097
1181
  if (blockNumber === undefined) {
1098
- return undefined;
1182
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1099
1183
  }
1100
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
1101
- const blockHash = blockHashes[blockHashIndex];
1102
- if (!blockHash) {
1103
- return undefined;
1184
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
1185
+ if (l2BlockHash === undefined) {
1186
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
1104
1187
  }
1105
1188
  return {
1106
- l2BlockNumber: BlockNumber(Number(blockNumber)),
1107
- l2BlockHash: new BlockHash(blockHash),
1189
+ l2BlockNumber: blockNumber,
1190
+ l2BlockHash,
1108
1191
  data: index
1109
1192
  };
1110
1193
  });
1111
1194
  }
1112
1195
  async getBlockHashMembershipWitness(referenceBlock, blockHash) {
1113
- const committedDb = await this.#getWorldState(referenceBlock);
1196
+ // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
1197
+ // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1198
+ // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1199
+ const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1200
+ if (referenceBlockNumber === BlockNumber.ZERO) {
1201
+ // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
1202
+ return undefined;
1203
+ }
1204
+ const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
1114
1205
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE, [
1115
1206
  blockHash
1116
1207
  ]);
1117
1208
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1118
1209
  }
1119
1210
  async getNoteHashMembershipWitness(referenceBlock, noteHash) {
1120
- const committedDb = await this.#getWorldState(referenceBlock);
1211
+ const committedDb = await this.getWorldState(referenceBlock);
1121
1212
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE, [
1122
1213
  noteHash
1123
1214
  ]);
1124
1215
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1125
1216
  }
1126
1217
  async getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
1127
- const db = await this.#getWorldState(referenceBlock);
1218
+ const db = await this.getWorldState(referenceBlock);
1128
1219
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
1129
1220
  l1ToL2Message
1130
1221
  ]);
@@ -1137,9 +1228,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1137
1228
  witness.path
1138
1229
  ];
1139
1230
  }
1140
- async getL1ToL2MessageBlock(l1ToL2Message) {
1231
+ async getL1ToL2MessageCheckpoint(l1ToL2Message) {
1141
1232
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1142
- return messageIndex ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex)) : undefined;
1233
+ return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1143
1234
  }
1144
1235
  /**
1145
1236
  * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
@@ -1156,23 +1247,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1156
1247
  */ async getL2ToL1Messages(epoch) {
1157
1248
  // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1158
1249
  const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1159
- const blocksInCheckpoints = [];
1160
- let previousSlotNumber = SlotNumber.ZERO;
1161
- let checkpointIndex = -1;
1162
- for (const checkpointedBlock of checkpointedBlocks){
1163
- const block = checkpointedBlock.block;
1164
- const slotNumber = block.header.globalVariables.slotNumber;
1165
- if (slotNumber !== previousSlotNumber) {
1166
- checkpointIndex++;
1167
- blocksInCheckpoints.push([]);
1168
- previousSlotNumber = slotNumber;
1169
- }
1170
- blocksInCheckpoints[checkpointIndex].push(block);
1171
- }
1250
+ const blocksInCheckpoints = chunkBy(checkpointedBlocks, (cb)=>cb.block.header.globalVariables.slotNumber).map((group)=>group.map((cb)=>cb.block));
1172
1251
  return blocksInCheckpoints.map((blocks)=>blocks.map((block)=>block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs)));
1173
1252
  }
1174
1253
  async getNullifierMembershipWitness(referenceBlock, nullifier) {
1175
- const db = await this.#getWorldState(referenceBlock);
1254
+ const db = await this.getWorldState(referenceBlock);
1176
1255
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [
1177
1256
  nullifier.toBuffer()
1178
1257
  ]);
@@ -1186,36 +1265,22 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1186
1265
  }
1187
1266
  return new NullifierMembershipWitness(index, leafPreimage, path);
1188
1267
  }
1189
- /**
1190
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1191
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1192
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1193
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1194
- * @returns The low nullifier membership witness (if found).
1195
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1196
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1197
- * we are trying to prove non-inclusion for.
1198
- *
1199
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1200
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1201
- * index of the nullifier itself when it already exists in the tree.
1202
- * TODO: This is a confusing behavior and we should eventually address that.
1203
- */ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1204
- const committedDb = await this.#getWorldState(referenceBlock);
1268
+ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1269
+ const committedDb = await this.getWorldState(referenceBlock);
1205
1270
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1206
1271
  if (!findResult) {
1207
1272
  return undefined;
1208
1273
  }
1209
1274
  const { index, alreadyPresent } = findResult;
1210
1275
  if (alreadyPresent) {
1211
- this.log.warn(`Nullifier ${nullifier.toBigInt()} already exists in the tree`);
1276
+ throw new Error(`Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`);
1212
1277
  }
1213
1278
  const preimageData = await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1214
1279
  const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1215
1280
  return new NullifierMembershipWitness(BigInt(index), preimageData, siblingPath);
1216
1281
  }
1217
1282
  async getPublicDataWitness(referenceBlock, leafSlot) {
1218
- const committedDb = await this.#getWorldState(referenceBlock);
1283
+ const committedDb = await this.getWorldState(referenceBlock);
1219
1284
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1220
1285
  if (!lowLeafResult) {
1221
1286
  return undefined;
@@ -1226,7 +1291,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1226
1291
  }
1227
1292
  }
1228
1293
  async getPublicStorageAt(referenceBlock, contract, slot) {
1229
- const committedDb = await this.#getWorldState(referenceBlock);
1294
+ const committedDb = await this.getWorldState(referenceBlock);
1230
1295
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1231
1296
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1232
1297
  if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
@@ -1305,7 +1370,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1305
1370
  });
1306
1371
  const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1307
1372
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1308
- const [processedTxs, failedTxs, _usedTxs, returns, _blobFields, debugLogs] = await processor.process([
1373
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([
1309
1374
  tx
1310
1375
  ]);
1311
1376
  // REFACTOR: Consider returning the error rather than throwing
@@ -1323,19 +1388,26 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1323
1388
  }
1324
1389
  async isValidTx(tx, { isSimulation, skipFeeEnforcement } = {}) {
1325
1390
  const db = this.worldStateSynchronizer.getCommitted();
1326
- const verifier = isSimulation ? undefined : this.proofVerifier;
1391
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1327
1392
  // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1328
1393
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1329
1394
  const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
1395
+ const l1Constants = await this.blockSource.getL1Constants();
1330
1396
  const validator = createTxValidatorForAcceptingTxsOverRPC(db, this.contractDataSource, verifier, {
1331
1397
  timestamp: nextSlotTimestamp,
1332
1398
  blockNumber,
1333
1399
  l1ChainId: this.l1ChainId,
1334
1400
  rollupVersion: this.version,
1335
- setupAllowList: this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions(),
1401
+ setupAllowList: [
1402
+ ...await getDefaultAllowedSetupFunctions(),
1403
+ ...this.config.txPublicSetupAllowListExtend ?? []
1404
+ ],
1336
1405
  gasFees: await this.getCurrentMinFees(),
1337
1406
  skipFeeEnforcement,
1338
- txsPermitted: !this.config.disableTransactions
1407
+ txsPermitted: !this.config.disableTransactions,
1408
+ rollupManaLimit: l1Constants.rollupManaLimit,
1409
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1410
+ maxBlockDAGas: this.config.validateMaxDABlockGas
1339
1411
  }, this.log.getBindings());
1340
1412
  return await validator.validateTx(tx);
1341
1413
  }
@@ -1358,7 +1430,18 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1358
1430
  archiver.updateConfig(config);
1359
1431
  }
1360
1432
  if (newConfig.realProofs !== this.config.realProofs) {
1361
- this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
1433
+ await Promise.all([
1434
+ tryStop(this.peerProofVerifier),
1435
+ tryStop(this.rpcProofVerifier)
1436
+ ]);
1437
+ if (newConfig.realProofs) {
1438
+ this.peerProofVerifier = await BatchChonkVerifier.new(newConfig, newConfig.bbChonkVerifyMaxBatch, 'peer');
1439
+ const rpcVerifier = await BBCircuitVerifier.new(newConfig);
1440
+ this.rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, newConfig.numConcurrentIVCVerifiers);
1441
+ } else {
1442
+ this.peerProofVerifier = new TestCircuitVerifier();
1443
+ this.rpcProofVerifier = new TestCircuitVerifier();
1444
+ }
1362
1445
  }
1363
1446
  this.config = newConfig;
1364
1447
  }
@@ -1418,7 +1501,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1418
1501
  });
1419
1502
  return Promise.resolve();
1420
1503
  }
1421
- async rollbackTo(targetBlock, force) {
1504
+ async rollbackTo(targetBlock, force, resumeSync = true) {
1422
1505
  const archiver = this.blockSource;
1423
1506
  if (!('rollbackTo' in archiver)) {
1424
1507
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1446,9 +1529,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1446
1529
  this.log.error(`Error during rollback`, err);
1447
1530
  throw err;
1448
1531
  } finally{
1449
- this.log.info(`Resuming world state and archiver sync.`);
1450
- this.worldStateSynchronizer.resumeSync();
1451
- archiver.resume();
1532
+ if (resumeSync) {
1533
+ this.log.info(`Resuming world state and archiver sync.`);
1534
+ this.worldStateSynchronizer.resumeSync();
1535
+ archiver.resume();
1536
+ } else {
1537
+ this.log.info(`Sync left paused after rollback (resumeSync=false).`);
1538
+ }
1452
1539
  }
1453
1540
  }
1454
1541
  async pauseSync() {
@@ -1462,18 +1549,12 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1462
1549
  this.blockSource.resume();
1463
1550
  return Promise.resolve();
1464
1551
  }
1465
- getSlashPayloads() {
1466
- if (!this.slasherClient) {
1467
- throw new Error(`Slasher client not enabled`);
1468
- }
1469
- return this.slasherClient.getSlashPayloads();
1470
- }
1471
1552
  getSlashOffenses(round) {
1472
1553
  if (!this.slasherClient) {
1473
1554
  throw new Error(`Slasher client not enabled`);
1474
1555
  }
1475
1556
  if (round === 'all') {
1476
- return this.slasherClient.getPendingOffenses();
1557
+ return this.slasherClient.getOffenses();
1477
1558
  } else {
1478
1559
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1479
1560
  }
@@ -1545,6 +1626,33 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1545
1626
  this.keyStoreManager = newManager;
1546
1627
  this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1547
1628
  }
1629
+ async mineBlock() {
1630
+ if (!this.sequencer) {
1631
+ throw new BadRequestError('Cannot mine block: no sequencer is running');
1632
+ }
1633
+ const currentBlockNumber = await this.getBlockNumber();
1634
+ // Use slot duration + 50% buffer as the timeout so this works on running networks too
1635
+ const { slotDuration } = await this.blockSource.getL1Constants();
1636
+ const timeoutSeconds = Math.ceil(slotDuration * 1.5);
1637
+ // Temporarily set minTxsPerBlock to 0 so the sequencer produces a block even with no txs
1638
+ const originalMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock;
1639
+ this.sequencer.updateConfig({
1640
+ minTxsPerBlock: 0
1641
+ });
1642
+ try {
1643
+ // Trigger the sequencer to produce a block immediately
1644
+ void this.sequencer.trigger();
1645
+ // Wait for the new L2 block to appear
1646
+ await retryUntil(async ()=>{
1647
+ const newBlockNumber = await this.getBlockNumber();
1648
+ return newBlockNumber > currentBlockNumber ? true : undefined;
1649
+ }, 'mineBlock', timeoutSeconds, 0.1);
1650
+ } finally{
1651
+ this.sequencer.updateConfig({
1652
+ minTxsPerBlock: originalMinTxsPerBlock
1653
+ });
1654
+ }
1655
+ }
1548
1656
  #getInitialHeaderHash() {
1549
1657
  if (!this.initialHeaderHashPromise) {
1550
1658
  this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
@@ -1555,7 +1663,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1555
1663
  * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1556
1664
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1557
1665
  * @returns An instance of a committed MerkleTreeOperations
1558
- */ async #getWorldState(block) {
1666
+ */ async getWorldState(block) {
1559
1667
  let blockSyncedTo = BlockNumber.ZERO;
1560
1668
  try {
1561
1669
  // Attempt to sync the world state if necessary
@@ -1567,6 +1675,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1567
1675
  this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
1568
1676
  return this.worldStateSynchronizer.getCommitted();
1569
1677
  }
1678
+ // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1679
+ let blockNumber;
1570
1680
  if (BlockHash.isBlockHash(block)) {
1571
1681
  const initialBlockHash = await this.#getInitialHeaderHash();
1572
1682
  if (block.equals(initialBlockHash)) {
@@ -1577,19 +1687,41 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1577
1687
  if (!header) {
1578
1688
  throw new Error(`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.`);
1579
1689
  }
1580
- const blockNumber = header.getBlockNumber();
1581
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1582
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1583
- }
1584
- // Block number provided
1585
- {
1586
- const blockNumber = block;
1587
- if (blockNumber > blockSyncedTo) {
1588
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1690
+ blockNumber = header.getBlockNumber();
1691
+ } else {
1692
+ blockNumber = block;
1693
+ }
1694
+ // Check it's within world state sync range
1695
+ if (blockNumber > blockSyncedTo) {
1696
+ throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1697
+ }
1698
+ this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1699
+ const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
1700
+ // Double-check world-state synced to the same block hash as was requested
1701
+ if (BlockHash.isBlockHash(block)) {
1702
+ const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1703
+ if (!blockHash || !block.equals(blockHash)) {
1704
+ throw new Error(`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.`);
1705
+ }
1706
+ }
1707
+ return snapshot;
1708
+ }
1709
+ /** Resolves a block parameter to a block number. */ async resolveBlockNumber(block) {
1710
+ if (block === 'latest') {
1711
+ return BlockNumber(await this.blockSource.getBlockNumber());
1712
+ }
1713
+ if (BlockHash.isBlockHash(block)) {
1714
+ const initialBlockHash = await this.#getInitialHeaderHash();
1715
+ if (block.equals(initialBlockHash)) {
1716
+ return BlockNumber.ZERO;
1717
+ }
1718
+ const header = await this.blockSource.getBlockHeaderByHash(block);
1719
+ if (!header) {
1720
+ throw new Error(`Block hash ${block.toString()} not found.`);
1589
1721
  }
1590
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1591
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1722
+ return header.getBlockNumber();
1592
1723
  }
1724
+ return block;
1593
1725
  }
1594
1726
  /**
1595
1727
  * Ensure we fully sync the world state