@aztec/aztec-node 0.0.1-commit.684755437 → 0.0.1-commit.69c59a8b3

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';
@@ -411,9 +413,9 @@ import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@az
411
413
  import { PublicSimulationOutput, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
412
414
  import { getPackageVersion } from '@aztec/stdlib/update-checker';
413
415
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
414
- 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';
415
417
  import { createWorldStateSynchronizer } from '@aztec/world-state';
416
- import { createPublicClient, fallback, http } from 'viem';
418
+ import { createPublicClient } from 'viem';
417
419
  import { createSentinel } from '../sentinel/factory.js';
418
420
  import { createKeyStoreForValidator } from './config.js';
419
421
  import { NodeMetrics } from './node_metrics.js';
@@ -438,9 +440,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
438
440
  l1ChainId;
439
441
  version;
440
442
  globalVariableBuilder;
443
+ feeProvider;
441
444
  epochCache;
442
445
  packageVersion;
443
- proofVerifier;
446
+ peerProofVerifier;
447
+ rpcProofVerifier;
444
448
  telemetry;
445
449
  log;
446
450
  blobClient;
@@ -461,7 +465,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
461
465
  // Prevent two snapshot operations to happen simultaneously
462
466
  isUploadingSnapshot;
463
467
  tracer;
464
- 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()){
465
469
  this.config = config;
466
470
  this.p2pClient = p2pClient;
467
471
  this.blockSource = blockSource;
@@ -477,9 +481,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
477
481
  this.l1ChainId = l1ChainId;
478
482
  this.version = version;
479
483
  this.globalVariableBuilder = globalVariableBuilder;
484
+ this.feeProvider = feeProvider;
480
485
  this.epochCache = epochCache;
481
486
  this.packageVersion = packageVersion;
482
- this.proofVerifier = proofVerifier;
487
+ this.peerProofVerifier = peerProofVerifier;
488
+ this.rpcProofVerifier = rpcProofVerifier;
483
489
  this.telemetry = telemetry;
484
490
  this.log = log;
485
491
  this.blobClient = blobClient;
@@ -499,6 +505,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
499
505
  throw new Error('debugLogStore should never be enabled when realProofs are set');
500
506
  }
501
507
  }
508
+ /** @internal Exposed for testing — returns the RPC proof verifier. */ getProofVerifier() {
509
+ return this.rpcProofVerifier;
510
+ }
502
511
  async getWorldStateSyncStatus() {
503
512
  const status = await this.worldStateSynchronizer.status();
504
513
  return status.syncSummary;
@@ -559,9 +568,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
559
568
  }
560
569
  const publicClient = createPublicClient({
561
570
  chain: ethereumChain.chainInfo,
562
- transport: fallback(config.l1RpcUrls.map((url)=>http(url, {
563
- batch: false
564
- }))),
571
+ transport: makeL1HttpTransport(config.l1RpcUrls, {
572
+ timeout: config.l1HttpTimeoutMS
573
+ }),
565
574
  pollingInterval: config.viemPollingIntervalMS
566
575
  });
567
576
  const l1ContractsAddresses = await RegistryContract.collectAddresses(publicClient, config.l1Contracts.registryAddress, config.rollupVersion ?? 'canonical');
@@ -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,13 +625,12 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
606
625
  } else {
607
626
  debugLogStore = new NullDebugLogStore();
608
627
  }
609
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
610
628
  const proverOnly = config.enableProverNode && config.disableValidator;
611
629
  if (proverOnly) {
612
630
  log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
613
631
  }
614
632
  // create the tx pool and the p2p client, which will need the l2 block source
615
- const p2pClient = await createP2PClient(config, archiver, proofVerifier, worldStateSynchronizer, epochCache, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
633
+ const p2pClient = await createP2PClient(config, archiver, peerProofVerifier, worldStateSynchronizer, epochCache, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
616
634
  // We'll accumulate sentinel watchers here
617
635
  const watchers = [];
618
636
  // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
@@ -637,34 +655,40 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
637
655
  blockSource: archiver,
638
656
  l1ToL2MessageSource: archiver,
639
657
  keyStoreManager,
640
- blobClient
658
+ blobClient,
659
+ slashingProtectionDb: deps.slashingProtectionDb
641
660
  });
642
661
  // If we have a validator client, register it as a source of offenses for the slasher,
643
662
  // and have it register callbacks on the p2p client *before* we start it, otherwise messages
644
663
  // like attestations or auths will fail.
