@aztec/aztec-node 0.0.1-commit.e588bc7e5 → 0.0.1-commit.e5a3663dd

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.
@@ -386,6 +386,7 @@ import { Fr } from '@aztec/foundation/curves/bn254';
386
386
  import { EthAddress } from '@aztec/foundation/eth-address';
387
387
  import { BadRequestError } from '@aztec/foundation/json-rpc';
388
388
  import { createLogger } from '@aztec/foundation/log';
389
+ import { retryUntil } from '@aztec/foundation/retry';
389
390
  import { count } from '@aztec/foundation/string';
390
391
  import { DateProvider, Timer } from '@aztec/foundation/timer';
391
392
  import { MembershipWitness } from '@aztec/foundation/trees';
@@ -396,12 +397,12 @@ import { createP2PClient, createTxValidatorForAcceptingTxsOverRPC, getDefaultAll
396
397
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
397
398
  import { createProverNode } from '@aztec/prover-node';
398
399
  import { createKeyStoreForProver } from '@aztec/prover-node/config';
399
- import { GlobalVariableBuilder, SequencerClient } from '@aztec/sequencer-client';
400
+ import { FeeProviderImpl, GlobalVariableBuilder, SequencerClient } from '@aztec/sequencer-client';
400
401
  import { PublicProcessorFactory } from '@aztec/simulator/server';
401
402
  import { AttestationsBlockWatcher, EpochPruneWatcher, createSlasher } from '@aztec/slasher';
402
403
  import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
403
404
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
404
- import { BlockHash, L2Block } from '@aztec/stdlib/block';
405
+ import { BlockHash, L2Block, inspectBlockParameter } from '@aztec/stdlib/block';
405
406
  import { GasFees } from '@aztec/stdlib/gas';
406
407
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
407
408
  import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
@@ -416,6 +417,7 @@ import { FullNodeCheckpointsBuilder as CheckpointsBuilder, FullNodeCheckpointsBu
416
417
  import { createWorldStateSynchronizer } from '@aztec/world-state';
417
418
  import { createPublicClient } from 'viem';
418
419
  import { createSentinel } from '../sentinel/factory.js';
420
+ import { blockResponseFromBlockData, blockResponseFromL2Block, checkpointResponseFromCheckpointData, checkpointResponseFromPublishedCheckpoint } from './block_response_helpers.js';
419
421
  import { createKeyStoreForValidator } from './config.js';
420
422
  import { NodeMetrics } from './node_metrics.js';
421
423
  _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
@@ -436,9 +438,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
436
438
  slasherClient;
437
439
  validatorsSentinel;
438
440
  epochPruneWatcher;
441
+ attestationsBlockWatcher;
439
442
  l1ChainId;
440
443
  version;
441
444
  globalVariableBuilder;
445
+ feeProvider;
442
446
  epochCache;
443
447
  packageVersion;
444
448
  peerProofVerifier;
@@ -463,7 +467,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
463
467
  // Prevent two snapshot operations to happen simultaneously
464
468
  isUploadingSnapshot;
465
469
  tracer;
466
- constructor(config, p2pClient, blockSource, logsSource, contractDataSource, l1ToL2MessageSource, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, epochPruneWatcher, l1ChainId, version, globalVariableBuilder, epochCache, packageVersion, peerProofVerifier, rpcProofVerifier, telemetry = getTelemetryClient(), log = createLogger('node'), blobClient, validatorClient, keyStoreManager, debugLogStore = new NullDebugLogStore()){
470
+ constructor(config, p2pClient, blockSource, logsSource, contractDataSource, l1ToL2MessageSource, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, epochPruneWatcher, attestationsBlockWatcher, l1ChainId, version, globalVariableBuilder, feeProvider, epochCache, packageVersion, peerProofVerifier, rpcProofVerifier, telemetry = getTelemetryClient(), log = createLogger('node'), blobClient, validatorClient, keyStoreManager, debugLogStore = new NullDebugLogStore()){
467
471
  this.config = config;
468
472
  this.p2pClient = p2pClient;
469
473
  this.blockSource = blockSource;
@@ -476,9 +480,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
476
480
  this.slasherClient = slasherClient;
477
481
  this.validatorsSentinel = validatorsSentinel;
478
482
  this.epochPruneWatcher = epochPruneWatcher;
483
+ this.attestationsBlockWatcher = attestationsBlockWatcher;
479
484
  this.l1ChainId = l1ChainId;
480
485
  this.version = version;
481
486
  this.globalVariableBuilder = globalVariableBuilder;
487
+ this.feeProvider = feeProvider;
482
488
  this.epochCache = epochCache;
483
489
  this.packageVersion = packageVersion;
484
490
  this.peerProofVerifier = peerProofVerifier;
@@ -509,9 +515,273 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
509
515
  const status = await this.worldStateSynchronizer.status();
510
516
  return status.syncSummary;
511
517
  }
518
+ async getChainTips() {
519
+ const { proposed, checkpointed, proven, finalized } = await this.blockSource.getL2Tips();
520
+ return {
521
+ proposed,
522
+ checkpointed,
523
+ proven,
524
+ finalized
525
+ };
526
+ }
512
527
  getL2Tips() {
513
528
  return this.blockSource.getL2Tips();
514
529
  }
530
+ async getBlockHeader(number) {
531
+ const resolvedNumber = number === 'latest' ? await this.blockSource.getBlockNumber() : number;
532
+ if (resolvedNumber === BlockNumber.ZERO) {
533
+ return this.worldStateSynchronizer.getCommitted().getInitialHeader();
534
+ }
535
+ return this.blockSource.getBlockHeader(resolvedNumber);
536
+ }
537
+ async getCheckpointedBlocks(from, limit) {
538
+ return await this.blockSource.getCheckpointedBlocks(from, limit) ?? [];
539
+ }
540
+ getCheckpointsDataForEpoch(epoch) {
541
+ return this.blockSource.getCheckpointsDataForEpoch(epoch);
542
+ }
543
+ getBlockNumber(tip) {
544
+ switch(tip){
545
+ case undefined:
546
+ case 'proposed':
547
+ return this.blockSource.getBlockNumber();
548
+ case 'checkpointed':
549
+ return this.blockSource.getCheckpointedL2BlockNumber();
550
+ case 'proven':
551
+ return this.blockSource.getProvenBlockNumber();
552
+ case 'finalized':
553
+ return this.blockSource.getFinalizedL2BlockNumber();
554
+ }
555
+ }
556
+ async getCheckpointNumber(tip) {
557
+ switch(tip){
558
+ case undefined:
559
+ case 'proposed':
560
+ case 'checkpointed':
561
+ return await this.blockSource.getCheckpointNumber();
562
+ case 'proven':
563
+ case 'finalized':
564
+ {
565
+ const tips = await this.blockSource.getL2Tips();
566
+ return tip === 'proven' ? tips.proven.checkpoint.number : tips.finalized.checkpoint.number;
567
+ }
568
+ }
569
+ }
570
+ isChainTip(value) {
571
+ return value === 'proposed' || value === 'checkpointed' || value === 'proven' || value === 'finalized';
572
+ }
573
+ async resolveBlockParameter(param) {
574
+ if (BlockHash.isBlockHash(param)) {
575
+ return {
576
+ hash: param
577
+ };
578
+ }
579
+ if (typeof param === 'number') {
580
+ return {
581
+ number: param
582
+ };
583
+ }
584
+ if (param === 'latest') {
585
+ return {
586
+ number: await this.blockSource.getBlockNumber()
587
+ };
588
+ }
589
+ if (this.isChainTip(param)) {
590
+ return {
591
+ number: await this.getBlockNumber(param)
592
+ };
593
+ }
594
+ if (typeof param === 'object' && param !== null) {
595
+ if ('number' in param) {
596
+ return {
597
+ number: param.number
598
+ };
599
+ }
600
+ if ('hash' in param) {
601
+ return {
602
+ hash: param.hash
603
+ };
604
+ }
605
+ if ('archive' in param) {
606
+ return {
607
+ archive: param.archive
608
+ };
609
+ }
610
+ }
611
+ throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(param)}`);
612
+ }
613
+ async resolveCheckpointParameter(param) {
614
+ if (typeof param === 'number') {
615
+ return {
616
+ number: param
617
+ };
618
+ }
619
+ if (param === 'latest') {
620
+ return {
621
+ number: await this.blockSource.getCheckpointNumber()
622
+ };
623
+ }
624
+ if (this.isChainTip(param)) {
625
+ return {
626
+ number: await this.getCheckpointNumber(param)
627
+ };
628
+ }
629
+ if (typeof param === 'object' && param !== null) {
630
+ if ('number' in param) {
631
+ return {
632
+ number: param.number
633
+ };
634
+ }
635
+ if ('slot' in param) {
636
+ return {
637
+ slot: param.slot
638
+ };
639
+ }
640
+ }
641
+ throw new BadRequestError(`Invalid CheckpointParameter: ${JSON.stringify(param)}`);
642
+ }
643
+ async getBlock(param, options = {}) {
644
+ const resolved = await this.resolveBlockParameter(param);
645
+ const wantTxs = !!options.includeTransactions;
646
+ const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
647
+ if (resolved.hash !== undefined) {
648
+ const initial = await this.#getInitialHeaderHash();
649
+ if (resolved.hash.equals(initial)) {
650
+ return await this.buildGenesisBlockResponse(options);
651
+ }
652
+ if (wantTxs) {
653
+ const block = await this.blockSource.getL2BlockByHash(resolved.hash);
654
+ if (!block) {
655
+ return undefined;
656
+ }
657
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(block.number) : undefined;
658
+ return await blockResponseFromL2Block(block, options, ctx);
659
+ }
660
+ const data = await this.blockSource.getBlockHeaderByHash(resolved.hash);
661
+ if (!data) {
662
+ return undefined;
663
+ }
664
+ const blockNumber = data.globalVariables.blockNumber;
665
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(blockNumber) : undefined;
666
+ if (ctx) {
667
+ return blockResponseFromBlockData(ctx.data, blockNumber, options, ctx);
668
+ }
669
+ const blockData = await this.blockSource.getBlockData(blockNumber);
670
+ if (!blockData) {
671
+ return undefined;
672
+ }
673
+ return blockResponseFromBlockData(blockData, blockNumber, options);
674
+ }
675
+ if (resolved.archive !== undefined) {
676
+ if (wantTxs) {
677
+ const block = await this.blockSource.getL2BlockByArchive(resolved.archive);
678
+ if (!block) {
679
+ return undefined;
680
+ }
681
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(block.number) : undefined;
682
+ return await blockResponseFromL2Block(block, options, ctx);
683
+ }
684
+ const data = await this.blockSource.getBlockDataByArchive(resolved.archive);
685
+ if (!data) {
686
+ return undefined;
687
+ }
688
+ const blockNumber = data.header.globalVariables.blockNumber;
689
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(blockNumber) : undefined;
690
+ return blockResponseFromBlockData(data, blockNumber, options, ctx);
691
+ }
692
+ const blockNumber = resolved.number;
693
+ if (blockNumber === BlockNumber.ZERO) {
694
+ return await this.buildGenesisBlockResponse(options);
695
+ }
696
+ if (wantTxs) {
697
+ const block = await this.blockSource.getL2Block(blockNumber);
698
+ if (!block) {
699
+ return undefined;
700
+ }
701
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(blockNumber) : undefined;
702
+ return await blockResponseFromL2Block(block, options, ctx);
703
+ }
704
+ const ctx = await this.blockSource.getBlockDataWithCheckpointContext(blockNumber);
705
+ if (!ctx) {
706
+ return undefined;
707
+ }
708
+ return blockResponseFromBlockData(ctx.data, blockNumber, options, ctx);
709
+ }
710
+ async getBlocks(from, limit, options = {}) {
711
+ const wantTxs = !!options.includeTransactions;
712
+ const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
713
+ if (wantTxs) {
714
+ const blocks = await this.blockSource.getBlocks(from, limit);
715
+ return await Promise.all(blocks.map(async (block)=>{
716
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(block.number) : undefined;
717
+ return blockResponseFromL2Block(block, options, ctx);
718
+ }));
719
+ }
720
+ const results = [];
721
+ for(let i = 0; i < limit; i++){
722
+ const blockNumber = BlockNumber(from + i);
723
+ const ctx = await this.blockSource.getBlockDataWithCheckpointContext(blockNumber);
724
+ if (!ctx) {
725
+ break;
726
+ }
727
+ results.push(blockResponseFromBlockData(ctx.data, blockNumber, options, ctx));
728
+ }
729
+ return results;
730
+ }
731
+ async getCheckpoint(param, options = {}) {
732
+ const resolved = await this.resolveCheckpointParameter(param);
733
+ let checkpointNumber = resolved.number;
734
+ if (checkpointNumber === undefined && resolved.slot !== undefined) {
735
+ checkpointNumber = await this.blockSource.getCheckpointNumberBySlot(resolved.slot);
736
+ }
737
+ if (checkpointNumber === undefined) {
738
+ return undefined;
739
+ }
740
+ if (options.includeBlocks) {
741
+ const [checkpoint] = await this.blockSource.getCheckpoints(checkpointNumber, 1);
742
+ if (!checkpoint) {
743
+ return undefined;
744
+ }
745
+ return await checkpointResponseFromPublishedCheckpoint(checkpoint, options);
746
+ }
747
+ const data = await this.blockSource.getCheckpointData(checkpointNumber);
748
+ if (!data) {
749
+ return undefined;
750
+ }
751
+ return checkpointResponseFromCheckpointData(data, options);
752
+ }
753
+ async getCheckpoints(from, limit, options = {}) {
754
+ if (options.includeBlocks) {
755
+ const checkpoints = await this.blockSource.getCheckpoints(from, limit);
756
+ return await Promise.all(checkpoints.map((cp)=>checkpointResponseFromPublishedCheckpoint(cp, options)));
757
+ }
758
+ const datas = await this.blockSource.getCheckpointDataRange(from, limit);
759
+ return datas.map((d)=>checkpointResponseFromCheckpointData(d, options));
760
+ }
761
+ async buildGenesisBlockResponse(options) {
762
+ const initial = this.worldStateSynchronizer.getCommitted().getInitialHeader();
763
+ const empty = L2Block.empty(initial);
764
+ const response = {
765
+ header: empty.header,
766
+ archive: empty.archive,
767
+ hash: await this.#getInitialHeaderHash(),
768
+ checkpointNumber: empty.checkpointNumber,
769
+ indexWithinCheckpoint: empty.indexWithinCheckpoint,
770
+ number: empty.number
771
+ };
772
+ if (options.includeTransactions) {
773
+ response.body = empty.body;
774
+ }
775
+ if (options.includeL1PublishInfo) {
776
+ response.l1 = {
777
+ published: false
778
+ };
779
+ }
780
+ if (options.includeAttestations) {
781
+ response.attestations = [];
782
+ }
783
+ return response;
784
+ }
515
785
  /**
516
786
  * initializes the Aztec Node, wait for component to sync.
517
787
  * @param config - The configuration to be used by the aztec node.
@@ -593,234 +863,261 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
593
863
  const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, {
594
864
  dateProvider
595
865
  });
596
- const archiver = await createArchiver(config, {
597
- blobClient,
598
- epochCache,
599
- telemetry,
600
- dateProvider
601
- }, {
602
- blockUntilSync: !config.skipArchiverInitialSync
603
- });
604
- // now create the merkle trees and the world state synchronizer
605
- const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.prefilledPublicData, telemetry);
606
- const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
607
- let peerProofVerifier;
608
- let rpcProofVerifier;
609
- if (useRealVerifiers) {
610
- peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
611
- const rpcVerifier = await BBCircuitVerifier.new(config);
612
- rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
613
- } else {
614
- peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
615
- rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
616
- }
617
- let debugLogStore;
618
- if (!config.realProofs) {
619
- log.warn(`Aztec node is accepting fake proofs`);
620
- debugLogStore = new InMemoryDebugLogStore();
621
- log.info('Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served');
622
- } else {
623
- debugLogStore = new NullDebugLogStore();
624
- }
625
- const proverOnly = config.enableProverNode && config.disableValidator;
626
- if (proverOnly) {
627
- log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
628
- }
629
- // create the tx pool and the p2p client, which will need the l2 block source
630
- const p2pClient = await createP2PClient(config, archiver, peerProofVerifier, worldStateSynchronizer, epochCache, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
631
- // We'll accumulate sentinel watchers here
632
- const watchers = [];
633
- // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
634
- // Override maxTxsPerCheckpoint with the validator-specific limit if set.
635
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder({
636
- ...config,
637
- l1GenesisTime,
638
- slotDuration: Number(slotDuration),
639
- rollupManaLimit,
640
- maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint
641
- }, worldStateSynchronizer, archiver, dateProvider, telemetry);
642
- let validatorClient;
643
- if (!proverOnly) {
644
- // Create validator client if required
645
- validatorClient = await createValidatorClient(config, {
646
- checkpointsBuilder: validatorCheckpointsBuilder,
647
- worldState: worldStateSynchronizer,
648
- p2pClient,
649
- telemetry,
650
- dateProvider,
651
- epochCache,
652
- blockSource: archiver,
653
- l1ToL2MessageSource: archiver,
654
- keyStoreManager,
866
+ // Track started resources so we can clean up on partial failure during node creation.
867
+ const started = [];
868
+ try {
869
+ const archiver = await createArchiver(config, {
655
870
  blobClient,
656
- slashingProtectionDb: deps.slashingProtectionDb
657
- });
658
- // If we have a validator client, register it as a source of offenses for the slasher,
659
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
660
- // like attestations or auths will fail.
661
- if (validatorClient) {
662
- watchers.push(validatorClient);
663
- const vc = validatorClient;
664
- const getValidatorAddresses = ()=>vc.getValidatorAddresses().map((a)=>a.toString());
665
- validatorClient.getProposalHandler().register(p2pClient, true, archiver, getValidatorAddresses);
666
- if (!options.dontStartSequencer) {
667
- await validatorClient.registerHandlers();
668
- }
669
- }
670
- }
671
- // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
672
- // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
673
- // while non-reexecution is used for validating the proposals and collecting their txs.
674
- // Checkpoint proposals rebuild blobs if the blob client can upload blobs.
675
- if (!validatorClient) {
676
- const reexecute = !!config.alwaysReexecuteBlockProposals;
677
- log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
678
- createProposalHandler(config, {
679
- checkpointsBuilder: validatorCheckpointsBuilder,
680
- worldState: worldStateSynchronizer,
681
871
  epochCache,
682
- blockSource: archiver,
683
- l1ToL2MessageSource: archiver,
684
- p2pClient,
685
- blobClient,
686
- dateProvider,
687
- telemetry
688
- }).register(p2pClient, reexecute, archiver);
689
- }
690
- // Start world state and wait for it to sync to the archiver.
691
- await worldStateSynchronizer.start();
692
- // Start p2p. Note that it depends on world state to be running.
693
- await p2pClient.start();
694
- let validatorsSentinel;
695
- let epochPruneWatcher;
696
- let attestationsBlockWatcher;
697
- if (!proverOnly) {
698
- validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
699
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
700
- watchers.push(validatorsSentinel);
701
- }
702
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
703
- epochPruneWatcher = new EpochPruneWatcher(archiver, archiver, epochCache, p2pClient.getTxProvider(), validatorCheckpointsBuilder, config);
704
- watchers.push(epochPruneWatcher);
705
- }
706
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
707
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
708
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
709
- watchers.push(attestationsBlockWatcher);
710
- }
711
- }
712
- // Start p2p-related services once the archiver has completed sync
713
- void archiver.waitForInitialSync().then(async ()=>{
714
- await p2pClient.start();
715
- await validatorsSentinel?.start();
716
- await epochPruneWatcher?.start();
717
- await attestationsBlockWatcher?.start();
718
- log.info(`All p2p services started`);
719
- }).catch((err)=>log.error('Failed to start p2p services after archiver sync', err));
720
- const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, {
721
- l1Contracts: config.l1Contracts,
722
- ethereumSlotDuration: config.ethereumSlotDuration,
723
- rollupVersion: BigInt(config.rollupVersion),
724
- l1GenesisTime,
725
- slotDuration: Number(slotDuration)
726
- });
727
- // Validator enabled, create/start relevant service
728
- let sequencer;
729
- let slasherClient;
730
- if (!config.disableValidator && validatorClient) {
731
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
732
- // as they are executed when the node is selected as proposer.
733
- const validatorAddresses = keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses() : [];
734
- slasherClient = await createSlasher(config, config.l1Contracts, getPublicClient(config), watchers, dateProvider, epochCache, validatorAddresses, undefined);
735
- await slasherClient.start();
736
- const l1TxUtils = config.sequencerPublisherForwarderAddress ? await createForwarderL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), config.sequencerPublisherForwarderAddress, {
737
- ...config,
738
- scope: 'sequencer'
739
- }, {
740
872
  telemetry,
741
- logger: log.createChild('l1-tx-utils'),
742
- dateProvider,
743
- kzg: Blob.getViemKzgInstance()
744
- }) : await createL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
745
- ...config,
746
- scope: 'sequencer'
873
+ dateProvider
747
874
  }, {
748
- telemetry,
749
- logger: log.createChild('l1-tx-utils'),
750
- dateProvider,
751
- kzg: Blob.getViemKzgInstance()
875
+ blockUntilSync: !config.skipArchiverInitialSync
752
876
  });
753
- // Create a funder L1TxUtils from the keystore funding account (if configured)
754
- const fundingSigner = keyStoreManager?.createFundingSigner();
755
- let funderL1TxUtils;
756
- if (fundingSigner) {
757
- const [funder] = await createL1TxUtilsFromSigners(publicClient, [
758
- fundingSigner
759
- ], {
877
+ started.push(archiver);
878
+ // now create the merkle trees and the world state synchronizer
879
+ const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.genesis, telemetry);
880
+ started.push(worldStateSynchronizer);
881
+ const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
882
+ let peerProofVerifier;
883
+ let rpcProofVerifier;
884
+ if (useRealVerifiers) {
885
+ peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
886
+ const rpcVerifier = await BBCircuitVerifier.new(config);
887
+ rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
888
+ } else {
889
+ peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
890
+ rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
891
+ }
892
+ started.push(peerProofVerifier, rpcProofVerifier);
893
+ let debugLogStore;
894
+ if (!config.realProofs) {
895
+ log.warn(`Aztec node is accepting fake proofs`);
896
+ debugLogStore = new InMemoryDebugLogStore();
897
+ log.info('Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served');
898
+ } else {
899
+ debugLogStore = new NullDebugLogStore();
900
+ }
901
+ const globalVariableBuilderConfig = {
902
+ l1Contracts: config.l1Contracts,
903
+ ethereumSlotDuration: config.ethereumSlotDuration,
904
+ rollupVersion: BigInt(config.rollupVersion),
905
+ l1GenesisTime,
906
+ slotDuration: Number(slotDuration)
907
+ };
908
+ const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, globalVariableBuilderConfig);
909
+ const feeProvider = new FeeProviderImpl(dateProvider, publicClient, globalVariableBuilderConfig);
910
+ const proverOnly = config.enableProverNode && config.disableValidator;
911
+ if (proverOnly) {
912
+ log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
913
+ }
914
+ // create the tx pool and the p2p client, which will need the l2 block source
915
+ const p2pClient = await createP2PClient(config, archiver, peerProofVerifier, worldStateSynchronizer, epochCache, feeProvider, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
916
+ started.push(p2pClient);
917
+ // We'll accumulate sentinel watchers here
918
+ const watchers = [];
919
+ // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
920
+ // Override maxTxsPerCheckpoint with the validator-specific limit if set.
921
+ const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder({
922
+ ...config,
923
+ l1GenesisTime,
924
+ slotDuration: Number(slotDuration),
925
+ rollupManaLimit,
926
+ maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint
927
+ }, worldStateSynchronizer, archiver, dateProvider, telemetry);
928
+ let validatorClient;
929
+ if (!config.disableValidator) {
930
+ // Create validator client if required
931
+ validatorClient = await createValidatorClient(config, {
932
+ checkpointsBuilder: validatorCheckpointsBuilder,
933
+ worldState: worldStateSynchronizer,
934
+ p2pClient,
935
+ telemetry,
936
+ dateProvider,
937
+ epochCache,
938
+ blockSource: archiver,
939
+ l1ToL2MessageSource: archiver,
940
+ keyStoreManager,
941
+ blobClient,
942
+ slashingProtectionDb: deps.slashingProtectionDb
943
+ });
944
+ // If we have a validator client, register it as a source of offenses for the slasher,
945
+ // and have it register callbacks on the p2p client *before* we start it, otherwise messages
946
+ // like attestations or auths will fail.
947
+ if (validatorClient) {
948
+ watchers.push(validatorClient);
949
+ const vc = validatorClient;
950
+ const getValidatorAddresses = ()=>vc.getValidatorAddresses().map((a)=>a.toString());
951
+ validatorClient.getProposalHandler().register(p2pClient, true, archiver, getValidatorAddresses);
952
+ if (!options.dontStartSequencer) {
953
+ await validatorClient.registerHandlers();
954
+ }
955
+ }
956
+ }
957
+ // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
958
+ // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
959
+ // while non-reexecution is used for validating the proposals and collecting their txs.
960
+ // Checkpoint proposals rebuild blobs if the blob client can upload blobs.
961
+ if (!validatorClient) {
962
+ const reexecute = !!config.alwaysReexecuteBlockProposals;
963
+ log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
964
+ createProposalHandler(config, {
965
+ checkpointsBuilder: validatorCheckpointsBuilder,
966
+ worldState: worldStateSynchronizer,
967
+ epochCache,
968
+ blockSource: archiver,
969
+ l1ToL2MessageSource: archiver,
970
+ p2pClient,
971
+ blobClient,
972
+ dateProvider,
973
+ telemetry
974
+ }).register(p2pClient, reexecute, archiver);
975
+ }
976
+ // Start world state and wait for it to sync to the archiver.
977
+ await worldStateSynchronizer.start();
978
+ // Start p2p. Note that it depends on world state to be running.
979
+ await p2pClient.start();
980
+ let validatorsSentinel;
981
+ let epochPruneWatcher;
982
+ let attestationsBlockWatcher;
983
+ if (!proverOnly) {
984
+ validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
985
+ if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
986
+ watchers.push(validatorsSentinel);
987
+ }
988
+ if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
989
+ epochPruneWatcher = new EpochPruneWatcher(archiver, archiver, epochCache, p2pClient.getTxProvider(), validatorCheckpointsBuilder, config);
990
+ watchers.push(epochPruneWatcher);
991
+ }
992
+ // We assume we want to slash for invalid attestations unless all max penalties are set to 0
993
+ if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
994
+ attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
995
+ watchers.push(attestationsBlockWatcher);
996
+ }
997
+ }
998
+ // Start p2p-related services once the archiver has completed sync
999
+ void archiver.waitForInitialSync().then(async ()=>{
1000
+ if (validatorsSentinel) {
1001
+ await validatorsSentinel.start();
1002
+ started.push(validatorsSentinel);
1003
+ }
1004
+ if (epochPruneWatcher) {
1005
+ await epochPruneWatcher.start();
1006
+ started.push(epochPruneWatcher);
1007
+ }
1008
+ if (attestationsBlockWatcher) {
1009
+ await attestationsBlockWatcher.start();
1010
+ started.push(attestationsBlockWatcher);
1011
+ }
1012
+ log.info(`All p2p services started`);
1013
+ }).catch((err)=>log.error('Failed to start p2p services after archiver sync', err));
1014
+ // Validator enabled, create/start relevant service
1015
+ let sequencer;
1016
+ let slasherClient;
1017
+ if (!config.disableValidator && validatorClient) {
1018
+ // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
1019
+ // as they are executed when the node is selected as proposer.
1020
+ const validatorAddresses = keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses() : [];
1021
+ slasherClient = await createSlasher(config, config.l1Contracts, getPublicClient(config), watchers, dateProvider, epochCache, validatorAddresses, undefined);
1022
+ await slasherClient.start();
1023
+ started.push(slasherClient);
1024
+ const l1TxUtils = config.sequencerPublisherForwarderAddress ? await createForwarderL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), config.sequencerPublisherForwarderAddress, {
760
1025
  ...config,
761
1026
  scope: 'sequencer'
762
1027
  }, {
763
1028
  telemetry,
764
- logger: log.createChild('l1-tx-utils:funder'),
765
- dateProvider
1029
+ logger: log.createChild('l1-tx-utils'),
1030
+ dateProvider,
1031
+ kzg: Blob.getViemKzgInstance()
1032
+ }) : await createL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
1033
+ ...config,
1034
+ scope: 'sequencer'
1035
+ }, {
1036
+ telemetry,
1037
+ logger: log.createChild('l1-tx-utils'),
1038
+ dateProvider,
1039
+ kzg: Blob.getViemKzgInstance()
1040
+ });
1041
+ // Create a funder L1TxUtils from the keystore funding account (if configured)
1042
+ const fundingSigner = keyStoreManager?.createFundingSigner();
1043
+ let funderL1TxUtils;
1044
+ if (fundingSigner) {
1045
+ const [funder] = await createL1TxUtilsFromSigners(publicClient, [
1046
+ fundingSigner
1047
+ ], {
1048
+ ...config,
1049
+ scope: 'sequencer'
1050
+ }, {
1051
+ telemetry,
1052
+ logger: log.createChild('l1-tx-utils:funder'),
1053
+ dateProvider
1054
+ });
1055
+ funderL1TxUtils = funder;
1056
+ }
1057
+ // Create and start the sequencer client
1058
+ const checkpointsBuilder = new CheckpointsBuilder({
1059
+ ...config,
1060
+ l1GenesisTime,
1061
+ slotDuration: Number(slotDuration),
1062
+ rollupManaLimit
1063
+ }, worldStateSynchronizer, archiver, dateProvider, telemetry, debugLogStore);
1064
+ sequencer = await SequencerClient.new(config, {
1065
+ ...deps,
1066
+ epochCache,
1067
+ l1TxUtils,
1068
+ funderL1TxUtils,
1069
+ validatorClient,
1070
+ p2pClient,
1071
+ worldStateSynchronizer,
1072
+ slasherClient,
1073
+ checkpointsBuilder,
1074
+ l2BlockSource: archiver,
1075
+ l1ToL2MessageSource: archiver,
1076
+ telemetry,
1077
+ dateProvider,
1078
+ blobClient,
1079
+ nodeKeyStore: keyStoreManager,
1080
+ globalVariableBuilder
766
1081
  });
767
- funderL1TxUtils = funder;
768
1082
  }
769
- // Create and start the sequencer client
770
- const checkpointsBuilder = new CheckpointsBuilder({
771
- ...config,
772
- l1GenesisTime,
773
- slotDuration: Number(slotDuration),
774
- rollupManaLimit
775
- }, worldStateSynchronizer, archiver, dateProvider, telemetry, debugLogStore);
776
- sequencer = await SequencerClient.new(config, {
777
- ...deps,
778
- epochCache,
779
- l1TxUtils,
780
- funderL1TxUtils,
781
- validatorClient,
782
- p2pClient,
783
- worldStateSynchronizer,
784
- slasherClient,
785
- checkpointsBuilder,
786
- l2BlockSource: archiver,
787
- l1ToL2MessageSource: archiver,
788
- telemetry,
789
- dateProvider,
790
- blobClient,
791
- nodeKeyStore: keyStoreManager,
792
- globalVariableBuilder
793
- });
794
- }
795
- if (!options.dontStartSequencer && sequencer) {
796
- await sequencer.start();
797
- log.verbose(`Sequencer started`);
798
- } else if (sequencer) {
799
- log.warn(`Sequencer created but not started`);
800
- }
801
- // Create prover node subsystem if enabled
802
- let proverNode;
803
- if (config.enableProverNode) {
804
- proverNode = await createProverNode(config, {
805
- ...deps.proverNodeDeps,
806
- telemetry,
807
- dateProvider,
808
- archiver,
809
- worldStateSynchronizer,
810
- p2pClient,
811
- epochCache,
812
- blobClient,
813
- keyStoreManager
814
- });
815
- if (!options.dontStartProverNode) {
816
- await proverNode.start();
817
- log.info(`Prover node subsystem started`);
818
- } else {
819
- log.info(`Prover node subsystem created but not started`);
1083
+ if (!options.dontStartSequencer && sequencer) {
1084
+ await sequencer.start();
1085
+ started.push(sequencer);
1086
+ log.verbose(`Sequencer started`);
1087
+ } else if (sequencer) {
1088
+ log.warn(`Sequencer created but not started`);
1089
+ }
1090
+ // Create prover node subsystem if enabled
1091
+ let proverNode;
1092
+ if (config.enableProverNode) {
1093
+ proverNode = await createProverNode(config, {
1094
+ ...deps.proverNodeDeps,
1095
+ telemetry,
1096
+ dateProvider,
1097
+ archiver,
1098
+ worldStateSynchronizer,
1099
+ p2pClient,
1100
+ epochCache,
1101
+ blobClient,
1102
+ keyStoreManager
1103
+ });
1104
+ if (!options.dontStartProverNode) {
1105
+ await proverNode.start();
1106
+ started.push(proverNode);
1107
+ log.info(`Prover node subsystem started`);
1108
+ } else {
1109
+ log.info(`Prover node subsystem created but not started`);
1110
+ }
1111
+ }
1112
+ const node = new AztecNodeService(config, p2pClient, archiver, archiver, archiver, archiver, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, epochPruneWatcher, attestationsBlockWatcher, ethereumChain.chainInfo.id, config.rollupVersion, globalVariableBuilder, feeProvider, epochCache, packageVersion, peerProofVerifier, rpcProofVerifier, telemetry, log, blobClient, validatorClient, keyStoreManager, debugLogStore);
1113
+ return node;
1114
+ } catch (err) {
1115
+ log.error('Failed during node creation, stopping started resources', err);
1116
+ for (const resource of started.reverse()){
1117
+ await tryStop(resource);
820
1118
  }
1119
+ throw err;
821
1120
  }
822
- const node = new AztecNodeService(config, p2pClient, archiver, archiver, archiver, archiver, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, epochPruneWatcher, ethereumChain.chainInfo.id, config.rollupVersion, globalVariableBuilder, epochCache, packageVersion, peerProofVerifier, rpcProofVerifier, telemetry, log, blobClient, validatorClient, keyStoreManager, debugLogStore);
823
- return node;
824
1121
  }
825
1122
  /**
826
1123
  * Returns the sequencer client instance.
@@ -881,64 +1178,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
881
1178
  };
882
1179
  return nodeInfo;
883
1180
  }
884
- /**
885
- * Get a block specified by its block number, block hash, or 'latest'.
886
- * @param block - The block parameter (block number, block hash, or 'latest').
887
- * @returns The requested block.
888
- */ async getBlock(block) {
889
- if (BlockHash.isBlockHash(block)) {
890
- return this.getBlockByHash(block);
891
- }
892
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
893
- if (blockNumber === BlockNumber.ZERO) {
894
- return this.buildInitialBlock();
895
- }
896
- return await this.blockSource.getL2Block(blockNumber);
897
- }
898
- /**
899
- * Get a block specified by its hash.
900
- * @param blockHash - The block hash being requested.
901
- * @returns The requested block.
902
- */ async getBlockByHash(blockHash) {
903
- const initialBlockHash = await this.#getInitialHeaderHash();
904
- if (blockHash.equals(initialBlockHash)) {
905
- return this.buildInitialBlock();
906
- }
907
- return await this.blockSource.getL2BlockByHash(blockHash);
908
- }
909
- buildInitialBlock() {
910
- const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
911
- return L2Block.empty(initialHeader);
1181
+ async getCurrentMinFees() {
1182
+ return await this.feeProvider.getCurrentMinFees();
912
1183
  }
913
- /**
914
- * Get a block specified by its archive root.
915
- * @param archive - The archive root being requested.
916
- * @returns The requested block.
917
- */ async getBlockByArchive(archive) {
918
- return await this.blockSource.getL2BlockByArchive(archive);
919
- }
920
- /**
921
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
922
- * @param from - The start of the range of blocks to return.
923
- * @param limit - The maximum number of blocks to obtain.
924
- * @returns The blocks requested.
925
- */ async getBlocks(from, limit) {
926
- return await this.blockSource.getBlocks(from, BlockNumber(limit)) ?? [];
927
- }
928
- async getCheckpoints(from, limit) {
929
- return await this.blockSource.getCheckpoints(from, limit) ?? [];
930
- }
931
- async getCheckpointedBlocks(from, limit) {
932
- return await this.blockSource.getCheckpointedBlocks(from, limit) ?? [];
933
- }
934
- getCheckpointsDataForEpoch(epochNumber) {
935
- return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
936
- }
937
- /**
938
- * Method to fetch the current min L2 fees.
939
- * @returns The current min L2 fees.
940
- */ async getCurrentMinFees() {
941
- return await this.globalVariableBuilder.getCurrentMinFees();
1184
+ /** Returns predicted min fees for the current slot and next N slots. */ async getPredictedMinFees(manaUsage) {
1185
+ return await this.feeProvider.getPredictedMinFees(manaUsage);
942
1186
  }
943
1187
  async getMaxPriorityFees() {
944
1188
  for await (const tx of this.p2pClient.iteratePendingTxs()){
@@ -950,21 +1194,6 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
950
1194
  });
951
1195
  }
952
1196
  /**
953
- * Method to fetch the latest block number synchronized by the node.
954
- * @returns The block number.
955
- */ async getBlockNumber() {
956
- return await this.blockSource.getBlockNumber();
957
- }
958
- async getProvenBlockNumber() {
959
- return await this.blockSource.getProvenBlockNumber();
960
- }
961
- async getCheckpointedBlockNumber() {
962
- return await this.blockSource.getCheckpointedL2BlockNumber();
963
- }
964
- getCheckpointNumber() {
965
- return this.blockSource.getCheckpointNumber();
966
- }
967
- /**
968
1197
  * Method to fetch the version of the package.
969
1198
  * @returns The node package version
970
1199
  */ getNodeVersion() {
@@ -1052,7 +1281,15 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1052
1281
  });
1053
1282
  throw new Error(`Invalid tx: ${reason}`);
1054
1283
  }
1055
- await this.p2pClient.sendTx(tx);
1284
+ try {
1285
+ await this.p2pClient.sendTx(tx);
1286
+ } catch (err) {
1287
+ this.metrics.receivedTx(timer.ms(), false);
1288
+ this.log.warn(`Mempool rejected tx ${txHash}: ${err.message}`, {
1289
+ txHash
1290
+ });
1291
+ throw err;
1292
+ }
1056
1293
  const duration = timer.ms();
1057
1294
  this.metrics.receivedTx(duration, true);
1058
1295
  this.log.info(`Received tx ${txHash} in ${duration}ms`, {
@@ -1073,10 +1310,10 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1073
1310
  // If the tx is in the pool but not in the archiver, it's pending.
1074
1311
  // This handles race conditions between archiver and p2p, where the archiver
1075
1312
  // has pruned the block in which a tx was mined, but p2p has not caught up yet.
1076
- receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
1313
+ receipt = new TxReceipt(txHash, TxStatus.PENDING, /*executionResult=*/ undefined, /*error=*/ undefined);
1077
1314
  } else {
1078
1315
  // Otherwise, if we don't know the tx, we consider it dropped.
1079
- receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
1316
+ receipt = new TxReceipt(txHash, TxStatus.DROPPED, /*executionResult=*/ undefined, /*error=*/ 'Tx dropped by P2P node');
1080
1317
  }
1081
1318
  this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
1082
1319
  return receipt;
@@ -1088,6 +1325,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1088
1325
  * Method to stop the aztec node.
1089
1326
  */ async stop() {
1090
1327
  this.log.info(`Stopping Aztec Node`);
1328
+ await tryStop(this.attestationsBlockWatcher);
1091
1329
  await tryStop(this.validatorsSentinel);
1092
1330
  await tryStop(this.epochPruneWatcher);
1093
1331
  await tryStop(this.slasherClient);
@@ -1177,13 +1415,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1177
1415
  if (blockNumber === undefined) {
1178
1416
  throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1179
1417
  }
1180
- const blockHash = blockNumberToHash.get(blockNumber);
1181
- if (blockHash === undefined) {
1418
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
1419
+ if (l2BlockHash === undefined) {
1182
1420
  throw new Error(`Block hash not found for block number ${blockNumber}`);
1183
1421
  }
1184
1422
  return {
1185
1423
  l2BlockNumber: blockNumber,
1186
- l2BlockHash: new BlockHash(blockHash),
1424
+ l2BlockHash,
1187
1425
  data: index
1188
1426
  };
1189
1427
  });
@@ -1296,36 +1534,6 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1296
1534
  const preimage = await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1297
1535
  return preimage.leaf.value;
1298
1536
  }
1299
- async getBlockHeader(block = 'latest') {
1300
- if (BlockHash.isBlockHash(block)) {
1301
- const initialBlockHash = await this.#getInitialHeaderHash();
1302
- if (block.equals(initialBlockHash)) {
1303
- // Block source doesn't handle initial header so we need to handle the case separately.
1304
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1305
- }
1306
- return this.blockSource.getBlockHeaderByHash(block);
1307
- } else {
1308
- // Block source doesn't handle initial header so we need to handle the case separately.
1309
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
1310
- if (blockNumber === BlockNumber.ZERO) {
1311
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1312
- }
1313
- return this.blockSource.getBlockHeader(block);
1314
- }
1315
- }
1316
- /**
1317
- * Get a block header specified by its archive root.
1318
- * @param archive - The archive root being requested.
1319
- * @returns The requested block header.
1320
- */ async getBlockHeaderByArchive(archive) {
1321
- return await this.blockSource.getBlockHeaderByArchive(archive);
1322
- }
1323
- getBlockData(number) {
1324
- return this.blockSource.getBlockData(number);
1325
- }
1326
- getBlockDataByArchive(archive) {
1327
- return this.blockSource.getBlockDataByArchive(archive);
1328
- }
1329
1537
  /**
1330
1538
  * Simulates the public part of a transaction with the current state.
1331
1539
  * @param tx - The transaction to simulate.
@@ -1497,7 +1705,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1497
1705
  });
1498
1706
  return Promise.resolve();
1499
1707
  }
1500
- async rollbackTo(targetBlock, force) {
1708
+ async rollbackTo(targetBlock, force, resumeSync = true) {
1501
1709
  const archiver = this.blockSource;
1502
1710
  if (!('rollbackTo' in archiver)) {
1503
1711
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1525,9 +1733,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1525
1733
  this.log.error(`Error during rollback`, err);
1526
1734
  throw err;
1527
1735
  } finally{
1528
- this.log.info(`Resuming world state and archiver sync.`);
1529
- this.worldStateSynchronizer.resumeSync();
1530
- archiver.resume();
1736
+ if (resumeSync) {
1737
+ this.log.info(`Resuming world state and archiver sync.`);
1738
+ this.worldStateSynchronizer.resumeSync();
1739
+ archiver.resume();
1740
+ } else {
1741
+ this.log.info(`Sync left paused after rollback (resumeSync=false).`);
1742
+ }
1531
1743
  }
1532
1744
  }
1533
1745
  async pauseSync() {
@@ -1541,18 +1753,12 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1541
1753
  this.blockSource.resume();
1542
1754
  return Promise.resolve();
1543
1755
  }
1544
- getSlashPayloads() {
1545
- if (!this.slasherClient) {
1546
- throw new Error(`Slasher client not enabled`);
1547
- }
1548
- return this.slasherClient.getSlashPayloads();
1549
- }
1550
1756
  getSlashOffenses(round) {
1551
1757
  if (!this.slasherClient) {
1552
1758
  throw new Error(`Slasher client not enabled`);
1553
1759
  }
1554
1760
  if (round === 'all') {
1555
- return this.slasherClient.getPendingOffenses();
1761
+ return this.slasherClient.getOffenses();
1556
1762
  } else {
1557
1763
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1558
1764
  }
@@ -1624,6 +1830,33 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1624
1830
  this.keyStoreManager = newManager;
1625
1831
  this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1626
1832
  }
1833
+ async mineBlock() {
1834
+ if (!this.sequencer) {
1835
+ throw new BadRequestError('Cannot mine block: no sequencer is running');
1836
+ }
1837
+ const currentBlockNumber = await this.getBlockNumber();
1838
+ // Use slot duration + 50% buffer as the timeout so this works on running networks too
1839
+ const { slotDuration } = await this.blockSource.getL1Constants();
1840
+ const timeoutSeconds = Math.ceil(slotDuration * 1.5);
1841
+ // Temporarily set minTxsPerBlock to 0 so the sequencer produces a block even with no txs
1842
+ const originalMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock;
1843
+ this.sequencer.updateConfig({
1844
+ minTxsPerBlock: 0
1845
+ });
1846
+ try {
1847
+ // Trigger the sequencer to produce a block immediately
1848
+ void this.sequencer.trigger();
1849
+ // Wait for the new L2 block to appear
1850
+ await retryUntil(async ()=>{
1851
+ const newBlockNumber = await this.getBlockNumber();
1852
+ return newBlockNumber > currentBlockNumber ? true : undefined;
1853
+ }, 'mineBlock', timeoutSeconds, 0.1);
1854
+ } finally{
1855
+ this.sequencer.updateConfig({
1856
+ minTxsPerBlock: originalMinTxsPerBlock
1857
+ });
1858
+ }
1859
+ }
1627
1860
  #getInitialHeaderHash() {
1628
1861
  if (!this.initialHeaderHashPromise) {
1629
1862
  this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
@@ -1651,48 +1884,60 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1651
1884
  if (BlockHash.isBlockHash(block)) {
1652
1885
  const initialBlockHash = await this.#getInitialHeaderHash();
1653
1886
  if (block.equals(initialBlockHash)) {
1654
- // Block source doesn't handle initial header so we need to handle the case separately.
1655
- return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1656
- }
1657
- const header = await this.blockSource.getBlockHeaderByHash(block);
1658
- if (!header) {
1659
- 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.`);
1887
+ // Block 0 is a first-class historical block: its state lives in the trees' persisted
1888
+ // block-0 payload. Resolving the genesis hash to block number 0 lets the snapshot path
1889
+ // pin reads to genesis state even after the node has advanced past it.
1890
+ blockNumber = BlockNumber.ZERO;
1891
+ } else {
1892
+ const header = await this.blockSource.getBlockHeaderByHash(block);
1893
+ if (!header) {
1894
+ 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.`);
1895
+ }
1896
+ blockNumber = header.getBlockNumber();
1660
1897
  }
1661
- blockNumber = header.getBlockNumber();
1662
1898
  } else {
1663
1899
  blockNumber = block;
1664
1900
  }
1665
1901
  // Check it's within world state sync range
1666
1902
  if (blockNumber > blockSyncedTo) {
1667
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1903
+ throw new Error(`Queried block ${inspectBlockParameter(block)} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1668
1904
  }
1669
1905
  this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1670
1906
  const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
1671
1907
  // Double-check world-state synced to the same block hash as was requested
1672
1908
  if (BlockHash.isBlockHash(block)) {
1673
1909
  const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1674
- if (!blockHash || !new BlockHash(blockHash).equals(block)) {
1675
- 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.`);
1910
+ if (!blockHash || !block.equals(blockHash)) {
1911
+ const initialBlockHash = await this.#getInitialHeaderHash();
1912
+ throw new Error(`Block hash ${block.toString()} not found in world state at block number ${blockNumber} (world state has ${blockHash?.toString() ?? 'no hash'} at that index, genesis header hash is ${initialBlockHash.toString()}). If the node API has been queried with anchor block hash possibly a reorg has occurred.`);
1676
1913
  }
1677
1914
  }
1678
1915
  return snapshot;
1679
1916
  }
1680
- /** Resolves a block parameter to a block number. */ async resolveBlockNumber(block) {
1681
- if (block === 'latest') {
1682
- return BlockNumber(await this.blockSource.getBlockNumber());
1917
+ /** Resolves any {@link BlockParameter} variant to a concrete block number. */ async resolveBlockNumber(block) {
1918
+ const resolved = await this.resolveBlockParameter(block);
1919
+ if (resolved.number !== undefined) {
1920
+ return resolved.number;
1683
1921
  }
1684
- if (BlockHash.isBlockHash(block)) {
1922
+ if (resolved.hash !== undefined) {
1685
1923
  const initialBlockHash = await this.#getInitialHeaderHash();
1686
- if (block.equals(initialBlockHash)) {
1924
+ if (resolved.hash.equals(initialBlockHash)) {
1687
1925
  return BlockNumber.ZERO;
1688
1926
  }
1689
- const header = await this.blockSource.getBlockHeaderByHash(block);
1927
+ const header = await this.blockSource.getBlockHeaderByHash(resolved.hash);
1928
+ if (!header) {
1929
+ throw new Error(`Block hash ${resolved.hash.toString()} not found.`);
1930
+ }
1931
+ return header.getBlockNumber();
1932
+ }
1933
+ if (resolved.archive !== undefined) {
1934
+ const header = await this.blockSource.getBlockHeaderByArchive(resolved.archive);
1690
1935
  if (!header) {
1691
- throw new Error(`Block hash ${block.toString()} not found.`);
1936
+ throw new Error(`Block with archive ${resolved.archive.toString()} not found.`);
1692
1937
  }
1693
1938
  return header.getBlockNumber();
1694
1939
  }
1695
- return block;
1940
+ throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(block)}`);
1696
1941
  }
1697
1942
  /**
1698
1943
  * Ensure we fully sync the world state