@aztec/aztec-node 0.0.1-commit.3469e52 → 0.0.1-commit.381b1a9

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.
@@ -374,12 +374,13 @@ var _dec, _initProto;
374
374
  import { createArchiver } from '@aztec/archiver';
375
375
  import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
376
376
  import { createBlobClientWithFileStores } from '@aztec/blob-client/client';
377
+ import { Blob } from '@aztec/blob-lib';
377
378
  import { EpochCache } from '@aztec/epoch-cache';
378
379
  import { createEthereumChain } from '@aztec/ethereum/chain';
379
380
  import { getPublicClient } from '@aztec/ethereum/client';
380
381
  import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
381
382
  import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
382
- import { compactArray, pick } from '@aztec/foundation/collection';
383
+ import { compactArray, pick, unique } from '@aztec/foundation/collection';
383
384
  import { Fr } from '@aztec/foundation/curves/bn254';
384
385
  import { EthAddress } from '@aztec/foundation/eth-address';
385
386
  import { BadRequestError } from '@aztec/foundation/json-rpc';
@@ -389,26 +390,28 @@ import { DateProvider, Timer } from '@aztec/foundation/timer';
389
390
  import { MembershipWitness } from '@aztec/foundation/trees';
390
391
  import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
391
392
  import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
392
- import { createForwarderL1TxUtilsFromEthSigner, createL1TxUtilsWithBlobsFromEthSigner } from '@aztec/node-lib/factories';
393
- import { createP2PClient, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
393
+ import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
394
+ import { createP2PClient, createTxValidatorForAcceptingTxsOverRPC, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
394
395
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
396
+ import { createProverNode } from '@aztec/prover-node';
397
+ import { createKeyStoreForProver } from '@aztec/prover-node/config';
395
398
  import { GlobalVariableBuilder, SequencerClient } from '@aztec/sequencer-client';
396
399
  import { PublicProcessorFactory } from '@aztec/simulator/server';
397
400
  import { AttestationsBlockWatcher, EpochPruneWatcher, createSlasher } from '@aztec/slasher';
398
401
  import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
399
402
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
400
- import { L2BlockHash, L2BlockNew } from '@aztec/stdlib/block';
403
+ import { BlockHash, L2Block } from '@aztec/stdlib/block';
401
404
  import { GasFees } from '@aztec/stdlib/gas';
402
405
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
403
406
  import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
404
407
  import { tryStop } from '@aztec/stdlib/interfaces/server';
408
+ import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
405
409
  import { InboxLeaf } from '@aztec/stdlib/messaging';
406
- import { P2PClientType } from '@aztec/stdlib/p2p';
407
410
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
408
411
  import { PublicSimulationOutput, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
409
412
  import { getPackageVersion } from '@aztec/stdlib/update-checker';
410
413
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
411
- import { FullNodeCheckpointsBuilder as CheckpointsBuilder, FullNodeCheckpointsBuilder, NodeKeystoreAdapter, ValidatorClient, createBlockProposalHandler, createValidatorClient, createValidatorForAcceptingTxs } from '@aztec/validator-client';
414
+ import { FullNodeCheckpointsBuilder as CheckpointsBuilder, FullNodeCheckpointsBuilder, NodeKeystoreAdapter, ValidatorClient, createBlockProposalHandler, createValidatorClient } from '@aztec/validator-client';
412
415
  import { createWorldStateSynchronizer } from '@aztec/world-state';
413
416
  import { createPublicClient, fallback, http } from 'viem';
414
417
  import { createSentinel } from '../sentinel/factory.js';
@@ -428,6 +431,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
428
431
  l1ToL2MessageSource;
429
432
  worldStateSynchronizer;
430
433
  sequencer;
434
+ proverNode;
431
435
  slasherClient;
432
436
  validatorsSentinel;
433
437
  epochPruneWatcher;
@@ -440,6 +444,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
440
444
  telemetry;
441
445
  log;
442
446
  blobClient;
447
+ validatorClient;
448
+ keyStoreManager;
449
+ debugLogStore;
443
450
  static{
444
451
  ({ e: [_initProto] } = _apply_decs_2203_r(this, [
445
452
  [
@@ -454,7 +461,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
454
461
  // Prevent two snapshot operations to happen simultaneously
455
462
  isUploadingSnapshot;
456
463
  tracer;
457
- constructor(config, p2pClient, blockSource, logsSource, contractDataSource, l1ToL2MessageSource, worldStateSynchronizer, sequencer, slasherClient, validatorsSentinel, epochPruneWatcher, l1ChainId, version, globalVariableBuilder, epochCache, packageVersion, proofVerifier, telemetry = getTelemetryClient(), log = createLogger('node'), blobClient){
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()){
458
465
  this.config = config;
459
466
  this.p2pClient = p2pClient;
460
467
  this.blockSource = blockSource;
@@ -463,6 +470,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
463
470
  this.l1ToL2MessageSource = l1ToL2MessageSource;
464
471
  this.worldStateSynchronizer = worldStateSynchronizer;
465
472
  this.sequencer = sequencer;
473
+ this.proverNode = proverNode;
466
474
  this.slasherClient = slasherClient;
467
475
  this.validatorsSentinel = validatorsSentinel;
468
476
  this.epochPruneWatcher = epochPruneWatcher;
@@ -475,12 +483,21 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
475
483
  this.telemetry = telemetry;
476
484
  this.log = log;
477
485
  this.blobClient = blobClient;
486
+ this.validatorClient = validatorClient;
487
+ this.keyStoreManager = keyStoreManager;
488
+ this.debugLogStore = debugLogStore;
478
489
  this.initialHeaderHashPromise = (_initProto(this), undefined);
479
490
  this.isUploadingSnapshot = false;
480
491
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
481
492
  this.tracer = telemetry.getTracer('AztecNodeService');
482
493
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
483
494
  this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
495
+ // A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
496
+ // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
497
+ // memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
498
+ if (debugLogStore.isEnabled && config.realProofs) {
499
+ throw new Error('debugLogStore should never be enabled when realProofs are set');
500
+ }
484
501
  }
485
502
  async getWorldStateSyncStatus() {
486
503
  const status = await this.worldStateSynchronizer.status();
@@ -502,16 +519,27 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
502
519
  const telemetry = deps.telemetry ?? getTelemetryClient();
503
520
  const dateProvider = deps.dateProvider ?? new DateProvider();
504
521
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
505
- // Build a key store from file if given or from environment otherwise
522
+ // Build a key store from file if given or from environment otherwise.
523
+ // We keep the raw KeyStore available so we can merge with prover keys if enableProverNode is set.
506
524
  let keyStoreManager;
507
525
  const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
508
526
  if (keyStoreProvided) {
509
527
  const keyStores = loadKeystores(config.keyStoreDirectory);
510
528
  keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
511
529
  } else {
512
- const keyStore = createKeyStoreForValidator(config);
513
- if (keyStore) {
514
- keyStoreManager = new KeystoreManager(keyStore);
530
+ const rawKeyStores = [];
531
+ const validatorKeyStore = createKeyStoreForValidator(config);
532
+ if (validatorKeyStore) {
533
+ rawKeyStores.push(validatorKeyStore);
534
+ }
535
+ if (config.enableProverNode) {
536
+ const proverKeyStore = createKeyStoreForProver(config);
537
+ if (proverKeyStore) {
538
+ rawKeyStores.push(proverKeyStore);
539
+ }
540
+ }
541
+ if (rawKeyStores.length > 0) {
542
+ keyStoreManager = new KeystoreManager(rawKeyStores.length === 1 ? rawKeyStores[0] : mergeKeystores(rawKeyStores));
515
543
  }
516
544
  }
517
545
  await keyStoreManager?.validateSigners();
@@ -520,8 +548,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
520
548
  if (keyStoreManager === undefined) {
521
549
  throw new Error('Failed to create key store, a requirement for running a validator');
522
550
  }
523
- if (!keyStoreProvided) {
524
- log.warn('KEY STORE CREATED FROM ENVIRONMENT, IT IS RECOMMENDED TO USE A FILE-BASED KEY STORE IN PRODUCTION ENVIRONMENTS');
551
+ if (!keyStoreProvided && process.env.NODE_ENV !== 'test') {
552
+ log.warn("Keystore created from env: it's recommended to use a file-based key store for production");
525
553
  }
526
554
  ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
527
555
  }
@@ -543,16 +571,17 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
543
571
  ...l1ContractsAddresses
544
572
  };
545
573
  const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
546
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
574
+ const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
547
575
  rollupContract.getL1GenesisTime(),
548
576
  rollupContract.getSlotDuration(),
549
- rollupContract.getVersion()
577
+ rollupContract.getVersion(),
578
+ rollupContract.getManaLimit().then(Number)
550
579
  ]);
551
580
  config.rollupVersion ??= Number(rollupVersionFromRollup);
552
581
  if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
553
582
  log.warn(`Registry looked up and returned a rollup with version (${config.rollupVersion}), but this does not match with version detected from the rollup directly: (${rollupVersionFromRollup}).`);
554
583
  }
555
- const blobClient = await createBlobClientWithFileStores(config, createLogger('node:blob-client:client'));
584
+ const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
556
585
  // attempt snapshot sync if possible
557
586
  await trySnapshotSync(config, log);
558
587
  const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, {
@@ -569,48 +598,63 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
569
598
  // now create the merkle trees and the world state synchronizer
570
599
  const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.prefilledPublicData, telemetry);
571
600
  const circuitVerifier = config.realProofs || config.debugForceTxProofVerification ? await BBCircuitVerifier.new(config) : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
601
+ let debugLogStore;
572
602
  if (!config.realProofs) {
573
603
  log.warn(`Aztec node is accepting fake proofs`);
604
+ debugLogStore = new InMemoryDebugLogStore();
605
+ log.info('Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served');
606
+ } else {
607
+ debugLogStore = new NullDebugLogStore();
574
608
  }
575
609
  const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
610
+ const proverOnly = config.enableProverNode && config.disableValidator;
611
+ if (proverOnly) {
612
+ log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
613
+ }
576
614
  // create the tx pool and the p2p client, which will need the l2 block source
577
- const p2pClient = await createP2PClient(P2PClientType.Full, config, archiver, proofVerifier, worldStateSynchronizer, epochCache, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
578
- // We should really not be modifying the config object
579
- config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
580
- // Create FullNodeCheckpointsBuilder for validator and non-validator block proposal handling
615
+ const p2pClient = await createP2PClient(config, archiver, proofVerifier, worldStateSynchronizer, epochCache, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
616
+ // We'll accumulate sentinel watchers here
617
+ const watchers = [];
618
+ // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
619
+ // Override maxTxsPerCheckpoint with the validator-specific limit if set.
581
620
  const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder({
582
621
  ...config,
583
622
  l1GenesisTime,
584
- slotDuration: Number(slotDuration)
623
+ slotDuration: Number(slotDuration),
624
+ rollupManaLimit,
625
+ maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint
585
626
  }, worldStateSynchronizer, archiver, dateProvider, telemetry);
586
- // We'll accumulate sentinel watchers here
587
- const watchers = [];
588
- // Create validator client if required
589
- const validatorClient = await createValidatorClient(config, {
590
- checkpointsBuilder: validatorCheckpointsBuilder,
591
- worldState: worldStateSynchronizer,
592
- p2pClient,
593
- telemetry,
594
- dateProvider,
595
- epochCache,
596
- blockSource: archiver,
597
- l1ToL2MessageSource: archiver,
598
- keyStoreManager,
599
- blobClient
600
- });
601
- // If we have a validator client, register it as a source of offenses for the slasher,
602
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
603
- // like attestations or auths will fail.
604
- if (validatorClient) {
605
- watchers.push(validatorClient);
606
- if (!options.dontStartSequencer) {
607
- await validatorClient.registerHandlers();
627
+ let validatorClient;
628
+ if (!proverOnly) {
629
+ // Create validator client if required
630
+ validatorClient = await createValidatorClient(config, {
631
+ checkpointsBuilder: validatorCheckpointsBuilder,
632
+ worldState: worldStateSynchronizer,
633
+ p2pClient,
634
+ telemetry,
635
+ dateProvider,
636
+ epochCache,
637
+ blockSource: archiver,
638
+ l1ToL2MessageSource: archiver,
639
+ keyStoreManager,
640
+ blobClient
641
+ });
642
+ // If we have a validator client, register it as a source of offenses for the slasher,
643
+ // and have it register callbacks on the p2p client *before* we start it, otherwise messages
644
+ // like attestations or auths will fail.
645
+ if (validatorClient) {
646
+ watchers.push(validatorClient);
647
+ if (!options.dontStartSequencer) {
648
+ await validatorClient.registerHandlers();
649
+ }
608
650
  }
609
651
  }
610
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
611
- // create a BlockProposalHandler to reexecute block proposals for monitoring
612
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
613
- log.info('Setting up block proposal reexecution for monitoring');
652
+ // If there's no validator client, create a BlockProposalHandler to handle block proposals
653
+ // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
654
+ // while non-reexecution is used for validating the proposals and collecting their txs.
655
+ if (!validatorClient) {
656
+ const reexecute = !!config.alwaysReexecuteBlockProposals;
657
+ log.info(`Setting up block proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
614
658
  createBlockProposalHandler(config, {
615
659
  checkpointsBuilder: validatorCheckpointsBuilder,
616
660
  worldState: worldStateSynchronizer,
@@ -620,26 +664,29 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
620
664
  p2pClient,
621
665
  dateProvider,
622
666
  telemetry
623
- }).registerForReexecution(p2pClient);
667
+ }).register(p2pClient, reexecute);
624
668
  }
625
669
  // Start world state and wait for it to sync to the archiver.
626
670
  await worldStateSynchronizer.start();
627
671
  // Start p2p. Note that it depends on world state to be running.
628
672
  await p2pClient.start();
629
- const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
630
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
631
- watchers.push(validatorsSentinel);
632
- }
673
+ let validatorsSentinel;
633
674
  let epochPruneWatcher;
634
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
635
- epochPruneWatcher = new EpochPruneWatcher(archiver, archiver, epochCache, p2pClient.getTxProvider(), validatorCheckpointsBuilder, config);
636
- watchers.push(epochPruneWatcher);
637
- }
638
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
639
675
  let attestationsBlockWatcher;
640
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
641
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
642
- watchers.push(attestationsBlockWatcher);
676
+ if (!proverOnly) {
677
+ validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
678
+ if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
679
+ watchers.push(validatorsSentinel);
680
+ }
681
+ if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
682
+ epochPruneWatcher = new EpochPruneWatcher(archiver, archiver, epochCache, p2pClient.getTxProvider(), validatorCheckpointsBuilder, config);
683
+ watchers.push(epochPruneWatcher);
684
+ }
685
+ // We assume we want to slash for invalid attestations unless all max penalties are set to 0
686
+ if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
687
+ attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
688
+ watchers.push(attestationsBlockWatcher);
689
+ }
643
690
  }
644
691
  // Start p2p-related services once the archiver has completed sync
645
692
  void archiver.waitForInitialSync().then(async ()=>{
@@ -658,27 +705,30 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
658
705
  const validatorAddresses = keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses() : [];
659
706
  slasherClient = await createSlasher(config, config.l1Contracts, getPublicClient(config), watchers, dateProvider, epochCache, validatorAddresses, undefined);
660
707
  await slasherClient.start();
661
- const l1TxUtils = config.publisherForwarderAddress ? await createForwarderL1TxUtilsFromEthSigner(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), config.publisherForwarderAddress, {
708
+ const l1TxUtils = config.sequencerPublisherForwarderAddress ? await createForwarderL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), config.sequencerPublisherForwarderAddress, {
662
709
  ...config,
663
710
  scope: 'sequencer'
664
711
  }, {
665
712
  telemetry,
666
713
  logger: log.createChild('l1-tx-utils'),
667
- dateProvider
668
- }) : await createL1TxUtilsWithBlobsFromEthSigner(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
714
+ dateProvider,
715
+ kzg: Blob.getViemKzgInstance()
716
+ }) : await createL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
669
717
  ...config,
670
718
  scope: 'sequencer'
671
719
  }, {
672
720
  telemetry,
673
721
  logger: log.createChild('l1-tx-utils'),
674
- dateProvider
722
+ dateProvider,
723
+ kzg: Blob.getViemKzgInstance()
675
724
  });
676
725
  // Create and start the sequencer client
677
726
  const checkpointsBuilder = new CheckpointsBuilder({
678
727
  ...config,
679
728
  l1GenesisTime,
680
- slotDuration: Number(slotDuration)
681
- }, worldStateSynchronizer, archiver, dateProvider, telemetry);
729
+ slotDuration: Number(slotDuration),
730
+ rollupManaLimit
731
+ }, worldStateSynchronizer, archiver, dateProvider, telemetry, debugLogStore);
682
732
  sequencer = await SequencerClient.new(config, {
683
733
  ...deps,
684
734
  epochCache,
@@ -702,13 +752,35 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
702
752
  } else if (sequencer) {
703
753
  log.warn(`Sequencer created but not started`);
704
754
  }
755
+ // Create prover node subsystem if enabled
756
+ let proverNode;
757
+ if (config.enableProverNode) {
758
+ proverNode = await createProverNode(config, {
759
+ ...deps.proverNodeDeps,
760
+ telemetry,
761
+ dateProvider,
762
+ archiver,
763
+ worldStateSynchronizer,
764
+ p2pClient,
765
+ epochCache,
766
+ blobClient,
767
+ keyStoreManager
768
+ });
769
+ if (!options.dontStartProverNode) {
770
+ await proverNode.start();
771
+ log.info(`Prover node subsystem started`);
772
+ } else {
773
+ log.info(`Prover node subsystem created but not started`);
774
+ }
775
+ }
705
776
  const globalVariableBuilder = new GlobalVariableBuilder({
706
777
  ...config,
707
778
  rollupVersion: BigInt(config.rollupVersion),
708
779
  l1GenesisTime,
709
780
  slotDuration: Number(slotDuration)
710
781
  });
711
- return new AztecNodeService(config, p2pClient, archiver, archiver, archiver, archiver, worldStateSynchronizer, sequencer, slasherClient, validatorsSentinel, epochPruneWatcher, ethereumChain.chainInfo.id, config.rollupVersion, globalVariableBuilder, epochCache, packageVersion, proofVerifier, telemetry, log, blobClient);
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);
783
+ return node;
712
784
  }
713
785
  /**
714
786
  * Returns the sequencer client instance.
@@ -716,6 +788,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
716
788
  */ getSequencer() {
717
789
  return this.sequencer;
718
790
  }
791
+ /** Returns the prover node subsystem, if enabled. */ getProverNode() {
792
+ return this.proverNode;
793
+ }
719
794
  getBlockSource() {
720
795
  return this.blockSource;
721
796
  }
@@ -735,7 +810,10 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
735
810
  return Promise.resolve(this.p2pClient.getEnr()?.encodeTxt());
736
811
  }
737
812
  async getAllowedPublicSetup() {
738
- return this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
813
+ return [
814
+ ...await getDefaultAllowedSetupFunctions(),
815
+ ...this.config.txPublicSetupAllowListExtend ?? []
816
+ ];
739
817
  }
740
818
  /**
741
819
  * Method to determine if the node is ready to accept transactions.
@@ -758,7 +836,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
758
836
  rollupVersion,
759
837
  enr,
760
838
  l1ContractAddresses: contractAddresses,
761
- protocolContractAddresses: protocolContractAddresses
839
+ protocolContractAddresses: protocolContractAddresses,
840
+ realProofs: !!this.config.realProofs
762
841
  };
763
842
  return nodeInfo;
764
843
  }
@@ -767,14 +846,14 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
767
846
  * @param block - The block parameter (block number, block hash, or 'latest').
768
847
  * @returns The requested block.
769
848
  */ async getBlock(block) {
770
- if (L2BlockHash.isL2BlockHash(block)) {
771
- return this.getBlockByHash(Fr.fromBuffer(block.toBuffer()));
849
+ if (BlockHash.isBlockHash(block)) {
850
+ return this.getBlockByHash(block);
772
851
  }
773
852
  const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
774
853
  if (blockNumber === BlockNumber.ZERO) {
775
854
  return this.buildInitialBlock();
776
855
  }
777
- return await this.blockSource.getL2BlockNew(blockNumber);
856
+ return await this.blockSource.getL2Block(blockNumber);
778
857
  }
779
858
  /**
780
859
  * Get a block specified by its hash.
@@ -782,21 +861,21 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
782
861
  * @returns The requested block.
783
862
  */ async getBlockByHash(blockHash) {
784
863
  const initialBlockHash = await this.#getInitialHeaderHash();
785
- if (blockHash.equals(Fr.fromBuffer(initialBlockHash.toBuffer()))) {
864
+ if (blockHash.equals(initialBlockHash)) {
786
865
  return this.buildInitialBlock();
787
866
  }
788
- return await this.blockSource.getL2BlockNewByHash(blockHash);
867
+ return await this.blockSource.getL2BlockByHash(blockHash);
789
868
  }
790
869
  buildInitialBlock() {
791
870
  const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
792
- return L2BlockNew.empty(initialHeader);
871
+ return L2Block.empty(initialHeader);
793
872
  }
794
873
  /**
795
874
  * Get a block specified by its archive root.
796
875
  * @param archive - The archive root being requested.
797
876
  * @returns The requested block.
798
877
  */ async getBlockByArchive(archive) {
799
- return await this.blockSource.getL2BlockNewByArchive(archive);
878
+ return await this.blockSource.getL2BlockByArchive(archive);
800
879
  }
801
880
  /**
802
881
  * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
@@ -804,19 +883,16 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
804
883
  * @param limit - The maximum number of blocks to obtain.
805
884
  * @returns The blocks requested.
806
885
  */ async getBlocks(from, limit) {
807
- return await this.blockSource.getL2BlocksNew(from, limit) ?? [];
808
- }
809
- async getPublishedBlocks(from, limit) {
810
- return await this.blockSource.getPublishedBlocks(from, limit) ?? [];
886
+ return await this.blockSource.getBlocks(from, BlockNumber(limit)) ?? [];
811
887
  }
812
- async getPublishedCheckpoints(from, limit) {
813
- return await this.blockSource.getPublishedCheckpoints(from, limit) ?? [];
888
+ async getCheckpoints(from, limit) {
889
+ return await this.blockSource.getCheckpoints(from, limit) ?? [];
814
890
  }
815
- async getL2BlocksNew(from, limit) {
816
- return await this.blockSource.getL2BlocksNew(from, limit) ?? [];
891
+ async getCheckpointedBlocks(from, limit) {
892
+ return await this.blockSource.getCheckpointedBlocks(from, limit) ?? [];
817
893
  }
818
- async getCheckpointedBlocks(from, limit, proven) {
819
- return await this.blockSource.getCheckpointedBlocks(from, limit, proven) ?? [];
894
+ getCheckpointsDataForEpoch(epochNumber) {
895
+ return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
820
896
  }
821
897
  /**
822
898
  * Method to fetch the current min L2 fees.
@@ -842,6 +918,12 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
842
918
  async getProvenBlockNumber() {
843
919
  return await this.blockSource.getProvenBlockNumber();
844
920
  }
921
+ async getCheckpointedBlockNumber() {
922
+ return await this.blockSource.getCheckpointedL2BlockNumber();
923
+ }
924
+ getCheckpointNumber() {
925
+ return this.blockSource.getCheckpointNumber();
926
+ }
845
927
  /**
846
928
  * Method to fetch the version of the package.
847
929
  * @returns The node package version
@@ -866,10 +948,28 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
866
948
  getContract(address) {
867
949
  return this.contractDataSource.getContract(address);
868
950
  }
869
- getPrivateLogsByTags(tags, page) {
951
+ async getPrivateLogsByTags(tags, page, referenceBlock) {
952
+ if (referenceBlock) {
953
+ const initialBlockHash = await this.#getInitialHeaderHash();
954
+ if (!referenceBlock.equals(initialBlockHash)) {
955
+ const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
956
+ if (!header) {
957
+ throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
958
+ }
959
+ }
960
+ }
870
961
  return this.logsSource.getPrivateLogsByTags(tags, page);
871
962
  }
872
- getPublicLogsByTagsFromContract(contractAddress, tags, page) {
963
+ async getPublicLogsByTagsFromContract(contractAddress, tags, page, referenceBlock) {
964
+ if (referenceBlock) {
965
+ const initialBlockHash = await this.#getInitialHeaderHash();
966
+ if (!referenceBlock.equals(initialBlockHash)) {
967
+ const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
968
+ if (!header) {
969
+ throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
970
+ }
971
+ }
972
+ }
873
973
  return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
874
974
  }
875
975
  /**
@@ -905,24 +1005,33 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
905
1005
  throw new Error(`Invalid tx: ${reason}`);
906
1006
  }
907
1007
  await this.p2pClient.sendTx(tx);
908
- this.metrics.receivedTx(timer.ms(), true);
909
- this.log.info(`Received tx ${txHash}`, {
1008
+ const duration = timer.ms();
1009
+ this.metrics.receivedTx(duration, true);
1010
+ this.log.info(`Received tx ${txHash} in ${duration}ms`, {
910
1011
  txHash
911
1012
  });
912
1013
  }
913
1014
  async getTxReceipt(txHash) {
914
- let txReceipt = new TxReceipt(txHash, TxStatus.DROPPED, 'Tx dropped by P2P node.');
915
- // We first check if the tx is in pending (instead of first checking if it is mined) because if we first check
916
- // for mined and then for pending there could be a race condition where the tx is mined between the two checks
917
- // and we would incorrectly return a TxReceipt with status DROPPED
918
- if (await this.p2pClient.getTxStatus(txHash) === 'pending') {
919
- txReceipt = new TxReceipt(txHash, TxStatus.PENDING, '');
920
- }
1015
+ // Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
1016
+ // as a fallback if we don't find a settled receipt in the archiver.
1017
+ const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
1018
+ const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
1019
+ // Then get the actual tx from the archiver, which tracks every tx in a mined block.
921
1020
  const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
1021
+ let receipt;
922
1022
  if (settledTxReceipt) {
923
- txReceipt = settledTxReceipt;
1023
+ receipt = settledTxReceipt;
1024
+ } else if (isKnownToPool) {
1025
+ // If the tx is in the pool but not in the archiver, it's pending.
1026
+ // This handles race conditions between archiver and p2p, where the archiver
1027
+ // has pruned the block in which a tx was mined, but p2p has not caught up yet.
1028
+ receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
1029
+ } else {
1030
+ // Otherwise, if we don't know the tx, we consider it dropped.
1031
+ receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
924
1032
  }
925
- return txReceipt;
1033
+ this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
1034
+ return receipt;
926
1035
  }
927
1036
  getTxEffect(txHash) {
928
1037
  return this.blockSource.getTxEffect(txHash);
@@ -936,6 +1045,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
936
1045
  await tryStop(this.slasherClient);
937
1046
  await tryStop(this.proofVerifier);
938
1047
  await tryStop(this.sequencer);
1048
+ await tryStop(this.proverNode);
939
1049
  await tryStop(this.p2pClient);
940
1050
  await tryStop(this.worldStateSynchronizer);
941
1051
  await tryStop(this.blockSource);
@@ -974,79 +1084,79 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
974
1084
  */ async getTxsByHash(txHashes) {
975
1085
  return compactArray(await Promise.all(txHashes.map((txHash)=>this.getTxByHash(txHash))));
976
1086
  }
977
- async findLeavesIndexes(block, treeId, leafValues) {
978
- const committedDb = await this.#getWorldState(block);
1087
+ async findLeavesIndexes(referenceBlock, treeId, leafValues) {
1088
+ const committedDb = await this.#getWorldState(referenceBlock);
979
1089
  const maybeIndices = await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
980
- // We filter out undefined values
981
- const indices = maybeIndices.filter((x)=>x !== undefined);
982
- // Now we find the block numbers for the indices
983
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
984
- // If any of the block numbers are undefined, we throw an error.
985
- for(let i = 0; i < indices.length; i++){
986
- if (blockNumbers[i] === undefined) {
987
- throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
1090
+ // Filter out undefined values to query block numbers only for found leaves
1091
+ const definedIndices = maybeIndices.filter((x)=>x !== undefined);
1092
+ // Now we find the block numbers for the defined indices
1093
+ const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
1094
+ // Build a map from leaf index to block number
1095
+ const indexToBlockNumber = new Map();
1096
+ for(let i = 0; i < definedIndices.length; i++){
1097
+ const blockNumber = blockNumbers[i];
1098
+ if (blockNumber === undefined) {
1099
+ throw new Error(`Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`);
988
1100
  }
1101
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
989
1102
  }
990
1103
  // Get unique block numbers in order to optimize num calls to getLeafValue function.
991
1104
  const uniqueBlockNumbers = [
992
- ...new Set(blockNumbers.filter((x)=>x !== undefined))
1105
+ ...new Set(indexToBlockNumber.values())
993
1106
  ];
994
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
995
- // (note that block number corresponds to the leaf index in the archive tree).
1107
+ // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
996
1108
  const blockHashes = await Promise.all(uniqueBlockNumbers.map((blockNumber)=>{
997
1109
  return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
998
1110
  }));
999
- // If any of the block hashes are undefined, we throw an error.
1111
+ // Build a map from block number to block hash
1112
+ const blockNumberToHash = new Map();
1000
1113
  for(let i = 0; i < uniqueBlockNumbers.length; i++){
1001
- if (blockHashes[i] === undefined) {
1114
+ const blockHash = blockHashes[i];
1115
+ if (blockHash === undefined) {
1002
1116
  throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
1003
1117
  }
1118
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
1004
1119
  }
1005
1120
  // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
1006
- return maybeIndices.map((index, i)=>{
1121
+ return maybeIndices.map((index)=>{
1007
1122
  if (index === undefined) {
1008
1123
  return undefined;
1009
1124
  }
1010
- const blockNumber = blockNumbers[i];
1125
+ const blockNumber = indexToBlockNumber.get(index);
1011
1126
  if (blockNumber === undefined) {
1012
- return undefined;
1127
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1013
1128
  }
1014
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
1015
- const blockHash = blockHashes[blockHashIndex];
1016
- if (!blockHash) {
1017
- return undefined;
1129
+ const blockHash = blockNumberToHash.get(blockNumber);
1130
+ if (blockHash === undefined) {
1131
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
1018
1132
  }
1019
1133
  return {
1020
- l2BlockNumber: BlockNumber(Number(blockNumber)),
1021
- l2BlockHash: L2BlockHash.fromField(blockHash),
1134
+ l2BlockNumber: blockNumber,
1135
+ l2BlockHash: new BlockHash(blockHash),
1022
1136
  data: index
1023
1137
  };
1024
1138
  });
1025
1139
  }
1026
- async getNullifierSiblingPath(block, leafIndex) {
1027
- const committedDb = await this.#getWorldState(block);
1028
- return committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, leafIndex);
1029
- }
1030
- async getNoteHashSiblingPath(block, leafIndex) {
1031
- const committedDb = await this.#getWorldState(block);
1032
- return committedDb.getSiblingPath(MerkleTreeId.NOTE_HASH_TREE, leafIndex);
1033
- }
1034
- async getArchiveMembershipWitness(block, archive) {
1035
- const committedDb = await this.#getWorldState(block);
1140
+ async getBlockHashMembershipWitness(referenceBlock, blockHash) {
1141
+ // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
1142
+ // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1143
+ // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1144
+ const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1145
+ const committedDb = await this.#getWorldState(BlockNumber(referenceBlockNumber - 1));
1036
1146
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE, [
1037
- archive
1147
+ blockHash
1038
1148
  ]);
1039
1149
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1040
1150
  }
1041
- async getNoteHashMembershipWitness(block, noteHash) {
1042
- const committedDb = await this.#getWorldState(block);
1151
+ async getNoteHashMembershipWitness(referenceBlock, noteHash) {
1152
+ const committedDb = await this.#getWorldState(referenceBlock);
1043
1153
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE, [
1044
1154
  noteHash
1045
1155
  ]);
1046
1156
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1047
1157
  }
1048
- async getL1ToL2MessageMembershipWitness(block, l1ToL2Message) {
1049
- const db = await this.#getWorldState(block);
1158
+ async getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
1159
+ const db = await this.#getWorldState(referenceBlock);
1050
1160
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
1051
1161
  l1ToL2Message
1052
1162
  ]);
@@ -1059,9 +1169,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1059
1169
  witness.path
1060
1170
  ];
1061
1171
  }
1062
- async getL1ToL2MessageBlock(l1ToL2Message) {
1172
+ async getL1ToL2MessageCheckpoint(l1ToL2Message) {
1063
1173
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1064
- return messageIndex ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex)) : undefined;
1174
+ return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1065
1175
  }
1066
1176
  /**
1067
1177
  * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
@@ -1076,12 +1186,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1076
1186
  * @param epoch - The epoch at which to get the data.
1077
1187
  * @returns The L2 to L1 messages (empty array if the epoch is not found).
1078
1188
  */ async getL2ToL1Messages(epoch) {
1079
- // Assumes `getBlocksForEpoch` returns blocks in ascending order of block number.
1080
- const blocks = await this.blockSource.getBlocksForEpoch(epoch);
1189
+ // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1190
+ const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1081
1191
  const blocksInCheckpoints = [];
1082
1192
  let previousSlotNumber = SlotNumber.ZERO;
1083
1193
  let checkpointIndex = -1;
1084
- for (const block of blocks){
1194
+ for (const checkpointedBlock of checkpointedBlocks){
1195
+ const block = checkpointedBlock.block;
1085
1196
  const slotNumber = block.header.globalVariables.slotNumber;
1086
1197
  if (slotNumber !== previousSlotNumber) {
1087
1198
  checkpointIndex++;
@@ -1092,16 +1203,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1092
1203
  }
1093
1204
  return blocksInCheckpoints.map((blocks)=>blocks.map((block)=>block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs)));
1094
1205
  }
1095
- async getArchiveSiblingPath(block, leafIndex) {
1096
- const committedDb = await this.#getWorldState(block);
1097
- return committedDb.getSiblingPath(MerkleTreeId.ARCHIVE, leafIndex);
1098
- }
1099
- async getPublicDataSiblingPath(block, leafIndex) {
1100
- const committedDb = await this.#getWorldState(block);
1101
- return committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, leafIndex);
1102
- }
1103
- async getNullifierMembershipWitness(block, nullifier) {
1104
- const db = await this.#getWorldState(block);
1206
+ async getNullifierMembershipWitness(referenceBlock, nullifier) {
1207
+ const db = await this.#getWorldState(referenceBlock);
1105
1208
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [
1106
1209
  nullifier.toBuffer()
1107
1210
  ]);
@@ -1117,7 +1220,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1117
1220
  }
1118
1221
  /**
1119
1222
  * Returns a low nullifier membership witness for a given nullifier at a given block.
1120
- * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1223
+ * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1224
+ * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1121
1225
  * @param nullifier - Nullifier we try to find the low nullifier witness for.
1122
1226
  * @returns The low nullifier membership witness (if found).
1123
1227
  * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
@@ -1128,8 +1232,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1128
1232
  * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1129
1233
  * index of the nullifier itself when it already exists in the tree.
1130
1234
  * TODO: This is a confusing behavior and we should eventually address that.
1131
- */ async getLowNullifierMembershipWitness(block, nullifier) {
1132
- const committedDb = await this.#getWorldState(block);
1235
+ */ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1236
+ const committedDb = await this.#getWorldState(referenceBlock);
1133
1237
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1134
1238
  if (!findResult) {
1135
1239
  return undefined;
@@ -1142,8 +1246,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1142
1246
  const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1143
1247
  return new NullifierMembershipWitness(BigInt(index), preimageData, siblingPath);
1144
1248
  }
1145
- async getPublicDataWitness(block, leafSlot) {
1146
- const committedDb = await this.#getWorldState(block);
1249
+ async getPublicDataWitness(referenceBlock, leafSlot) {
1250
+ const committedDb = await this.#getWorldState(referenceBlock);
1147
1251
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1148
1252
  if (!lowLeafResult) {
1149
1253
  return undefined;
@@ -1153,8 +1257,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1153
1257
  return new PublicDataWitness(lowLeafResult.index, preimage, path);
1154
1258
  }
1155
1259
  }
1156
- async getPublicStorageAt(block, contract, slot) {
1157
- const committedDb = await this.#getWorldState(block);
1260
+ async getPublicStorageAt(referenceBlock, contract, slot) {
1261
+ const committedDb = await this.#getWorldState(referenceBlock);
1158
1262
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1159
1263
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1160
1264
  if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
@@ -1164,14 +1268,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1164
1268
  return preimage.leaf.value;
1165
1269
  }
1166
1270
  async getBlockHeader(block = 'latest') {
1167
- if (L2BlockHash.isL2BlockHash(block)) {
1271
+ if (BlockHash.isBlockHash(block)) {
1168
1272
  const initialBlockHash = await this.#getInitialHeaderHash();
1169
1273
  if (block.equals(initialBlockHash)) {
1170
1274
  // Block source doesn't handle initial header so we need to handle the case separately.
1171
1275
  return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1172
1276
  }
1173
- const blockHashFr = Fr.fromBuffer(block.toBuffer());
1174
- return this.blockSource.getBlockHeaderByHash(blockHashFr);
1277
+ return this.blockSource.getBlockHeaderByHash(block);
1175
1278
  } else {
1176
1279
  // Block source doesn't handle initial header so we need to handle the case separately.
1177
1280
  const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
@@ -1188,6 +1291,12 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1188
1291
  */ async getBlockHeaderByArchive(archive) {
1189
1292
  return await this.blockSource.getBlockHeaderByArchive(archive);
1190
1293
  }
1294
+ getBlockData(number) {
1295
+ return this.blockSource.getBlockData(number);
1296
+ }
1297
+ getBlockDataByArchive(archive) {
1298
+ return this.blockSource.getBlockDataByArchive(archive);
1299
+ }
1191
1300
  /**
1192
1301
  * Simulates the public part of a transaction with the current state.
1193
1302
  * @param tx - The transaction to simulate.
@@ -1200,17 +1309,20 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1200
1309
  throw new BadRequestError(`Transaction total gas limit ${txGasLimit + teardownGasLimit} (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${this.config.rpcSimulatePublicMaxGasLimit} for simulation`);
1201
1310
  }
1202
1311
  const txHash = tx.getTxHash();
1203
- const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
1312
+ const latestBlockNumber = await this.blockSource.getBlockNumber();
1313
+ const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1204
1314
  // If sequencer is not initialized, we just set these values to zero for simulation.
1205
1315
  const coinbase = EthAddress.ZERO;
1206
1316
  const feeRecipient = AztecAddress.ZERO;
1207
1317
  const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(blockNumber, coinbase, feeRecipient);
1208
- const publicProcessorFactory = new PublicProcessorFactory(this.contractDataSource, new DateProvider(), this.telemetry);
1318
+ const publicProcessorFactory = new PublicProcessorFactory(this.contractDataSource, new DateProvider(), this.telemetry, this.log.getBindings());
1209
1319
  this.log.verbose(`Simulating public calls for tx ${txHash}`, {
1210
1320
  globalVariables: newGlobalVariables.toInspect(),
1211
1321
  txHash,
1212
1322
  blockNumber
1213
1323
  });
1324
+ // Ensure world-state has caught up with the latest block we loaded from the archiver
1325
+ await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1214
1326
  const merkleTreeFork = await this.worldStateSynchronizer.fork();
1215
1327
  try {
1216
1328
  const config = PublicSimulatorConfig.from({
@@ -1225,7 +1337,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1225
1337
  });
1226
1338
  const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1227
1339
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1228
- const [processedTxs, failedTxs, _usedTxs, returns] = await processor.process([
1340
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([
1229
1341
  tx
1230
1342
  ]);
1231
1343
  // REFACTOR: Consider returning the error rather than throwing
@@ -1236,7 +1348,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1236
1348
  throw failedTxs[0].error;
1237
1349
  }
1238
1350
  const [processedTx] = processedTxs;
1239
- return new PublicSimulationOutput(processedTx.revertReason, processedTx.globalVariables, processedTx.txEffect, returns, processedTx.gasUsed);
1351
+ return new PublicSimulationOutput(processedTx.revertReason, processedTx.globalVariables, processedTx.txEffect, returns, processedTx.gasUsed, debugLogs);
1240
1352
  } finally{
1241
1353
  await merkleTreeFork.close();
1242
1354
  }
@@ -1244,19 +1356,26 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1244
1356
  async isValidTx(tx, { isSimulation, skipFeeEnforcement } = {}) {
1245
1357
  const db = this.worldStateSynchronizer.getCommitted();
1246
1358
  const verifier = isSimulation ? undefined : this.proofVerifier;
1247
- // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
1359
+ // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1248
1360
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1249
1361
  const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
1250
- const validator = createValidatorForAcceptingTxs(db, this.contractDataSource, verifier, {
1362
+ const l1Constants = await this.blockSource.getL1Constants();
1363
+ const validator = createTxValidatorForAcceptingTxsOverRPC(db, this.contractDataSource, verifier, {
1251
1364
  timestamp: nextSlotTimestamp,
1252
1365
  blockNumber,
1253
1366
  l1ChainId: this.l1ChainId,
1254
1367
  rollupVersion: this.version,
1255
- setupAllowList: this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions(),
1368
+ setupAllowList: [
1369
+ ...await getDefaultAllowedSetupFunctions(),
1370
+ ...this.config.txPublicSetupAllowListExtend ?? []
1371
+ ],
1256
1372
  gasFees: await this.getCurrentMinFees(),
1257
1373
  skipFeeEnforcement,
1258
- txsPermitted: !this.config.disableTransactions
1259
- });
1374
+ txsPermitted: !this.config.disableTransactions,
1375
+ rollupManaLimit: l1Constants.rollupManaLimit,
1376
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1377
+ maxBlockDAGas: this.config.validateMaxDABlockGas
1378
+ }, this.log.getBindings());
1260
1379
  return await validator.validateTx(tx);
1261
1380
  }
1262
1381
  getConfig() {
@@ -1398,9 +1517,76 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1398
1517
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1399
1518
  }
1400
1519
  }
1520
+ async reloadKeystore() {
1521
+ if (!this.config.keyStoreDirectory?.length) {
1522
+ throw new BadRequestError('Cannot reload keystore: node is not using a file-based keystore. ' + 'Set KEY_STORE_DIRECTORY to use file-based keystores.');
1523
+ }
1524
+ if (!this.validatorClient) {
1525
+ throw new BadRequestError('Cannot reload keystore: validator is not enabled.');
1526
+ }
1527
+ this.log.info('Reloading keystore from disk');
1528
+ // Re-read and validate keystore files
1529
+ const keyStores = loadKeystores(this.config.keyStoreDirectory);
1530
+ const newManager = new KeystoreManager(mergeKeystores(keyStores));
1531
+ await newManager.validateSigners();
1532
+ ValidatorClient.validateKeyStoreConfiguration(newManager, this.log);
1533
+ // Validate that every validator's publisher keys overlap with the L1 signers
1534
+ // that were initialized at startup. Publishers cannot be hot-reloaded, so a
1535
+ // validator with a publisher key that doesn't match any existing L1 signer
1536
+ // would silently fail on every proposer slot.
1537
+ if (this.keyStoreManager && this.sequencer) {
1538
+ const oldAdapter = NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager);
1539
+ const availablePublishers = new Set(oldAdapter.getAttesterAddresses().flatMap((a)=>oldAdapter.getPublisherAddresses(a).map((p)=>p.toString().toLowerCase())));
1540
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
1541
+ for (const attester of newAdapter.getAttesterAddresses()){
1542
+ const pubs = newAdapter.getPublisherAddresses(attester);
1543
+ if (pubs.length > 0 && !pubs.some((p)=>availablePublishers.has(p.toString().toLowerCase()))) {
1544
+ throw new BadRequestError(`Cannot reload keystore: validator ${attester} has publisher keys ` + `[${pubs.map((p)=>p.toString()).join(', ')}] but none match the L1 signers initialized at startup ` + `[${[
1545
+ ...availablePublishers
1546
+ ].join(', ')}]. Publishers cannot be hot-reloaded — ` + `use an existing publisher key or restart the node.`);
1547
+ }
1548
+ }
1549
+ }
1550
+ // Build adapters for old and new keystores to compute diff
1551
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
1552
+ const newAddresses = newAdapter.getAttesterAddresses();
1553
+ const oldAddresses = this.keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager).getAttesterAddresses() : [];
1554
+ const oldSet = new Set(oldAddresses.map((a)=>a.toString()));
1555
+ const newSet = new Set(newAddresses.map((a)=>a.toString()));
1556
+ const added = newAddresses.filter((a)=>!oldSet.has(a.toString()));
1557
+ const removed = oldAddresses.filter((a)=>!newSet.has(a.toString()));
1558
+ if (added.length > 0) {
1559
+ this.log.info(`Keystore reload: adding attester keys: ${added.map((a)=>a.toString()).join(', ')}`);
1560
+ }
1561
+ if (removed.length > 0) {
1562
+ this.log.info(`Keystore reload: removing attester keys: ${removed.map((a)=>a.toString()).join(', ')}`);
1563
+ }
1564
+ if (added.length === 0 && removed.length === 0) {
1565
+ this.log.info('Keystore reload: attester keys unchanged');
1566
+ }
1567
+ // Update the validator client (coinbase, feeRecipient, attester keys)
1568
+ this.validatorClient.reloadKeystore(newManager);
1569
+ // Update the publisher factory's keystore so newly-added validators
1570
+ // can be matched to existing publisher keys when proposing blocks.
1571
+ if (this.sequencer) {
1572
+ this.sequencer.updatePublisherNodeKeyStore(newAdapter);
1573
+ }
1574
+ // Update slasher's "don't-slash-self" list with new validator addresses
1575
+ if (this.slasherClient && !this.config.slashSelfAllowed) {
1576
+ const slashValidatorsNever = unique([
1577
+ ...this.config.slashValidatorsNever ?? [],
1578
+ ...newAddresses
1579
+ ].map((a)=>a.toString())).map(EthAddress.fromString);
1580
+ this.slasherClient.updateConfig({
1581
+ slashValidatorsNever
1582
+ });
1583
+ }
1584
+ this.keyStoreManager = newManager;
1585
+ this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1586
+ }
1401
1587
  #getInitialHeaderHash() {
1402
1588
  if (!this.initialHeaderHashPromise) {
1403
- this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash().then((hash)=>L2BlockHash.fromField(hash));
1589
+ this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
1404
1590
  }
1405
1591
  return this.initialHeaderHashPromise;
1406
1592
  }
@@ -1420,14 +1606,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1420
1606
  this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
1421
1607
  return this.worldStateSynchronizer.getCommitted();
1422
1608
  }
1423
- if (L2BlockHash.isL2BlockHash(block)) {
1609
+ if (BlockHash.isBlockHash(block)) {
1424
1610
  const initialBlockHash = await this.#getInitialHeaderHash();
1425
1611
  if (block.equals(initialBlockHash)) {
1426
1612
  // Block source doesn't handle initial header so we need to handle the case separately.
1427
1613
  return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1428
1614
  }
1429
- const blockHashFr = Fr.fromBuffer(block.toBuffer());
1430
- const header = await this.blockSource.getBlockHeaderByHash(blockHashFr);
1615
+ const header = await this.blockSource.getBlockHeaderByHash(block);
1431
1616
  if (!header) {
1432
1617
  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.`);
1433
1618
  }
@@ -1445,6 +1630,23 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1445
1630
  return this.worldStateSynchronizer.getSnapshot(blockNumber);
1446
1631
  }
1447
1632
  }
1633
+ /** Resolves a block parameter to a block number. */ async resolveBlockNumber(block) {
1634
+ if (block === 'latest') {
1635
+ return BlockNumber(await this.blockSource.getBlockNumber());
1636
+ }
1637
+ if (BlockHash.isBlockHash(block)) {
1638
+ const initialBlockHash = await this.#getInitialHeaderHash();
1639
+ if (block.equals(initialBlockHash)) {
1640
+ return BlockNumber.ZERO;
1641
+ }
1642
+ const header = await this.blockSource.getBlockHeaderByHash(block);
1643
+ if (!header) {
1644
+ throw new Error(`Block hash ${block.toString()} not found.`);
1645
+ }
1646
+ return header.getBlockNumber();
1647
+ }
1648
+ return block;
1649
+ }
1448
1650
  /**
1449
1651
  * Ensure we fully sync the world state
1450
1652
  * @returns A promise that fulfils once the world state is synced