@aztec/aztec-node 0.0.1-commit.10bd49492 → 0.0.1-commit.11bf3dd6e

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
  /**
@@ -894,11 +938,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
894
938
  getCheckpointsDataForEpoch(epochNumber) {
895
939
  return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
896
940
  }
897
- /**
898
- * Method to fetch the current min L2 fees.
899
- * @returns The current min L2 fees.
900
- */ async getCurrentMinFees() {
901
- return await this.globalVariableBuilder.getCurrentMinFees();
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);
902
946
  }
903
947
  async getMaxPriorityFees() {
904
948
  for await (const tx of this.p2pClient.iteratePendingTxs()){
@@ -949,28 +993,36 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
949
993
  return this.contractDataSource.getContract(address);
950
994
  }
951
995
  async getPrivateLogsByTags(tags, page, referenceBlock) {
996
+ let upToBlockNumber;
952
997
  if (referenceBlock) {
953
998
  const initialBlockHash = await this.#getInitialHeaderHash();
954
- if (!referenceBlock.equals(initialBlockHash)) {
999
+ if (referenceBlock.equals(initialBlockHash)) {
1000
+ upToBlockNumber = BlockNumber(0);
1001
+ } else {
955
1002
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
956
1003
  if (!header) {
957
1004
  throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
958
1005
  }
1006
+ upToBlockNumber = header.globalVariables.blockNumber;
959
1007
  }
960
1008
  }
961
- return this.logsSource.getPrivateLogsByTags(tags, page);
1009
+ return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
962
1010
  }
963
1011
  async getPublicLogsByTagsFromContract(contractAddress, tags, page, referenceBlock) {
1012
+ let upToBlockNumber;
964
1013
  if (referenceBlock) {
965
1014
  const initialBlockHash = await this.#getInitialHeaderHash();
966
- if (!referenceBlock.equals(initialBlockHash)) {
1015
+ if (referenceBlock.equals(initialBlockHash)) {
1016
+ upToBlockNumber = BlockNumber(0);
1017
+ } else {
967
1018
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
968
1019
  if (!header) {
969
1020
  throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
970
1021
  }
1022
+ upToBlockNumber = header.globalVariables.blockNumber;
971
1023
  }
972
1024
  }
973
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
1025
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
974
1026
  }
975
1027
  /**
976
1028
  * Gets public logs based on the provided filter.
@@ -1043,7 +1095,10 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1043
1095
  await tryStop(this.validatorsSentinel);
1044
1096
  await tryStop(this.epochPruneWatcher);
1045
1097
  await tryStop(this.slasherClient);
1046
- await tryStop(this.proofVerifier);
1098
+ await Promise.all([
1099
+ tryStop(this.peerProofVerifier),
1100
+ tryStop(this.rpcProofVerifier)
1101
+ ]);
1047
1102
  await tryStop(this.sequencer);
1048
1103
  await tryStop(this.proverNode);
1049
1104
  await tryStop(this.p2pClient);
@@ -1085,7 +1140,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1085
1140
  return compactArray(await Promise.all(txHashes.map((txHash)=>this.getTxByHash(txHash))));
1086
1141
  }
1087
1142
  async findLeavesIndexes(referenceBlock, treeId, leafValues) {
1088
- const committedDb = await this.#getWorldState(referenceBlock);
1143
+ const committedDb = await this.getWorldState(referenceBlock);
1089
1144
  const maybeIndices = await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
1090
1145
  // Filter out undefined values to query block numbers only for found leaves
1091
1146
  const definedIndices = maybeIndices.filter((x)=>x !== undefined);
@@ -1126,33 +1181,41 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1126
1181
  if (blockNumber === undefined) {
1127
1182
  throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1128
1183
  }
1129
- const blockHash = blockNumberToHash.get(blockNumber);
1130
- if (blockHash === undefined) {
1184
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
1185
+ if (l2BlockHash === undefined) {
1131
1186
  throw new Error(`Block hash not found for block number ${blockNumber}`);
1132
1187
  }
1133
1188
  return {
1134
1189
  l2BlockNumber: blockNumber,
1135
- l2BlockHash: new BlockHash(blockHash),
1190
+ l2BlockHash,
1136
1191
  data: index
1137
1192
  };
1138
1193
  });
1139
1194
  }
1140
1195
  async getBlockHashMembershipWitness(referenceBlock, blockHash) {
1141
- 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));
1142
1205
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE, [
1143
1206
  blockHash
1144
1207
  ]);
1145
1208
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1146
1209
  }
1147
1210
  async getNoteHashMembershipWitness(referenceBlock, noteHash) {
1148
- const committedDb = await this.#getWorldState(referenceBlock);
1211
+ const committedDb = await this.getWorldState(referenceBlock);
1149
1212
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE, [
1150
1213
  noteHash
1151
1214
  ]);
1152
1215
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1153
1216
  }
1154
1217
  async getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
1155
- const db = await this.#getWorldState(referenceBlock);
1218
+ const db = await this.getWorldState(referenceBlock);
1156
1219
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
1157
1220
  l1ToL2Message
1158
1221
  ]);
@@ -1184,23 +1247,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1184
1247
  */ async getL2ToL1Messages(epoch) {
1185
1248
  // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1186
1249
  const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1187
- const blocksInCheckpoints = [];
1188
- let previousSlotNumber = SlotNumber.ZERO;
1189
- let checkpointIndex = -1;
1190
- for (const checkpointedBlock of checkpointedBlocks){
1191
- const block = checkpointedBlock.block;
1192
- const slotNumber = block.header.globalVariables.slotNumber;
1193
- if (slotNumber !== previousSlotNumber) {
1194
- checkpointIndex++;
1195
- blocksInCheckpoints.push([]);
1196
- previousSlotNumber = slotNumber;
1197
- }
1198
- blocksInCheckpoints[checkpointIndex].push(block);
1199
- }
1250
+ const blocksInCheckpoints = chunkBy(checkpointedBlocks, (cb)=>cb.block.header.globalVariables.slotNumber).map((group)=>group.map((cb)=>cb.block));
1200
1251
  return blocksInCheckpoints.map((blocks)=>blocks.map((block)=>block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs)));
1201
1252
  }
1202
1253
  async getNullifierMembershipWitness(referenceBlock, nullifier) {
1203
- const db = await this.#getWorldState(referenceBlock);
1254
+ const db = await this.getWorldState(referenceBlock);
1204
1255
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [
1205
1256
  nullifier.toBuffer()
1206
1257
  ]);
@@ -1214,36 +1265,22 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1214
1265
  }
1215
1266
  return new NullifierMembershipWitness(index, leafPreimage, path);
1216
1267
  }