645
664
  if (validatorClient) {
646
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);
647
669
  if (!options.dontStartSequencer) {
648
670
  await validatorClient.registerHandlers();
649
671
  }
650
672
  }
651
673
  }
652
- // If there's no validator client, create a BlockProposalHandler to handle block proposals
674
+ // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
653
675
  // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
654
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.
655
678
  if (!validatorClient) {
656
679
  const reexecute = !!config.alwaysReexecuteBlockProposals;
657
- log.info(`Setting up block proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
658
- createBlockProposalHandler(config, {
680
+ log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
681
+ createProposalHandler(config, {
659
682
  checkpointsBuilder: validatorCheckpointsBuilder,
660
683
  worldState: worldStateSynchronizer,
661
684
  epochCache,
662
685
  blockSource: archiver,
663
686
  l1ToL2MessageSource: archiver,
664
687
  p2pClient,
688
+ blobClient,
665
689
  dateProvider,
666
690
  telemetry
667
- }).register(p2pClient, reexecute);
691
+ }).register(p2pClient, reexecute, archiver);
668
692
  }
669
693
  // Start world state and wait for it to sync to the archiver.
670
694
  await worldStateSynchronizer.start();
@@ -690,12 +714,20 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
690
714
  }
691
715
  // Start p2p-related services once the archiver has completed sync
692
716
  void archiver.waitForInitialSync().then(async ()=>{
693
- await p2pClient.start();
694
717
  await validatorsSentinel?.start();
695
718
  await epochPruneWatcher?.start();
696
719
  await attestationsBlockWatcher?.start();
697
720
  log.info(`All p2p services started`);
698
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);
699
731
  // Validator enabled, create/start relevant service
700
732
  let sequencer;
701
733
  let slasherClient;
@@ -722,6 +754,22 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
722
754
  dateProvider,
723
755
  kzg: Blob.getViemKzgInstance()
724
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
+ }
725
773
  // Create and start the sequencer client
726
774
  const checkpointsBuilder = new CheckpointsBuilder({
727
775
  ...config,
@@ -733,6 +781,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
733
781
  ...deps,
734
782
  epochCache,
735
783
  l1TxUtils,
784
+ funderL1TxUtils,
736
785
  validatorClient,
737
786
  p2pClient,
738
787
  worldStateSynchronizer,
@@ -743,7 +792,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
743
792
  telemetry,
744
793
  dateProvider,
745
794
  blobClient,
746
- nodeKeyStore: keyStoreManager
795
+ nodeKeyStore: keyStoreManager,
796
+ globalVariableBuilder
747
797
  });
748
798
  }
749
799
  if (!options.dontStartSequencer && sequencer) {
@@ -773,13 +823,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
773
823
  log.info(`Prover node subsystem created but not started`);
774
824
  }
775
825
  }
776
- const globalVariableBuilder = new GlobalVariableBuilder({
777
- ...config,
778
- rollupVersion: BigInt(config.rollupVersion),
779
- l1GenesisTime,
780
- slotDuration: Number(slotDuration)
781
- });
782
- 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);
783
827
  return node;
784
828
  }
785
829
  /**
@@ -891,11 +935,14 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
891
935
  async getCheckpointedBlocks(from, limit) {
892
936
  return await this.blockSource.getCheckpointedBlocks(from, limit) ?? [];
893
937
  }
894
- /**
895
- * Method to fetch the current min L2 fees.
896
- * @returns The current min L2 fees.
897
- */ async getCurrentMinFees() {
898
- 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);
899
946
  }
900
947
  async getMaxPriorityFees() {
901
948
  for await (const tx of this.p2pClient.iteratePendingTxs()){
@@ -946,28 +993,36 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
946
993
  return this.contractDataSource.getContract(address);
947
994
  }
948
995
  async getPrivateLogsByTags(tags, page, referenceBlock) {
996
+ let upToBlockNumber;
949
997
  if (referenceBlock) {
950
998
  const initialBlockHash = await this.#getInitialHeaderHash();
951
- if (!referenceBlock.equals(initialBlockHash)) {
999
+ if (referenceBlock.equals(initialBlockHash)) {
1000
+ upToBlockNumber = BlockNumber(0);
1001
+ } else {
952
1002
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
953
1003
  if (!header) {
954
1004
  throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
955
1005
  }
1006
+ upToBlockNumber = header.globalVariables.blockNumber;
956
1007
  }
957
1008
  }
958
- return this.logsSource.getPrivateLogsByTags(tags, page);
1009
+ return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
959
1010
  }
960
1011
  async getPublicLogsByTagsFromContract(contractAddress, tags, page, referenceBlock) {
1012
+ let upToBlockNumber;
961
1013
  if (referenceBlock) {
962
1014
  const initialBlockHash = await this.#getInitialHeaderHash();
963
- if (!referenceBlock.equals(initialBlockHash)) {
1015
+ if (referenceBlock.equals(initialBlockHash)) {
1016
+ upToBlockNumber = BlockNumber(0);
1017
+ } else {
964
1018
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
965
1019
  if (!header) {
966
1020
  throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
967
1021
  }
1022
+ upToBlockNumber = header.globalVariables.blockNumber;
968
1023
  }
969
1024
  }
970
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
1025
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
971
1026
  }
972
1027
  /**
973
1028
  * Gets public logs based on the provided filter.
@@ -1040,7 +1095,10 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1040
1095
  await tryStop(this.validatorsSentinel);
1041
1096
  await tryStop(this.epochPruneWatcher);
1042
1097
  await tryStop(this.slasherClient);
1043
- await tryStop(this.proofVerifier);
1098
+ await Promise.all([
1099
+ tryStop(this.peerProofVerifier),
1100
+ tryStop(this.rpcProofVerifier)
1101
+ ]);
1044
1102
  await tryStop(this.sequencer);
1045
1103
  await tryStop(this.proverNode);
1046
1104
  await tryStop(this.p2pClient);
@@ -1082,70 +1140,82 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1082
1140
  return compactArray(await Promise.all(txHashes.map((txHash)=>this.getTxByHash(txHash))));
1083
1141
  }
1084
1142
  async findLeavesIndexes(referenceBlock, treeId, leafValues) {
1085
- const committedDb = await this.#getWorldState(referenceBlock);
1143
+ const committedDb = await this.getWorldState(referenceBlock);
1086
1144
  const maybeIndices = await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
1087
- // We filter out undefined values
1088
- const indices = maybeIndices.filter((x)=>x !== undefined);
1089
- // Now we find the block numbers for the indices
1090
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
1091
- // If any of the block numbers are undefined, we throw an error.
1092
- for(let i = 0; i < indices.length; i++){
1093
- if (blockNumbers[i] === undefined) {
1094
- 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]}`);
1095
1155
  }
1156
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
1096
1157
  }
1097
1158
  // Get unique block numbers in order to optimize num calls to getLeafValue function.
1098
1159
  const uniqueBlockNumbers = [
1099
- ...new Set(blockNumbers.filter((x)=>x !== undefined))
1160
+ ...new Set(indexToBlockNumber.values())
1100
1161
  ];
1101
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
1102
- // (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).
1103
1163
  const blockHashes = await Promise.all(uniqueBlockNumbers.map((blockNumber)=>{
1104
1164
  return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1105
1165
  }));
1106
- // 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();
1107
1168
  for(let i = 0; i < uniqueBlockNumbers.length; i++){
1108
- if (blockHashes[i] === undefined) {
1169
+ const blockHash = blockHashes[i];
1170
+ if (blockHash === undefined) {
1109
1171
  throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
1110
1172
  }
1173
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
1111
1174
  }
1112
1175
  // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
1113
- return maybeIndices.map((index, i)=>{
1176
+ return maybeIndices.map((index)=>{
1114
1177
  if (index === undefined) {
1115
1178
  return undefined;
1116
1179
  }
1117
- const blockNumber = blockNumbers[i];
1180
+ const blockNumber = indexToBlockNumber.get(index);
1118
1181
  if (blockNumber === undefined) {
1119
- return undefined;
1182
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1120
1183
  }
1121
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
1122
- const blockHash = blockHashes[blockHashIndex];
1123
- if (!blockHash) {
1124
- return undefined;
1184
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
1185
+ if (l2BlockHash === undefined) {
1186
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
1125
1187
  }
1126
1188
  return {
1127
- l2BlockNumber: BlockNumber(Number(blockNumber)),
1128
- l2BlockHash: new BlockHash(blockHash),
1189
+ l2BlockNumber: blockNumber,
1190
+ l2BlockHash,
1129
1191
  data: index
1130
1192
  };
1131
1193
  });
1132
1194
  }
1133
1195
  async getBlockHashMembershipWitness(referenceBlock, blockHash) {
1134
- 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));
1135
1205
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE, [
1136
1206
  blockHash
1137
1207
  ]);
1138
1208
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1139
1209
  }