1217
- /**
1218
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1219
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1220
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1221
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1222
- * @returns The low nullifier membership witness (if found).
1223
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1224
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1225
- * we are trying to prove non-inclusion for.
1226
- *
1227
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1228
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1229
- * index of the nullifier itself when it already exists in the tree.
1230
- * TODO: This is a confusing behavior and we should eventually address that.
1231
- */ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1232
- const committedDb = await this.#getWorldState(referenceBlock);
1268
+ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1269
+ const committedDb = await this.getWorldState(referenceBlock);
1233
1270
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1234
1271
  if (!findResult) {
1235
1272
  return undefined;
1236
1273
  }
1237
1274
  const { index, alreadyPresent } = findResult;
1238
1275
  if (alreadyPresent) {
1239
- 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`);
1240
1277
  }
1241
1278
  const preimageData = await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1242
1279
  const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1243
1280
  return new NullifierMembershipWitness(BigInt(index), preimageData, siblingPath);
1244
1281
  }
1245
1282
  async getPublicDataWitness(referenceBlock, leafSlot) {
1246
- const committedDb = await this.#getWorldState(referenceBlock);
1283
+ const committedDb = await this.getWorldState(referenceBlock);
1247
1284
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1248
1285
  if (!lowLeafResult) {
1249
1286
  return undefined;
@@ -1254,7 +1291,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1254
1291
  }
1255
1292
  }
1256
1293
  async getPublicStorageAt(referenceBlock, contract, slot) {
1257
- const committedDb = await this.#getWorldState(referenceBlock);
1294
+ const committedDb = await this.getWorldState(referenceBlock);
1258
1295
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1259
1296
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1260
1297
  if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
@@ -1351,7 +1388,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1351
1388
  }
1352
1389
  async isValidTx(tx, { isSimulation, skipFeeEnforcement } = {}) {
1353
1390
  const db = this.worldStateSynchronizer.getCommitted();
1354
- const verifier = isSimulation ? undefined : this.proofVerifier;
1391
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1355
1392
  // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1356
1393
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1357
1394
  const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
@@ -1393,7 +1430,18 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1393
1430
  archiver.updateConfig(config);
1394
1431
  }
1395
1432
  if (newConfig.realProofs !== this.config.realProofs) {
1396
- 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
+ }
1397
1445
  }
1398
1446
  this.config = newConfig;
1399
1447
  }
@@ -1453,7 +1501,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1453
1501
  });
1454
1502
  return Promise.resolve();
1455
1503
  }
1456
- async rollbackTo(targetBlock, force) {
1504
+ async rollbackTo(targetBlock, force, resumeSync = true) {
1457
1505
  const archiver = this.blockSource;
1458
1506
  if (!('rollbackTo' in archiver)) {
1459
1507
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1481,9 +1529,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1481
1529
  this.log.error(`Error during rollback`, err);
1482
1530
  throw err;
1483
1531
  } finally{
1484
- this.log.info(`Resuming world state and archiver sync.`);
1485
- this.worldStateSynchronizer.resumeSync();
1486
- 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
+ }
1487
1539
  }
1488
1540
  }
1489
1541
  async pauseSync() {
@@ -1497,18 +1549,12 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1497
1549
  this.blockSource.resume();
1498
1550
  return Promise.resolve();
1499
1551
  }
1500
- getSlashPayloads() {
1501
- if (!this.slasherClient) {
1502
- throw new Error(`Slasher client not enabled`);
1503
- }
1504
- return this.slasherClient.getSlashPayloads();
1505
- }
1506
1552
  getSlashOffenses(round) {
1507
1553
  if (!this.slasherClient) {
1508
1554
  throw new Error(`Slasher client not enabled`);
1509
1555
  }
1510
1556
  if (round === 'all') {
1511
- return this.slasherClient.getPendingOffenses();
1557
+ return this.slasherClient.getOffenses();
1512
1558
  } else {
1513
1559
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1514
1560
  }
@@ -1580,6 +1626,33 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1580
1626
  this.keyStoreManager = newManager;
1581
1627
  this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1582
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
+ }
1583
1656
  #getInitialHeaderHash() {
1584
1657
  if (!this.initialHeaderHashPromise) {
1585
1658
  this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
@@ -1590,7 +1663,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1590
1663
  * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1591
1664
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1592
1665
  * @returns An instance of a committed MerkleTreeOperations
1593
- */ async #getWorldState(block) {
1666
+ */ async getWorldState(block) {
1594
1667
  let blockSyncedTo = BlockNumber.ZERO;
1595
1668
  try {
1596
1669
  // Attempt to sync the world state if necessary
@@ -1602,6 +1675,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1602
1675
  this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
1603
1676
  return this.worldStateSynchronizer.getCommitted();
1604
1677
  }
1678
+ // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1679
+ let blockNumber;
1605
1680
  if (BlockHash.isBlockHash(block)) {
1606
1681
  const initialBlockHash = await this.#getInitialHeaderHash();
1607
1682
  if (block.equals(initialBlockHash)) {
@@ -1612,19 +1687,41 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1612
1687
  if (!header) {
1613
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.`);
1614
1689
  }
1615
- const blockNumber = header.getBlockNumber();
1616
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1617
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1618
- }
1619
- // Block number provided
1620
- {
1621
- const blockNumber = block;
1622
- if (blockNumber > blockSyncedTo) {
1623
- 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.`);
1624
1721
  }
1625
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1626
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1722
+ return header.getBlockNumber();
1627
1723
  }
1724
+ return block;
1628
1725
  }
1629
1726
  /**
1630
1727
  * Ensure we fully sync the world state