1140
1210
  async getNoteHashMembershipWitness(referenceBlock, noteHash) {
1141
- const committedDb = await this.#getWorldState(referenceBlock);
1211
+ const committedDb = await this.getWorldState(referenceBlock);
1142
1212
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE, [
1143
1213
  noteHash
1144
1214
  ]);
1145
1215
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1146
1216
  }
1147
1217
  async getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
1148
- const db = await this.#getWorldState(referenceBlock);
1218
+ const db = await this.getWorldState(referenceBlock);
1149
1219
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
1150
1220
  l1ToL2Message
1151
1221
  ]);
@@ -1177,23 +1247,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1177
1247
  */ async getL2ToL1Messages(epoch) {
1178
1248
  // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1179
1249
  const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1180
- const blocksInCheckpoints = [];
1181
- let previousSlotNumber = SlotNumber.ZERO;
1182
- let checkpointIndex = -1;
1183
- for (const checkpointedBlock of checkpointedBlocks){
1184
- const block = checkpointedBlock.block;
1185
- const slotNumber = block.header.globalVariables.slotNumber;
1186
- if (slotNumber !== previousSlotNumber) {
1187
- checkpointIndex++;
1188
- blocksInCheckpoints.push([]);
1189
- previousSlotNumber = slotNumber;
1190
- }
1191
- blocksInCheckpoints[checkpointIndex].push(block);
1192
- }
1250
+ const blocksInCheckpoints = chunkBy(checkpointedBlocks, (cb)=>cb.block.header.globalVariables.slotNumber).map((group)=>group.map((cb)=>cb.block));
1193
1251
  return blocksInCheckpoints.map((blocks)=>blocks.map((block)=>block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs)));
1194
1252
  }
1195
1253
  async getNullifierMembershipWitness(referenceBlock, nullifier) {
1196
- const db = await this.#getWorldState(referenceBlock);
1254
+ const db = await this.getWorldState(referenceBlock);
1197
1255
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [
1198
1256
  nullifier.toBuffer()
1199
1257
  ]);
@@ -1207,36 +1265,22 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1207
1265
  }
1208
1266
  return new NullifierMembershipWitness(index, leafPreimage, path);
1209
1267
  }
1210
- /**
1211
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1212
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1213
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1214
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1215
- * @returns The low nullifier membership witness (if found).
1216
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1217
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1218
- * we are trying to prove non-inclusion for.
1219
- *
1220
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1221
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1222
- * index of the nullifier itself when it already exists in the tree.
1223
- * TODO: This is a confusing behavior and we should eventually address that.
1224
- */ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1225
- const committedDb = await this.#getWorldState(referenceBlock);
1268
+ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1269
+ const committedDb = await this.getWorldState(referenceBlock);
1226
1270
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1227
1271
  if (!findResult) {
1228
1272
  return undefined;
1229
1273
  }
1230
1274
  const { index, alreadyPresent } = findResult;
1231
1275
  if (alreadyPresent) {
1232
- 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`);
1233
1277
  }
1234
1278
  const preimageData = await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1235
1279
  const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1236
1280
  return new NullifierMembershipWitness(BigInt(index), preimageData, siblingPath);
1237
1281
  }
1238
1282
  async getPublicDataWitness(referenceBlock, leafSlot) {
1239
- const committedDb = await this.#getWorldState(referenceBlock);
1283
+ const committedDb = await this.getWorldState(referenceBlock);
1240
1284
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1241
1285
  if (!lowLeafResult) {
1242
1286
  return undefined;
@@ -1247,7 +1291,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1247
1291
  }
1248
1292
  }
1249
1293
  async getPublicStorageAt(referenceBlock, contract, slot) {
1250
- const committedDb = await this.#getWorldState(referenceBlock);
1294
+ const committedDb = await this.getWorldState(referenceBlock);
1251
1295
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1252
1296
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1253
1297
  if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
@@ -1344,10 +1388,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1344
1388
  }
1345
1389
  async isValidTx(tx, { isSimulation, skipFeeEnforcement } = {}) {
1346
1390
  const db = this.worldStateSynchronizer.getCommitted();
1347
- const verifier = isSimulation ? undefined : this.proofVerifier;
1391
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1348
1392
  // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1349
1393
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1350
1394
  const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
1395
+ const l1Constants = await this.blockSource.getL1Constants();
1351
1396
  const validator = createTxValidatorForAcceptingTxsOverRPC(db, this.contractDataSource, verifier, {
1352
1397
  timestamp: nextSlotTimestamp,
1353
1398
  blockNumber,
@@ -1359,7 +1404,10 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1359
1404
  ],
1360
1405
  gasFees: await this.getCurrentMinFees(),
1361
1406
  skipFeeEnforcement,
1362
- txsPermitted: !this.config.disableTransactions
1407
+ txsPermitted: !this.config.disableTransactions,
1408
+ rollupManaLimit: l1Constants.rollupManaLimit,
1409
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1410
+ maxBlockDAGas: this.config.validateMaxDABlockGas
1363
1411
  }, this.log.getBindings());
1364
1412
  return await validator.validateTx(tx);
1365
1413
  }
@@ -1382,7 +1430,18 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1382
1430
  archiver.updateConfig(config);
1383
1431
  }
1384
1432
  if (newConfig.realProofs !== this.config.realProofs) {
1385
- 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
+ }
1386
1445
  }
1387
1446
  this.config = newConfig;
1388
1447
  }
@@ -1442,7 +1501,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1442
1501
  });
1443
1502
  return Promise.resolve();
1444
1503
  }
1445
- async rollbackTo(targetBlock, force) {
1504
+ async rollbackTo(targetBlock, force, resumeSync = true) {
1446
1505
  const archiver = this.blockSource;
1447
1506
  if (!('rollbackTo' in archiver)) {
1448
1507
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1470,9 +1529,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1470
1529
  this.log.error(`Error during rollback`, err);
1471
1530
  throw err;
1472
1531
  } finally{
1473
- this.log.info(`Resuming world state and archiver sync.`);
1474
- this.worldStateSynchronizer.resumeSync();
1475
- 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
+ }
1476
1539
  }
1477
1540
  }
1478
1541
  async pauseSync() {
@@ -1486,18 +1549,12 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1486
1549
  this.blockSource.resume();
1487
1550
  return Promise.resolve();
1488
1551
  }
1489
- getSlashPayloads() {
1490
- if (!this.slasherClient) {
1491
- throw new Error(`Slasher client not enabled`);
1492
- }
1493
- return this.slasherClient.getSlashPayloads();
1494
- }
1495
1552
  getSlashOffenses(round) {
1496
1553
  if (!this.slasherClient) {
1497
1554
  throw new Error(`Slasher client not enabled`);
1498
1555
  }
1499
1556
  if (round === 'all') {
1500
- return this.slasherClient.getPendingOffenses();
1557
+ return this.slasherClient.getOffenses();
1501
1558
  } else {
1502
1559
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1503
1560
  }
@@ -1569,6 +1626,33 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1569
1626
  this.keyStoreManager = newManager;
1570
1627
  this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1571
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
+ }
1572
1656
  #getInitialHeaderHash() {
1573
1657
  if (!this.initialHeaderHashPromise) {
1574
1658
  this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
@@ -1579,7 +1663,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1579
1663
  * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1580
1664
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1581
1665
  * @returns An instance of a committed MerkleTreeOperations
1582
- */ async #getWorldState(block) {
1666
+ */ async getWorldState(block) {
1583
1667
  let blockSyncedTo = BlockNumber.ZERO;
1584
1668
  try {
1585
1669
  // Attempt to sync the world state if necessary
@@ -1591,6 +1675,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1591
1675
  this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
1592
1676
  return this.worldStateSynchronizer.getCommitted();
1593
1677
  }
1678
+ // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1679
+ let blockNumber;
1594
1680
  if (BlockHash.isBlockHash(block)) {
1595
1681
  const initialBlockHash = await this.#getInitialHeaderHash();
1596
1682
  if (block.equals(initialBlockHash)) {
@@ -1601,19 +1687,41 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1601
1687
  if (!header) {
1602
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.`);
1603
1689
  }
1604
- const blockNumber = header.getBlockNumber();
1605
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1606
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1607
- }
1608
- // Block number provided
1609
- {
1610
- const blockNumber = block;
1611
- if (blockNumber > blockSyncedTo) {
1612
- 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.`);
1613
1721
  }
1614
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1615
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1722
+ return header.getBlockNumber();
1616
1723
  }
1724
+ return block;
1617
1725
  }
1618
1726
  /**
1619
1727
  * Ensure we fully sync the world state