@aztec/aztec-node 0.0.1-commit.a072138 → 0.0.1-commit.a5db02d

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.
Files changed (71) hide show
  1. package/dest/aztec-node/block_response_helpers.d.ts +25 -0
  2. package/dest/aztec-node/block_response_helpers.d.ts.map +1 -0
  3. package/dest/aztec-node/block_response_helpers.js +112 -0
  4. package/dest/aztec-node/config.d.ts +23 -8
  5. package/dest/aztec-node/config.d.ts.map +1 -1
  6. package/dest/aztec-node/config.js +26 -8
  7. package/dest/aztec-node/node_public_calls_simulator.d.ts +90 -0
  8. package/dest/aztec-node/node_public_calls_simulator.d.ts.map +1 -0
  9. package/dest/aztec-node/node_public_calls_simulator.js +346 -0
  10. package/dest/aztec-node/public_data_overrides.d.ts +13 -0
  11. package/dest/aztec-node/public_data_overrides.d.ts.map +1 -0
  12. package/dest/aztec-node/public_data_overrides.js +21 -0
  13. package/dest/aztec-node/register_node_rpc_handlers.d.ts +10 -0
  14. package/dest/aztec-node/register_node_rpc_handlers.d.ts.map +1 -0
  15. package/dest/aztec-node/register_node_rpc_handlers.js +31 -0
  16. package/dest/aztec-node/server.d.ts +140 -135
  17. package/dest/aztec-node/server.d.ts.map +1 -1
  18. package/dest/aztec-node/server.js +490 -730
  19. package/dest/bin/index.js +15 -10
  20. package/dest/factory.d.ts +33 -0
  21. package/dest/factory.d.ts.map +1 -0
  22. package/dest/factory.js +509 -0
  23. package/dest/index.d.ts +3 -1
  24. package/dest/index.d.ts.map +1 -1
  25. package/dest/index.js +2 -0
  26. package/dest/modules/block_parameter.d.ts +25 -0
  27. package/dest/modules/block_parameter.d.ts.map +1 -0
  28. package/dest/modules/block_parameter.js +100 -0
  29. package/dest/modules/node_block_provider.d.ts +19 -0
  30. package/dest/modules/node_block_provider.d.ts.map +1 -0
  31. package/dest/modules/node_block_provider.js +112 -0
  32. package/dest/modules/node_tx_receipt.d.ts +24 -0
  33. package/dest/modules/node_tx_receipt.d.ts.map +1 -0
  34. package/dest/modules/node_tx_receipt.js +70 -0
  35. package/dest/modules/node_world_state_queries.d.ts +65 -0
  36. package/dest/modules/node_world_state_queries.d.ts.map +1 -0
  37. package/dest/modules/node_world_state_queries.js +272 -0
  38. package/dest/sentinel/config.d.ts +3 -2
  39. package/dest/sentinel/config.d.ts.map +1 -1
  40. package/dest/sentinel/config.js +15 -5
  41. package/dest/sentinel/factory.d.ts +6 -4
  42. package/dest/sentinel/factory.d.ts.map +1 -1
  43. package/dest/sentinel/factory.js +12 -5
  44. package/dest/sentinel/sentinel.d.ts +146 -22
  45. package/dest/sentinel/sentinel.d.ts.map +1 -1
  46. package/dest/sentinel/sentinel.js +266 -118
  47. package/dest/sentinel/store.d.ts +8 -8
  48. package/dest/sentinel/store.d.ts.map +1 -1
  49. package/dest/sentinel/store.js +33 -21
  50. package/dest/test/index.d.ts +3 -3
  51. package/dest/test/index.d.ts.map +1 -1
  52. package/package.json +28 -25
  53. package/src/aztec-node/block_response_helpers.ts +161 -0
  54. package/src/aztec-node/config.ts +55 -16
  55. package/src/aztec-node/node_public_calls_simulator.ts +383 -0
  56. package/src/aztec-node/public_data_overrides.ts +35 -0
  57. package/src/aztec-node/register_node_rpc_handlers.ts +29 -0
  58. package/src/aztec-node/server.ts +632 -939
  59. package/src/bin/index.ts +19 -12
  60. package/src/factory.ts +673 -0
  61. package/src/index.ts +2 -0
  62. package/src/modules/block_parameter.ts +93 -0
  63. package/src/modules/node_block_provider.ts +149 -0
  64. package/src/modules/node_tx_receipt.ts +115 -0
  65. package/src/modules/node_world_state_queries.ts +374 -0
  66. package/src/sentinel/README.md +103 -0
  67. package/src/sentinel/config.ts +18 -6
  68. package/src/sentinel/factory.ts +22 -7
  69. package/src/sentinel/sentinel.ts +316 -136
  70. package/src/sentinel/store.ts +35 -27
  71. package/src/test/index.ts +2 -2
@@ -371,55 +371,59 @@ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
371
  return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
372
372
  }
373
373
  var _dec, _initProto;
374
- import { createArchiver } from '@aztec/archiver';
375
- import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
376
- import { createBlobClientWithFileStores } from '@aztec/blob-client/client';
377
- import { EpochCache } from '@aztec/epoch-cache';
378
- import { createEthereumChain } from '@aztec/ethereum/chain';
379
- import { getPublicClient } from '@aztec/ethereum/client';
380
- import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
381
- import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
382
- import { compactArray, pick } from '@aztec/foundation/collection';
383
- import { Fr } from '@aztec/foundation/curves/bn254';
374
+ import { BBCircuitVerifier, BatchChonkVerifier, QueuedIVCVerifier } from '@aztec/bb-prover';
375
+ import { TestCircuitVerifier } from '@aztec/bb-prover/test';
376
+ import { pickL1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
377
+ import { BlockNumber } from '@aztec/foundation/branded-types';
378
+ import { compactArray, pick, unique } from '@aztec/foundation/collection';
384
379
  import { EthAddress } from '@aztec/foundation/eth-address';
385
380
  import { BadRequestError } from '@aztec/foundation/json-rpc';
386
381
  import { createLogger } from '@aztec/foundation/log';
382
+ import { retryUntil } from '@aztec/foundation/retry';
387
383
  import { count } from '@aztec/foundation/string';
388
- import { DateProvider, Timer } from '@aztec/foundation/timer';
389
- import { MembershipWitness } from '@aztec/foundation/trees';
384
+ import { Timer } from '@aztec/foundation/timer';
390
385
  import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
391
- import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
392
- import { createForwarderL1TxUtilsFromEthSigner, createL1TxUtilsWithBlobsFromEthSigner } from '@aztec/node-lib/factories';
393
- import { createP2PClient, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
386
+ import { uploadSnapshot } from '@aztec/node-lib/actions';
387
+ import { createTxValidatorForAcceptingTxsOverRPC, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
394
388
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
395
- import { GlobalVariableBuilder, SequencerClient } from '@aztec/sequencer-client';
396
- import { PublicProcessorFactory } from '@aztec/simulator/server';
397
- import { AttestationsBlockWatcher, EpochPruneWatcher, createSlasher } from '@aztec/slasher';
398
- import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
399
- import { AztecAddress } from '@aztec/stdlib/aztec-address';
400
- import { BlockHash, L2Block } from '@aztec/stdlib/block';
401
- import { GasFees } from '@aztec/stdlib/gas';
402
- import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
389
+ import { STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS } from '@aztec/standard-contracts/multi-call-entrypoint';
390
+ import { inspectBlockParameter } from '@aztec/stdlib/block';
391
+ import { GasFees, getNetworkTxGasLimits } from '@aztec/stdlib/gas';
403
392
  import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
404
393
  import { tryStop } from '@aztec/stdlib/interfaces/server';
405
- import { InboxLeaf } from '@aztec/stdlib/messaging';
406
- import { P2PClientType } from '@aztec/stdlib/p2p';
407
- import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
408
- import { PublicSimulationOutput, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
409
- import { getPackageVersion } from '@aztec/stdlib/update-checker';
394
+ import { NullDebugLogStore } from '@aztec/stdlib/logs';
410
395
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
411
- import { FullNodeCheckpointsBuilder as CheckpointsBuilder, FullNodeCheckpointsBuilder, NodeKeystoreAdapter, ValidatorClient, createBlockProposalHandler, createValidatorClient, createValidatorForAcceptingTxs } from '@aztec/validator-client';
412
- import { createWorldStateSynchronizer } from '@aztec/world-state';
413
- import { createPublicClient, fallback, http } from 'viem';
414
- import { createSentinel } from '../sentinel/factory.js';
415
- import { createKeyStoreForValidator } from './config.js';
396
+ import { NodeKeystoreAdapter, ValidatorClient } from '@aztec/validator-client';
397
+ import { NodeBlockProvider } from '../modules/node_block_provider.js';
398
+ import { NodeTxReceiptBuilder } from '../modules/node_tx_receipt.js';
399
+ import { NodeWorldStateQueries } from '../modules/node_world_state_queries.js';
416
400
  import { NodeMetrics } from './node_metrics.js';
401
+ import { NodePublicCallsSimulator } from './node_public_calls_simulator.js';
417
402
  _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
418
403
  [Attributes.TX_HASH]: tx.getTxHash().toString()
419
404
  }));
420
405
  /**
421
406
  * The aztec node.
422
407
  */ export class AztecNodeService {
408
+ static{
409
+ ({ e: [_initProto] } = _apply_decs_2203_r(this, [
410
+ [
411
+ _dec,
412
+ 2,
413
+ "simulatePublicCalls"
414
+ ]
415
+ ], []));
416
+ }
417
+ metrics;
418
+ // Prevent two snapshot operations to happen simultaneously
419
+ isUploadingSnapshot = (_initProto(this), false);
420
+ // Saved minTxsPerBlock used by `pauseSequencer` to restore production-sequencer config on resume.
421
+ sequencerPausedMinTxsPerBlock;
422
+ nodePublicCallsSimulator;
423
+ worldStateQueries;
424
+ blockProvider;
425
+ txReceiptBuilder;
426
+ tracer;
423
427
  config;
424
428
  p2pClient;
425
429
  blockSource;
@@ -428,287 +432,155 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
428
432
  l1ToL2MessageSource;
429
433
  worldStateSynchronizer;
430
434
  sequencer;
435
+ proverNode;
431
436
  slasherClient;
432
437
  validatorsSentinel;
433
- epochPruneWatcher;
438
+ stopStartedWatchers;
434
439
  l1ChainId;
435
440
  version;
436
441
  globalVariableBuilder;
442
+ rollupContract;
443
+ feeProvider;
437
444
  epochCache;
438
445
  packageVersion;
439
- proofVerifier;
446
+ peerProofVerifier;
447
+ rpcProofVerifier;
440
448
  telemetry;
441
449
  log;
442
450
  blobClient;
443
- static{
444
- ({ e: [_initProto] } = _apply_decs_2203_r(this, [
445
- [
446
- _dec,
447
- 2,
448
- "simulatePublicCalls"
449
- ]
450
- ], []));
451
- }
452
- metrics;
453
- initialHeaderHashPromise;
454
- // Prevent two snapshot operations to happen simultaneously
455
- isUploadingSnapshot;
456
- 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){
458
- this.config = config;
459
- this.p2pClient = p2pClient;
460
- this.blockSource = blockSource;
461
- this.logsSource = logsSource;
462
- this.contractDataSource = contractDataSource;
463
- this.l1ToL2MessageSource = l1ToL2MessageSource;
464
- this.worldStateSynchronizer = worldStateSynchronizer;
465
- this.sequencer = sequencer;
466
- this.slasherClient = slasherClient;
467
- this.validatorsSentinel = validatorsSentinel;
468
- this.epochPruneWatcher = epochPruneWatcher;
469
- this.l1ChainId = l1ChainId;
470
- this.version = version;
471
- this.globalVariableBuilder = globalVariableBuilder;
472
- this.epochCache = epochCache;
473
- this.packageVersion = packageVersion;
474
- this.proofVerifier = proofVerifier;
475
- this.telemetry = telemetry;
476
- this.log = log;
477
- this.blobClient = blobClient;
478
- this.initialHeaderHashPromise = (_initProto(this), undefined);
479
- this.isUploadingSnapshot = false;
480
- this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
481
- this.tracer = telemetry.getTracer('AztecNodeService');
451
+ validatorClient;
452
+ keyStoreManager;
453
+ debugLogStore;
454
+ automineSequencer;
455
+ constructor(deps){
456
+ this.config = deps.config;
457
+ this.p2pClient = deps.p2pClient;
458
+ this.blockSource = deps.blockSource;
459
+ this.logsSource = deps.logsSource;
460
+ this.contractDataSource = deps.contractDataSource;
461
+ this.l1ToL2MessageSource = deps.l1ToL2MessageSource;
462
+ this.worldStateSynchronizer = deps.worldStateSynchronizer;
463
+ this.sequencer = deps.sequencer;
464
+ this.proverNode = deps.proverNode;
465
+ this.slasherClient = deps.slasherClient;
466
+ this.validatorsSentinel = deps.validatorsSentinel;
467
+ this.stopStartedWatchers = deps.stopStartedWatchers;
468
+ this.l1ChainId = deps.l1ChainId;
469
+ this.version = deps.version;
470
+ this.globalVariableBuilder = deps.globalVariableBuilder;
471
+ this.rollupContract = deps.rollupContract;
472
+ this.feeProvider = deps.feeProvider;
473
+ this.epochCache = deps.epochCache;
474
+ this.packageVersion = deps.packageVersion;
475
+ this.peerProofVerifier = deps.peerProofVerifier;
476
+ this.rpcProofVerifier = deps.rpcProofVerifier;
477
+ this.telemetry = deps.telemetry ?? getTelemetryClient();
478
+ this.log = deps.log ?? createLogger('node');
479
+ this.blobClient = deps.blobClient;
480
+ this.validatorClient = deps.validatorClient;
481
+ this.keyStoreManager = deps.keyStoreManager;
482
+ this.debugLogStore = deps.debugLogStore ?? new NullDebugLogStore();
483
+ this.automineSequencer = deps.automineSequencer;
484
+ this.metrics = new NodeMetrics(this.telemetry, 'AztecNodeService');
485
+ this.tracer = this.telemetry.getTracer('AztecNodeService');
486
+ // The node never represents a proposer's payout addresses, so the simulator zeroes coinbase and
487
+ // fee recipient. The signature context only needs chain id + rollup address (see signature_utils).
488
+ this.nodePublicCallsSimulator = new NodePublicCallsSimulator({
489
+ blockSource: this.blockSource,
490
+ worldStateSynchronizer: this.worldStateSynchronizer,
491
+ l1ToL2MessageSource: this.l1ToL2MessageSource,
492
+ contractDataSource: this.contractDataSource,
493
+ globalVariableBuilder: this.globalVariableBuilder,
494
+ rollupContract: this.rollupContract,
495
+ epochCache: this.epochCache,
496
+ signatureContext: {
497
+ chainId: this.l1ChainId,
498
+ rollupAddress: this.config.rollupAddress
499
+ },
500
+ config: this.config,
501
+ telemetry: this.telemetry,
502
+ log: this.log.createChild('public-calls-simulator')
503
+ });
504
+ this.worldStateQueries = new NodeWorldStateQueries({
505
+ worldStateSynchronizer: this.worldStateSynchronizer,
506
+ blockSource: this.blockSource,
507
+ l1ToL2MessageSource: this.l1ToL2MessageSource,
508
+ log: this.log.createChild('world-state-queries')
509
+ });
510
+ this.blockProvider = new NodeBlockProvider(this.blockSource);
511
+ this.txReceiptBuilder = new NodeTxReceiptBuilder({
512
+ p2pClient: this.p2pClient,
513
+ blockSource: this.blockSource,
514
+ debugLogStore: this.debugLogStore
515
+ });
482
516
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
483
- this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
517
+ this.log.info(`Aztec Node started on chain 0x${this.l1ChainId.toString(16)}`, pickL1ContractAddresses(this.config));
518
+ // A defensive check that protects us against introducing a bug in the complex node creation flow. We must
519
+ // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
520
+ // memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
521
+ if (this.debugLogStore.isEnabled && this.config.realProofs) {
522
+ throw new Error('debugLogStore should never be enabled when realProofs are set');
523
+ }
524
+ }
525
+ /** @internal Exposed for testing — returns the RPC proof verifier. */ getProofVerifier() {
526
+ return this.rpcProofVerifier;
484
527
  }
485
528
  async getWorldStateSyncStatus() {
486
529
  const status = await this.worldStateSynchronizer.status();
487
530
  return status.syncSummary;
488
531
  }
489
- getL2Tips() {
532
+ getChainTips() {
490
533
  return this.blockSource.getL2Tips();
491
534
  }
492
- /**
493
- * initializes the Aztec Node, wait for component to sync.
494
- * @param config - The configuration to be used by the aztec node.
495
- * @returns - A fully synced Aztec Node for use in development/testing.
496
- */ static async createAndSync(inputConfig, deps = {}, options = {}) {
497
- const config = {
498
- ...inputConfig
499
- }; // Copy the config so we dont mutate the input object
500
- const log = deps.logger ?? createLogger('node');
501
- const packageVersion = getPackageVersion() ?? '';
502
- const telemetry = deps.telemetry ?? getTelemetryClient();
503
- const dateProvider = deps.dateProvider ?? new DateProvider();
504
- const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
505
- // Build a key store from file if given or from environment otherwise
506
- let keyStoreManager;
507
- const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
508
- if (keyStoreProvided) {
509
- const keyStores = loadKeystores(config.keyStoreDirectory);
510
- keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
511
- } else {
512
- const keyStore = createKeyStoreForValidator(config);
513
- if (keyStore) {
514
- keyStoreManager = new KeystoreManager(keyStore);
515
- }
516
- }
517
- await keyStoreManager?.validateSigners();
518
- // If we are a validator, verify our configuration before doing too much more.
519
- if (!config.disableValidator) {
520
- if (keyStoreManager === undefined) {
521
- throw new Error('Failed to create key store, a requirement for running a validator');
522
- }
523
- if (!keyStoreProvided) {
524
- log.warn('KEY STORE CREATED FROM ENVIRONMENT, IT IS RECOMMENDED TO USE A FILE-BASED KEY STORE IN PRODUCTION ENVIRONMENTS');
525
- }
526
- ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
527
- }
528
- // validate that the actual chain id matches that specified in configuration
529
- if (config.l1ChainId !== ethereumChain.chainInfo.id) {
530
- throw new Error(`RPC URL configured for chain id ${ethereumChain.chainInfo.id} but expected id ${config.l1ChainId}`);
531
- }
532
- const publicClient = createPublicClient({
533
- chain: ethereumChain.chainInfo,
534
- transport: fallback(config.l1RpcUrls.map((url)=>http(url, {
535
- batch: false
536
- }))),
537
- pollingInterval: config.viemPollingIntervalMS
538
- });
539
- const l1ContractsAddresses = await RegistryContract.collectAddresses(publicClient, config.l1Contracts.registryAddress, config.rollupVersion ?? 'canonical');
540
- // Overwrite the passed in vars.
541
- config.l1Contracts = {
542
- ...config.l1Contracts,
543
- ...l1ContractsAddresses
544
- };
545
- const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
546
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
547
- rollupContract.getL1GenesisTime(),
548
- rollupContract.getSlotDuration(),
549
- rollupContract.getVersion()
550
- ]);
551
- config.rollupVersion ??= Number(rollupVersionFromRollup);
552
- if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
553
- 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
- }
555
- const blobClient = await createBlobClientWithFileStores(config, createLogger('node:blob-client:client'));
556
- // attempt snapshot sync if possible
557
- await trySnapshotSync(config, log);
558
- const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, {
559
- dateProvider
560
- });
561
- const archiver = await createArchiver(config, {
562
- blobClient,
563
- epochCache,
564
- telemetry,
565
- dateProvider
566
- }, {
567
- blockUntilSync: !config.skipArchiverInitialSync
568
- });
569
- // now create the merkle trees and the world state synchronizer
570
- const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.prefilledPublicData, telemetry);
571
- const circuitVerifier = config.realProofs || config.debugForceTxProofVerification ? await BBCircuitVerifier.new(config) : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
572
- if (!config.realProofs) {
573
- log.warn(`Aztec node is accepting fake proofs`);
574
- }
575
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
576
- // 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
581
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder({
582
- ...config,
583
- l1GenesisTime,
584
- slotDuration: Number(slotDuration)
585
- }, 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();
608
- }
609
- }
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');
614
- createBlockProposalHandler(config, {
615
- checkpointsBuilder: validatorCheckpointsBuilder,
616
- worldState: worldStateSynchronizer,
617
- epochCache,
618
- blockSource: archiver,
619
- l1ToL2MessageSource: archiver,
620
- p2pClient,
621
- dateProvider,
622
- telemetry
623
- }).registerForReexecution(p2pClient);
624
- }
625
- // Start world state and wait for it to sync to the archiver.
626
- await worldStateSynchronizer.start();
627
- // Start p2p. Note that it depends on world state to be running.
628
- await p2pClient.start();
629
- const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
630
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
631
- watchers.push(validatorsSentinel);
632
- }
633
- 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
- let attestationsBlockWatcher;
640
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
641
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
642
- watchers.push(attestationsBlockWatcher);
643
- }
644
- // Start p2p-related services once the archiver has completed sync
645
- void archiver.waitForInitialSync().then(async ()=>{
646
- await p2pClient.start();
647
- await validatorsSentinel?.start();
648
- await epochPruneWatcher?.start();
649
- await attestationsBlockWatcher?.start();
650
- log.info(`All p2p services started`);
651
- }).catch((err)=>log.error('Failed to start p2p services after archiver sync', err));
652
- // Validator enabled, create/start relevant service
653
- let sequencer;
654
- let slasherClient;
655
- if (!config.disableValidator && validatorClient) {
656
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
657
- // as they are executed when the node is selected as proposer.
658
- const validatorAddresses = keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses() : [];
659
- slasherClient = await createSlasher(config, config.l1Contracts, getPublicClient(config), watchers, dateProvider, epochCache, validatorAddresses, undefined);
660
- await slasherClient.start();
661
- const l1TxUtils = config.publisherForwarderAddress ? await createForwarderL1TxUtilsFromEthSigner(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), config.publisherForwarderAddress, {
662
- ...config,
663
- scope: 'sequencer'
664
- }, {
665
- telemetry,
666
- logger: log.createChild('l1-tx-utils'),
667
- dateProvider
668
- }) : await createL1TxUtilsWithBlobsFromEthSigner(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
669
- ...config,
670
- scope: 'sequencer'
671
- }, {
672
- telemetry,
673
- logger: log.createChild('l1-tx-utils'),
674
- dateProvider
675
- });
676
- // Create and start the sequencer client
677
- const checkpointsBuilder = new CheckpointsBuilder({
678
- ...config,
679
- l1GenesisTime,
680
- slotDuration: Number(slotDuration)
681
- }, worldStateSynchronizer, archiver, dateProvider, telemetry);
682
- sequencer = await SequencerClient.new(config, {
683
- ...deps,
684
- epochCache,
685
- l1TxUtils,
686
- validatorClient,
687
- p2pClient,
688
- worldStateSynchronizer,
689
- slasherClient,
690
- checkpointsBuilder,
691
- l2BlockSource: archiver,
692
- l1ToL2MessageSource: archiver,
693
- telemetry,
694
- dateProvider,
695
- blobClient,
696
- nodeKeyStore: keyStoreManager
697
- });
535
+ getL1Constants() {
536
+ return this.blockSource.getL1Constants();
537
+ }
538
+ getSyncedL2SlotNumber() {
539
+ return this.blockSource.getSyncedL2SlotNumber();
540
+ }
541
+ getSyncedL2EpochNumber() {
542
+ return this.blockSource.getSyncedL2EpochNumber();
543
+ }
544
+ getSyncedL1Timestamp() {
545
+ return this.blockSource.getL1Timestamp();
546
+ }
547
+ getCheckpointsData(query) {
548
+ return this.blockSource.getCheckpointsData(query);
549
+ }
550
+ async getBlockNumber(tip) {
551
+ if (tip === undefined || tip === 'proposed') {
552
+ return this.blockSource.getBlockNumber();
698
553
  }
699
- if (!options.dontStartSequencer && sequencer) {
700
- await sequencer.start();
701
- log.verbose(`Sequencer started`);
702
- } else if (sequencer) {
703
- log.warn(`Sequencer created but not started`);
554
+ return await this.blockSource.getBlockNumber({
555
+ tag: tip
556
+ }) ?? BlockNumber.ZERO;
557
+ }
558
+ async getCheckpointNumber(tip) {
559
+ const tips = await this.blockSource.getL2Tips();
560
+ switch(tip){
561
+ case undefined:
562
+ case 'checkpointed':
563
+ return tips.checkpointed.checkpoint.number;
564
+ case 'proven':
565
+ return tips.proven.checkpoint.number;
566
+ case 'finalized':
567
+ return tips.finalized.checkpoint.number;
704
568
  }
705
- const globalVariableBuilder = new GlobalVariableBuilder({
706
- ...config,
707
- rollupVersion: BigInt(config.rollupVersion),
708
- l1GenesisTime,
709
- slotDuration: Number(slotDuration)
710
- });
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);
569
+ }
570
+ getBlock(param, options = {}) {
571
+ return this.blockProvider.getBlock(param, options);
572
+ }
573
+ getBlockData(param) {
574
+ return this.blockProvider.getBlockData(param);
575
+ }
576
+ getBlocks(from, limit, options = {}) {
577
+ return this.blockProvider.getBlocks(from, limit, options);
578
+ }
579
+ getCheckpoint(param, options = {}) {
580
+ return this.blockProvider.getCheckpoint(param, options);
581
+ }
582
+ getCheckpoints(from, limit, options = {}) {
583
+ return this.blockProvider.getCheckpoints(from, limit, options);
712
584
  }
713
585
  /**
714
586
  * Returns the sequencer client instance.
@@ -716,6 +588,12 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
716
588
  */ getSequencer() {
717
589
  return this.sequencer;
718
590
  }
591
+ /** Test-only: returns the AutomineSequencer when wired via `useAutomineSequencer`. */ getAutomineSequencer() {
592
+ return this.automineSequencer;
593
+ }
594
+ /** Returns the prover node subsystem, if enabled. */ getProverNode() {
595
+ return this.proverNode;
596
+ }
719
597
  getBlockSource() {
720
598
  return this.blockSource;
721
599
  }
@@ -729,13 +607,16 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
729
607
  * Method to return the currently deployed L1 contract addresses.
730
608
  * @returns - The currently deployed L1 contract addresses.
731
609
  */ getL1ContractAddresses() {
732
- return Promise.resolve(this.config.l1Contracts);
610
+ return Promise.resolve(pickL1ContractAddresses(this.config));
733
611
  }
734
612
  getEncodedEnr() {
735
613
  return Promise.resolve(this.p2pClient.getEnr()?.encodeTxt());
736
614
  }
737
615
  async getAllowedPublicSetup() {
738
- return this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
616
+ return [
617
+ ...await getDefaultAllowedSetupFunctions(),
618
+ ...this.config.txPublicSetupAllowListExtend ?? []
619
+ ];
739
620
  }
740
621
  /**
741
622
  * Method to determine if the node is ready to accept transactions.
@@ -744,82 +625,47 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
744
625
  return Promise.resolve(this.p2pClient.isReady() ?? false);
745
626
  }
746
627
  async getNodeInfo() {
747
- const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses] = await Promise.all([
628
+ const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses, l1Constants] = await Promise.all([
748
629
  this.getNodeVersion(),
749
630
  this.getVersion(),
750
631
  this.getChainId(),
751
632
  this.getEncodedEnr(),
752
633
  this.getL1ContractAddresses(),
753
- this.getProtocolContractAddresses()
634
+ this.getProtocolContractAddresses(),
635
+ this.blockSource.getL1Constants()
754
636
  ]);
637
+ // Gas limits a single tx may declare on this network, derived from network-wide constants only (the
638
+ // timetable's blocks-per-checkpoint and the network-minimum per-block multipliers) — never this node's
639
+ // local caps or configured multipliers, which can make the node stricter at block-building time but
640
+ // cannot define what the network accepts for relay. Clients read txsLimits to set fallback gas limits.
641
+ const maxTxGas = getNetworkTxGasLimits(this.config, l1Constants);
755
642
  const nodeInfo = {
756
643
  nodeVersion,
757
644
  l1ChainId: chainId,
758
645
  rollupVersion,
759
646
  enr,
760
647
  l1ContractAddresses: contractAddresses,
761
- protocolContractAddresses: protocolContractAddresses
648
+ protocolContractAddresses: protocolContractAddresses,
649
+ realProofs: !!this.config.realProofs,
650
+ txsLimits: {
651
+ gas: {
652
+ daGas: maxTxGas.daGas,
653
+ l2Gas: maxTxGas.l2Gas
654
+ }
655
+ }
762
656
  };
763
657
  return nodeInfo;
764
658
  }
765
- /**
766
- * Get a block specified by its block number, block hash, or 'latest'.
767
- * @param block - The block parameter (block number, block hash, or 'latest').
768
- * @returns The requested block.
769
- */ async getBlock(block) {
770
- if (BlockHash.isBlockHash(block)) {
771
- return this.getBlockByHash(block);
772
- }
773
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
774
- if (blockNumber === BlockNumber.ZERO) {
775
- return this.buildInitialBlock();
776
- }
777
- return await this.blockSource.getL2Block(blockNumber);
778
- }
779
- /**
780
- * Get a block specified by its hash.
781
- * @param blockHash - The block hash being requested.
782
- * @returns The requested block.
783
- */ async getBlockByHash(blockHash) {
784
- const initialBlockHash = await this.#getInitialHeaderHash();
785
- if (blockHash.equals(initialBlockHash)) {
786
- return this.buildInitialBlock();
787
- }
788
- return await this.blockSource.getL2BlockByHash(blockHash);
789
- }
790
- buildInitialBlock() {
791
- const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
792
- return L2Block.empty(initialHeader);
793
- }
794
- /**
795
- * Get a block specified by its archive root.
796
- * @param archive - The archive root being requested.
797
- * @returns The requested block.
798
- */ async getBlockByArchive(archive) {
799
- return await this.blockSource.getL2BlockByArchive(archive);
800
- }
801
- /**
802
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
803
- * @param from - The start of the range of blocks to return.
804
- * @param limit - The maximum number of blocks to obtain.
805
- * @returns The blocks requested.
806
- */ async getBlocks(from, limit) {
807
- return await this.blockSource.getBlocks(from, BlockNumber(limit)) ?? [];
659
+ async getCurrentMinFees() {
660
+ return await this.feeProvider.getCurrentMinFees();
808
661
  }
809
- async getCheckpoints(from, limit) {
810
- return await this.blockSource.getCheckpoints(from, limit) ?? [];
811
- }
812
- async getCheckpointedBlocks(from, limit) {
813
- return await this.blockSource.getCheckpointedBlocks(from, limit) ?? [];
814
- }
815
- /**
816
- * Method to fetch the current min L2 fees.
817
- * @returns The current min L2 fees.
818
- */ async getCurrentMinFees() {
819
- return await this.globalVariableBuilder.getCurrentMinFees();
662
+ /** Returns predicted min fees for the current slot and next N slots. */ async getPredictedMinFees(manaUsage) {
663
+ return await this.feeProvider.getPredictedMinFees(manaUsage);
820
664
  }
821
665
  async getMaxPriorityFees() {
822
- for await (const tx of this.p2pClient.iteratePendingTxs()){
666
+ for await (const tx of this.p2pClient.iteratePendingTxs({
667
+ includeProof: false
668
+ })){
823
669
  return tx.getGasSettings().maxPriorityFeesPerGas;
824
670
  }
825
671
  return GasFees.from({
@@ -828,18 +674,6 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
828
674
  });
829
675
  }
830
676
  /**
831
- * Method to fetch the latest block number synchronized by the node.
832
- * @returns The block number.
833
- */ async getBlockNumber() {
834
- return await this.blockSource.getBlockNumber();
835
- }
836
- async getProvenBlockNumber() {
837
- return await this.blockSource.getProvenBlockNumber();
838
- }
839
- async getCheckpointedBlockNumber() {
840
- return await this.blockSource.getCheckpointedL2BlockNumber();
841
- }
842
- /**
843
677
  * Method to fetch the version of the package.
844
678
  * @returns The node package version
845
679
  */ getNodeVersion() {
@@ -860,46 +694,18 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
860
694
  getContractClass(id) {
861
695
  return this.contractDataSource.getContractClass(id);
862
696
  }
863
- getContract(address) {
864
- return this.contractDataSource.getContract(address);
865
- }
866
- async getPrivateLogsByTags(tags, page, referenceBlock) {
867
- if (referenceBlock) {
868
- const initialBlockHash = await this.#getInitialHeaderHash();
869
- if (!referenceBlock.equals(initialBlockHash)) {
870
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
871
- if (!header) {
872
- throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
873
- }
874
- }
875
- }
876
- return this.logsSource.getPrivateLogsByTags(tags, page);
877
- }
878
- async getPublicLogsByTagsFromContract(contractAddress, tags, page, referenceBlock) {
879
- if (referenceBlock) {
880
- const initialBlockHash = await this.#getInitialHeaderHash();
881
- if (!referenceBlock.equals(initialBlockHash)) {
882
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
883
- if (!header) {
884
- throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
885
- }
886
- }
697
+ async getContract(address, referenceBlock = 'latest') {
698
+ const blockData = await this.getBlockData(referenceBlock);
699
+ if (!blockData) {
700
+ throw new Error(`Reference block ${inspectBlockParameter(referenceBlock)} not found when querying contract ${address}. If the node API has been queried with an anchor block hash, possibly a reorg has occurred.`);
887
701
  }
888
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
702
+ return this.contractDataSource.getContract(address, blockData.header.globalVariables.timestamp);
889
703
  }
890
- /**
891
- * Gets public logs based on the provided filter.
892
- * @param filter - The filter to apply to the logs.
893
- * @returns The requested logs.
894
- */ getPublicLogs(filter) {
895
- return this.logsSource.getPublicLogs(filter);
704
+ getPrivateLogsByTags(query) {
705
+ return this.logsSource.getPrivateLogsByTags(query);
896
706
  }
897
- /**
898
- * Gets contract class logs based on the provided filter.
899
- * @param filter - The filter to apply to the logs.
900
- * @returns The requested logs.
901
- */ getContractClassLogs(filter) {
902
- return this.logsSource.getContractClassLogs(filter);
707
+ getPublicLogsByTags(query) {
708
+ return this.logsSource.getPublicLogsByTags(query);
903
709
  }
904
710
  /**
905
711
  * Method to submit a transaction to the p2p pool.
@@ -919,31 +725,23 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
919
725
  });
920
726
  throw new Error(`Invalid tx: ${reason}`);
921
727
  }
922
- await this.p2pClient.sendTx(tx);
923
- this.metrics.receivedTx(timer.ms(), true);
924
- this.log.info(`Received tx ${txHash}`, {
728
+ try {
729
+ await this.p2pClient.sendTx(tx);
730
+ } catch (err) {
731
+ this.metrics.receivedTx(timer.ms(), false);
732
+ this.log.warn(`Mempool rejected tx ${txHash}: ${err.message}`, {
733
+ txHash
734
+ });
735
+ throw err;
736
+ }
737
+ const duration = timer.ms();
738
+ this.metrics.receivedTx(duration, true);
739
+ this.log.info(`Received tx ${txHash} in ${duration}ms`, {
925
740
  txHash
926
741
  });
927
742
  }
928
- async getTxReceipt(txHash) {
929
- // Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
930
- // as a fallback if we don't find a settled receipt in the archiver.
931
- const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
932
- const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
933
- // Then get the actual tx from the archiver, which tracks every tx in a mined block.
934
- const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
935
- if (settledTxReceipt) {
936
- // If the archiver has the receipt then return it.
937
- return settledTxReceipt;
938
- } else if (isKnownToPool) {
939
- // If the tx is in the pool but not in the archiver, it's pending.
940
- // This handles race conditions between archiver and p2p, where the archiver
941
- // has pruned the block in which a tx was mined, but p2p has not caught up yet.
942
- return new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
943
- } else {
944
- // Otherwise, if we don't know the tx, we consider it dropped.
945
- return new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
946
- }
743
+ getTxReceipt(txHash, options) {
744
+ return this.txReceiptBuilder.getTxReceipt(txHash, options);
947
745
  }
948
746
  getTxEffect(txHash) {
949
747
  return this.blockSource.getTxEffect(txHash);
@@ -952,11 +750,15 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
952
750
  * Method to stop the aztec node.
953
751
  */ async stop() {
954
752
  this.log.info(`Stopping Aztec Node`);
955
- await tryStop(this.validatorsSentinel);
956
- await tryStop(this.epochPruneWatcher);
753
+ await this.stopStartedWatchers();
957
754
  await tryStop(this.slasherClient);
958
- await tryStop(this.proofVerifier);
755
+ await Promise.all([
756
+ tryStop(this.peerProofVerifier),
757
+ tryStop(this.rpcProofVerifier)
758
+ ]);
959
759
  await tryStop(this.sequencer);
760
+ await tryStop(this.automineSequencer);
761
+ await tryStop(this.proverNode);
960
762
  await tryStop(this.p2pClient);
961
763
  await tryStop(this.worldStateSynchronizer);
962
764
  await tryStop(this.blockSource);
@@ -975,293 +777,120 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
975
777
  * @param limit - The number of items to returns
976
778
  * @param after - The last known pending tx. Used for pagination
977
779
  * @returns - The pending txs.
978
- */ getPendingTxs(limit, after) {
979
- return this.p2pClient.getPendingTxs(limit, after);
780
+ */ getPendingTxs(limit, after, options) {
781
+ return this.p2pClient.getPendingTxs(limit, after, options);
980
782
  }
981
783
  getPendingTxCount() {
982
784
  return this.p2pClient.getPendingTxCount();
983
785
  }
786
+ getPeers(includePending) {
787
+ return this.p2pClient.getPeers(includePending);
788
+ }
789
+ getCheckpointAttestationsForSlot(slot, proposalPayloadHash) {
790
+ return this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalPayloadHash);
791
+ }
792
+ getProposalsForSlot(slot) {
793
+ return this.p2pClient.getProposalsForSlot(slot);
794
+ }
984
795
  /**
985
- * Method to retrieve a single tx from the mempool or unfinalized chain.
796
+ * Method to retrieve a single tx from the mempool or unfinalized chain. The tx's proof is only loaded and returned
797
+ * when `includeProof` is set.
986
798
  * @param txHash - The transaction hash to return.
799
+ * @param options - Options for the returned tx (eg whether to include its proof).
987
800
  * @returns - The tx if it exists.
988
- */ getTxByHash(txHash) {
989
- return Promise.resolve(this.p2pClient.getTxByHashFromPool(txHash));
801
+ */ getTxByHash(txHash, options) {
802
+ return this.p2pClient.getTxByHashFromPool(txHash, {
803
+ includeProof: !!options?.includeProof
804
+ });
990
805
  }
991
806
  /**
992
- * Method to retrieve txs from the mempool or unfinalized chain.
807
+ * Method to retrieve txs from the mempool or unfinalized chain. The txs' proofs are only loaded and returned when
808
+ * `includeProof` is set.
993
809
  * @param txHash - The transaction hash to return.
810
+ * @param options - Options for the returned txs (eg whether to include their proofs).
994
811
  * @returns - The txs if it exists.
995
- */ async getTxsByHash(txHashes) {
996
- return compactArray(await Promise.all(txHashes.map((txHash)=>this.getTxByHash(txHash))));
997
- }
998
- async findLeavesIndexes(referenceBlock, treeId, leafValues) {
999
- const committedDb = await this.#getWorldState(referenceBlock);
1000
- const maybeIndices = await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
1001
- // We filter out undefined values
1002
- const indices = maybeIndices.filter((x)=>x !== undefined);
1003
- // Now we find the block numbers for the indices
1004
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
1005
- // If any of the block numbers are undefined, we throw an error.
1006
- for(let i = 0; i < indices.length; i++){
1007
- if (blockNumbers[i] === undefined) {
1008
- throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
1009
- }
1010
- }
1011
- // Get unique block numbers in order to optimize num calls to getLeafValue function.
1012
- const uniqueBlockNumbers = [
1013
- ...new Set(blockNumbers.filter((x)=>x !== undefined))
1014
- ];
1015
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
1016
- // (note that block number corresponds to the leaf index in the archive tree).
1017
- const blockHashes = await Promise.all(uniqueBlockNumbers.map((blockNumber)=>{
1018
- return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1019
- }));
1020
- // If any of the block hashes are undefined, we throw an error.
1021
- for(let i = 0; i < uniqueBlockNumbers.length; i++){
1022
- if (blockHashes[i] === undefined) {
1023
- throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
1024
- }
1025
- }
1026
- // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
1027
- return maybeIndices.map((index, i)=>{
1028
- if (index === undefined) {
1029
- return undefined;
1030
- }
1031
- const blockNumber = blockNumbers[i];
1032
- if (blockNumber === undefined) {
1033
- return undefined;
1034
- }
1035
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
1036
- const blockHash = blockHashes[blockHashIndex];
1037
- if (!blockHash) {
1038
- return undefined;
1039
- }
1040
- return {
1041
- l2BlockNumber: BlockNumber(Number(blockNumber)),
1042
- l2BlockHash: new BlockHash(blockHash),
1043
- data: index
1044
- };
812
+ */ async getTxsByHash(txHashes, options) {
813
+ const txs = await this.p2pClient.getTxsByHashFromPool(txHashes, {
814
+ includeProof: !!options?.includeProof
1045
815
  });
816
+ return compactArray(txs);
1046
817
  }
1047
- async getBlockHashMembershipWitness(referenceBlock, blockHash) {
1048
- const committedDb = await this.#getWorldState(referenceBlock);
1049
- const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE, [
1050
- blockHash
1051
- ]);
1052
- return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
818
+ findLeavesIndexes(referenceBlock, treeId, leafValues) {
819
+ return this.worldStateQueries.findLeavesIndexes(referenceBlock, treeId, leafValues);
1053
820
  }
1054
- async getNoteHashMembershipWitness(referenceBlock, noteHash) {
1055
- const committedDb = await this.#getWorldState(referenceBlock);
1056
- const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE, [
1057
- noteHash
1058
- ]);
1059
- return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
821
+ getBlockHashMembershipWitness(referenceBlock, blockHash) {
822
+ return this.worldStateQueries.getBlockHashMembershipWitness(referenceBlock, blockHash);
1060
823
  }
1061
- async getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
1062
- const db = await this.#getWorldState(referenceBlock);
1063
- const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
1064
- l1ToL2Message
1065
- ]);
1066
- if (!witness) {
1067
- return undefined;
1068
- }
1069
- // REFACTOR: Return a MembershipWitness object
1070
- return [
1071
- witness.index,
1072
- witness.path
1073
- ];
824
+ getNoteHashMembershipWitness(referenceBlock, noteHash) {
825
+ return this.worldStateQueries.getNoteHashMembershipWitness(referenceBlock, noteHash);
1074
826
  }
1075
- async getL1ToL2MessageBlock(l1ToL2Message) {
1076
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1077
- return messageIndex ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex)) : undefined;
827
+ getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
828
+ return this.worldStateQueries.getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message);
1078
829
  }
1079
- /**
1080
- * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
1081
- * @param l1ToL2Message - The L1 to L2 message to check.
1082
- * @returns Whether the message is synced and ready to be included in a block.
1083
- */ async isL1ToL2MessageSynced(l1ToL2Message) {
1084
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1085
- return messageIndex !== undefined;
830
+ getL1ToL2MessageCheckpoint(l1ToL2Message) {
831
+ return this.worldStateQueries.getL1ToL2MessageCheckpoint(l1ToL2Message);
1086
832
  }
1087
833
  /**
1088
834
  * Returns all the L2 to L1 messages in an epoch.
835
+ *
836
+ * @deprecated Use {@link getL2ToL1MembershipWitness} to get an L2-to-L1 message witness directly.
837
+ *
1089
838
  * @param epoch - The epoch at which to get the data.
1090
839
  * @returns The L2 to L1 messages (empty array if the epoch is not found).
1091
- */ async getL2ToL1Messages(epoch) {
1092
- // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1093
- const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1094
- const blocksInCheckpoints = [];
1095
- let previousSlotNumber = SlotNumber.ZERO;
1096
- let checkpointIndex = -1;
1097
- for (const checkpointedBlock of checkpointedBlocks){
1098
- const block = checkpointedBlock.block;
1099
- const slotNumber = block.header.globalVariables.slotNumber;
1100
- if (slotNumber !== previousSlotNumber) {
1101
- checkpointIndex++;
1102
- blocksInCheckpoints.push([]);
1103
- previousSlotNumber = slotNumber;
1104
- }
1105
- blocksInCheckpoints[checkpointIndex].push(block);
1106
- }
1107
- return blocksInCheckpoints.map((blocks)=>blocks.map((block)=>block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs)));
1108
- }
1109
- async getNullifierMembershipWitness(referenceBlock, nullifier) {
1110
- const db = await this.#getWorldState(referenceBlock);
1111
- const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [
1112
- nullifier.toBuffer()
1113
- ]);
1114
- if (!witness) {
1115
- return undefined;
1116
- }
1117
- const { index, path } = witness;
1118
- const leafPreimage = await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1119
- if (!leafPreimage) {
1120
- return undefined;
1121
- }
1122
- return new NullifierMembershipWitness(index, leafPreimage, path);
840
+ */ getL2ToL1Messages(epoch) {
841
+ return this.worldStateQueries.getL2ToL1Messages(epoch);
1123
842
  }
1124
843
  /**
1125
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1126
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1127
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1128
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1129
- * @returns The low nullifier membership witness (if found).
1130
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1131
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1132
- * we are trying to prove non-inclusion for.
1133
- *
1134
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1135
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1136
- * index of the nullifier itself when it already exists in the tree.
1137
- * TODO: This is a confusing behavior and we should eventually address that.
1138
- */ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1139
- const committedDb = await this.#getWorldState(referenceBlock);
1140
- const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1141
- if (!findResult) {
1142
- return undefined;
1143
- }
1144
- const { index, alreadyPresent } = findResult;
1145
- if (alreadyPresent) {
1146
- this.log.warn(`Nullifier ${nullifier.toBigInt()} already exists in the tree`);
1147
- }
1148
- const preimageData = await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1149
- const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1150
- return new NullifierMembershipWitness(BigInt(index), preimageData, siblingPath);
1151
- }
1152
- async getPublicDataWitness(referenceBlock, leafSlot) {
1153
- const committedDb = await this.#getWorldState(referenceBlock);
1154
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1155
- if (!lowLeafResult) {
1156
- return undefined;
1157
- } else {
1158
- const preimage = await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1159
- const path = await committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1160
- return new PublicDataWitness(lowLeafResult.index, preimage, path);
1161
- }
844
+ * Returns the L2-to-L1 membership witness for a message in `txHash`. Passthrough to the
845
+ * archiver's locally-cached resolver — see {@link Archiver.getL2ToL1MembershipWitness}.
846
+ */ getL2ToL1MembershipWitness(txHash, message, messageIndexInTx) {
847
+ return this.worldStateQueries.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
1162
848
  }
1163
- async getPublicStorageAt(referenceBlock, contract, slot) {
1164
- const committedDb = await this.#getWorldState(referenceBlock);
1165
- const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1166
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1167
- if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
1168
- return Fr.ZERO;
1169
- }
1170
- const preimage = await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1171
- return preimage.leaf.value;
1172
- }
1173
- async getBlockHeader(block = 'latest') {
1174
- if (BlockHash.isBlockHash(block)) {
1175
- const initialBlockHash = await this.#getInitialHeaderHash();
1176
- if (block.equals(initialBlockHash)) {
1177
- // Block source doesn't handle initial header so we need to handle the case separately.
1178
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1179
- }
1180
- return this.blockSource.getBlockHeaderByHash(block);
1181
- } else {
1182
- // Block source doesn't handle initial header so we need to handle the case separately.
1183
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
1184
- if (blockNumber === BlockNumber.ZERO) {
1185
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1186
- }
1187
- return this.blockSource.getBlockHeader(block);
1188
- }
849
+ getNullifierMembershipWitness(referenceBlock, nullifier) {
850
+ return this.worldStateQueries.getNullifierMembershipWitness(referenceBlock, nullifier);
1189
851
  }
1190
- /**
1191
- * Get a block header specified by its archive root.
1192
- * @param archive - The archive root being requested.
1193
- * @returns The requested block header.
1194
- */ async getBlockHeaderByArchive(archive) {
1195
- return await this.blockSource.getBlockHeaderByArchive(archive);
852
+ getLowNullifierMembershipWitness(referenceBlock, nullifier) {
853
+ return this.worldStateQueries.getLowNullifierMembershipWitness(referenceBlock, nullifier);
854
+ }
855
+ getPublicDataWitness(referenceBlock, leafSlot) {
856
+ return this.worldStateQueries.getPublicDataWitness(referenceBlock, leafSlot);
857
+ }
858
+ getPublicStorageAt(referenceBlock, contract, slot) {
859
+ return this.worldStateQueries.getPublicStorageAt(referenceBlock, contract, slot);
1196
860
  }
1197
861
  /**
1198
862
  * Simulates the public part of a transaction with the current state.
1199
863
  * @param tx - The transaction to simulate.
1200
- **/ async simulatePublicCalls(tx, skipFeeEnforcement = false) {
1201
- // Check total gas limit for simulation
1202
- const gasSettings = tx.data.constants.txContext.gasSettings;
1203
- const txGasLimit = gasSettings.gasLimits.l2Gas;
1204
- const teardownGasLimit = gasSettings.teardownGasLimits.l2Gas;
1205
- if (txGasLimit + teardownGasLimit > this.config.rpcSimulatePublicMaxGasLimit) {
1206
- throw new BadRequestError(`Transaction total gas limit ${txGasLimit + teardownGasLimit} (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${this.config.rpcSimulatePublicMaxGasLimit} for simulation`);
1207
- }
1208
- const txHash = tx.getTxHash();
1209
- const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
1210
- // If sequencer is not initialized, we just set these values to zero for simulation.
1211
- const coinbase = EthAddress.ZERO;
1212
- const feeRecipient = AztecAddress.ZERO;
1213
- const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(blockNumber, coinbase, feeRecipient);
1214
- const publicProcessorFactory = new PublicProcessorFactory(this.contractDataSource, new DateProvider(), this.telemetry, this.log.getBindings());
1215
- this.log.verbose(`Simulating public calls for tx ${txHash}`, {
1216
- globalVariables: newGlobalVariables.toInspect(),
1217
- txHash,
1218
- blockNumber
1219
- });
1220
- const merkleTreeFork = await this.worldStateSynchronizer.fork();
1221
- try {
1222
- const config = PublicSimulatorConfig.from({
1223
- skipFeeEnforcement,
1224
- collectDebugLogs: true,
1225
- collectHints: false,
1226
- collectCallMetadata: true,
1227
- collectStatistics: false,
1228
- collectionLimits: CollectionLimitsConfig.from({
1229
- maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads
1230
- })
1231
- });
1232
- const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1233
- // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1234
- const [processedTxs, failedTxs, _usedTxs, returns] = await processor.process([
1235
- tx
1236
- ]);
1237
- // REFACTOR: Consider returning the error rather than throwing
1238
- if (failedTxs.length) {
1239
- this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, {
1240
- txHash
1241
- });
1242
- throw failedTxs[0].error;
1243
- }
1244
- const [processedTx] = processedTxs;
1245
- return new PublicSimulationOutput(processedTx.revertReason, processedTx.globalVariables, processedTx.txEffect, returns, processedTx.gasUsed);
1246
- } finally{
1247
- await merkleTreeFork.close();
1248
- }
864
+ * @param skipFeeEnforcement - If true, fee enforcement is skipped.
865
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
866
+ **/ simulatePublicCalls(tx, skipFeeEnforcement = false, overrides) {
867
+ return this.nodePublicCallsSimulator.simulate(tx, skipFeeEnforcement, overrides);
1249
868
  }
1250
869
  async isValidTx(tx, { isSimulation, skipFeeEnforcement } = {}) {
1251
870
  const db = this.worldStateSynchronizer.getCommitted();
1252
- const verifier = isSimulation ? undefined : this.proofVerifier;
1253
- // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
871
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
872
+ // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1254
873
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1255
874
  const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
1256
- const validator = createValidatorForAcceptingTxs(db, this.contractDataSource, verifier, {
875
+ const l1Constants = await this.blockSource.getL1Constants();
876
+ // Enforce the same network admission limit the node advertises in getNodeInfo (network-wide, not this
877
+ // node's local caps), so a tx the wallet sized against txsLimits is not rejected here.
878
+ const networkTxGasLimits = getNetworkTxGasLimits(this.config, l1Constants);
879
+ const validator = createTxValidatorForAcceptingTxsOverRPC(db, this.contractDataSource, verifier, {
1257
880
  timestamp: nextSlotTimestamp,
1258
881
  blockNumber,
1259
882
  l1ChainId: this.l1ChainId,
1260
883
  rollupVersion: this.version,
1261
- setupAllowList: this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions(),
884
+ setupAllowList: [
885
+ ...await getDefaultAllowedSetupFunctions(),
886
+ ...this.config.txPublicSetupAllowListExtend ?? []
887
+ ],
1262
888
  gasFees: await this.getCurrentMinFees(),
1263
889
  skipFeeEnforcement,
1264
- txsPermitted: !this.config.disableTransactions
890
+ isSimulation,
891
+ txsPermitted: !this.config.disableTransactions,
892
+ maxTxL2Gas: networkTxGasLimits.l2Gas,
893
+ maxTxDAGas: networkTxGasLimits.daGas
1265
894
  }, this.log.getBindings());
1266
895
  return await validator.validateTx(tx);
1267
896
  }
@@ -1275,7 +904,20 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1275
904
  ...this.config,
1276
905
  ...config
1277
906
  };
1278
- this.sequencer?.updateConfig(config);
907
+ // If the sequencer is currently paused via pauseSequencer(), record the caller's desired
908
+ // minTxsPerBlock as the restore value (so resumeSequencer applies it) and keep the freeze
909
+ // (MAX_SAFE_INTEGER) applied to the underlying sequencer. Without this guard, forwarding
910
+ // the new minTxsPerBlock to the sequencer would silently unpause block production while
911
+ // pauseSequencer() still considers it paused.
912
+ const sequencerUpdate = {
913
+ ...config
914
+ };
915
+ if (this.sequencerPausedMinTxsPerBlock !== undefined && sequencerUpdate.minTxsPerBlock !== undefined) {
916
+ this.sequencerPausedMinTxsPerBlock = sequencerUpdate.minTxsPerBlock;
917
+ delete sequencerUpdate.minTxsPerBlock;
918
+ }
919
+ this.sequencer?.updateConfig(sequencerUpdate);
920
+ this.automineSequencer?.updateConfig(sequencerUpdate);
1279
921
  this.slasherClient?.updateConfig(config);
1280
922
  this.validatorsSentinel?.updateConfig(config);
1281
923
  await this.p2pClient.updateP2PConfig(config);
@@ -1284,7 +926,18 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1284
926
  archiver.updateConfig(config);
1285
927
  }
1286
928
  if (newConfig.realProofs !== this.config.realProofs) {
1287
- this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
929
+ await Promise.all([
930
+ tryStop(this.peerProofVerifier),
931
+ tryStop(this.rpcProofVerifier)
932
+ ]);
933
+ if (newConfig.realProofs) {
934
+ this.peerProofVerifier = await BatchChonkVerifier.new(newConfig, newConfig.bbChonkVerifyMaxBatch, 'peer');
935
+ const rpcVerifier = await BBCircuitVerifier.new(newConfig);
936
+ this.rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, newConfig.numConcurrentIVCVerifiers);
937
+ } else {
938
+ this.peerProofVerifier = new TestCircuitVerifier();
939
+ this.rpcProofVerifier = new TestCircuitVerifier();
940
+ }
1288
941
  }
1289
942
  this.config = newConfig;
1290
943
  }
@@ -1293,7 +946,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1293
946
  classRegistry: ProtocolContractAddress.ContractClassRegistry,
1294
947
  feeJuice: ProtocolContractAddress.FeeJuice,
1295
948
  instanceRegistry: ProtocolContractAddress.ContractInstanceRegistry,
1296
- multiCallEntrypoint: ProtocolContractAddress.MultiCallEntrypoint
949
+ multiCallEntrypoint: STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS
1297
950
  });
1298
951
  }
1299
952
  registerContractFunctionSignatures(signatures) {
@@ -1344,7 +997,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1344
997
  });
1345
998
  return Promise.resolve();
1346
999
  }
1347
- async rollbackTo(targetBlock, force) {
1000
+ async rollbackTo(targetBlock, force, resumeSync = true) {
1348
1001
  const archiver = this.blockSource;
1349
1002
  if (!('rollbackTo' in archiver)) {
1350
1003
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1372,9 +1025,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1372
1025
  this.log.error(`Error during rollback`, err);
1373
1026
  throw err;
1374
1027
  } finally{
1375
- this.log.info(`Resuming world state and archiver sync.`);
1376
- this.worldStateSynchronizer.resumeSync();
1377
- archiver.resume();
1028
+ if (resumeSync) {
1029
+ this.log.info(`Resuming world state and archiver sync.`);
1030
+ this.worldStateSynchronizer.resumeSync();
1031
+ archiver.resume();
1032
+ } else {
1033
+ this.log.info(`Sync left paused after rollback (resumeSync=false).`);
1034
+ }
1378
1035
  }
1379
1036
  }
1380
1037
  async pauseSync() {
@@ -1388,73 +1045,176 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1388
1045
  this.blockSource.resume();
1389
1046
  return Promise.resolve();
1390
1047
  }
1391
- getSlashPayloads() {
1392
- if (!this.slasherClient) {
1393
- throw new Error(`Slasher client not enabled`);
1048
+ pauseSequencer() {
1049
+ if (this.automineSequencer) {
1050
+ this.automineSequencer.pause();
1051
+ return Promise.resolve();
1052
+ }
1053
+ if (this.sequencer) {
1054
+ if (this.sequencerPausedMinTxsPerBlock === undefined) {
1055
+ this.sequencerPausedMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock ?? 0;
1056
+ this.sequencer.updateConfig({
1057
+ minTxsPerBlock: Number.MAX_SAFE_INTEGER
1058
+ });
1059
+ this.log.info(`Sequencer paused (minTxsPerBlock set to MAX_SAFE_INTEGER)`, {
1060
+ previousMinTxsPerBlock: this.sequencerPausedMinTxsPerBlock
1061
+ });
1062
+ }
1063
+ return Promise.resolve();
1064
+ }
1065
+ throw new BadRequestError('Cannot pause sequencer: no sequencer is running');
1066
+ }
1067
+ resumeSequencer() {
1068
+ if (this.automineSequencer) {
1069
+ this.automineSequencer.resume();
1070
+ return Promise.resolve();
1071
+ }
1072
+ if (this.sequencer) {
1073
+ if (this.sequencerPausedMinTxsPerBlock !== undefined) {
1074
+ const restored = this.sequencerPausedMinTxsPerBlock;
1075
+ this.sequencerPausedMinTxsPerBlock = undefined;
1076
+ this.sequencer.updateConfig({
1077
+ minTxsPerBlock: restored
1078
+ });
1079
+ this.log.info(`Sequencer resumed (minTxsPerBlock restored)`, {
1080
+ minTxsPerBlock: restored
1081
+ });
1082
+ }
1083
+ return Promise.resolve();
1394
1084
  }
1395
- return this.slasherClient.getSlashPayloads();
1085
+ throw new BadRequestError('Cannot resume sequencer: no sequencer is running');
1396
1086
  }
1397
1087
  getSlashOffenses(round) {
1398
1088
  if (!this.slasherClient) {
1399
1089
  throw new Error(`Slasher client not enabled`);
1400
1090
  }
1401
1091
  if (round === 'all') {
1402
- return this.slasherClient.getPendingOffenses();
1092
+ return this.slasherClient.getOffenses();
1403
1093
  } else {
1404
1094
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1405
1095
  }
1406
1096
  }
1407
- #getInitialHeaderHash() {
1408
- if (!this.initialHeaderHashPromise) {
1409
- this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
1097
+ async reloadKeystore() {
1098
+ if (!this.config.keyStoreDirectory?.length) {
1099
+ throw new BadRequestError('Cannot reload keystore: node is not using a file-based keystore. ' + 'Set KEY_STORE_DIRECTORY to use file-based keystores.');
1100
+ }
1101
+ if (!this.validatorClient) {
1102
+ throw new BadRequestError('Cannot reload keystore: validator is not enabled.');
1103
+ }
1104
+ this.log.info('Reloading keystore from disk');
1105
+ // Re-read and validate keystore files
1106
+ const keyStores = loadKeystores(this.config.keyStoreDirectory);
1107
+ const newManager = new KeystoreManager(mergeKeystores(keyStores));
1108
+ await newManager.validateSigners();
1109
+ ValidatorClient.validateKeyStoreConfiguration(newManager, this.log);
1110
+ // Validate that every validator's publisher keys overlap with the L1 signers
1111
+ // that were initialized at startup. Publishers cannot be hot-reloaded, so a
1112
+ // validator with a publisher key that doesn't match any existing L1 signer
1113
+ // would silently fail on every proposer slot.
1114
+ if (this.keyStoreManager && this.sequencer) {
1115
+ const oldAdapter = NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager);
1116
+ const availablePublishers = new Set(oldAdapter.getAttesterAddresses().flatMap((a)=>oldAdapter.getPublisherAddresses(a).map((p)=>p.toString().toLowerCase())));
1117
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
1118
+ for (const attester of newAdapter.getAttesterAddresses()){
1119
+ const pubs = newAdapter.getPublisherAddresses(attester);
1120
+ if (pubs.length > 0 && !pubs.some((p)=>availablePublishers.has(p.toString().toLowerCase()))) {
1121
+ 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 ` + `[${[
1122
+ ...availablePublishers
1123
+ ].join(', ')}]. Publishers cannot be hot-reloaded — ` + `use an existing publisher key or restart the node.`);
1124
+ }
1125
+ }
1410
1126
  }
1411
- return this.initialHeaderHashPromise;
1412
- }
1413
- /**
1414
- * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1415
- * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1416
- * @returns An instance of a committed MerkleTreeOperations
1417
- */ async #getWorldState(block) {
1418
- let blockSyncedTo = BlockNumber.ZERO;
1127
+ // Build adapters for old and new keystores to compute diff
1128
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
1129
+ const newAddresses = newAdapter.getAttesterAddresses();
1130
+ const oldAddresses = this.keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager).getAttesterAddresses() : [];
1131
+ const oldSet = new Set(oldAddresses.map((a)=>a.toString()));
1132
+ const newSet = new Set(newAddresses.map((a)=>a.toString()));
1133
+ const added = newAddresses.filter((a)=>!oldSet.has(a.toString()));
1134
+ const removed = oldAddresses.filter((a)=>!newSet.has(a.toString()));
1135
+ if (added.length > 0) {
1136
+ this.log.info(`Keystore reload: adding attester keys: ${added.map((a)=>a.toString()).join(', ')}`);
1137
+ }
1138
+ if (removed.length > 0) {
1139
+ this.log.info(`Keystore reload: removing attester keys: ${removed.map((a)=>a.toString()).join(', ')}`);
1140
+ }
1141
+ if (added.length === 0 && removed.length === 0) {
1142
+ this.log.info('Keystore reload: attester keys unchanged');
1143
+ }
1144
+ // Update the validator client (coinbase, feeRecipient, attester keys)
1145
+ this.validatorClient.reloadKeystore(newManager);
1146
+ // Update the publisher factory's keystore so newly-added validators
1147
+ // can be matched to existing publisher keys when proposing blocks.
1148
+ if (this.sequencer) {
1149
+ this.sequencer.updatePublisherNodeKeyStore(newAdapter);
1150
+ }
1151
+ // Update slasher's "don't-slash-self" list with new validator addresses
1152
+ if (this.slasherClient && !this.config.slashSelfAllowed) {
1153
+ const slashValidatorsNever = unique([
1154
+ ...this.config.slashValidatorsNever ?? [],
1155
+ ...newAddresses
1156
+ ].map((a)=>a.toString())).map(EthAddress.fromString);
1157
+ this.slasherClient.updateConfig({
1158
+ slashValidatorsNever
1159
+ });
1160
+ }
1161
+ this.keyStoreManager = newManager;
1162
+ this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1163
+ }
1164
+ async mineBlock() {
1165
+ if (this.automineSequencer) {
1166
+ await this.automineSequencer.buildEmptyBlock();
1167
+ return;
1168
+ }
1169
+ if (!this.sequencer) {
1170
+ throw new BadRequestError('Cannot mine block: no sequencer is running');
1171
+ }
1172
+ const currentBlockNumber = await this.getBlockNumber();
1173
+ // Use slot duration + 50% buffer as the timeout so this works on running networks too
1174
+ const { slotDuration } = await this.blockSource.getL1Constants();
1175
+ const timeoutSeconds = Math.ceil(slotDuration * 1.5);
1176
+ // Temporarily set minTxsPerBlock to 0 so the sequencer produces a block even with no txs
1177
+ const originalMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock;
1178
+ this.sequencer.updateConfig({
1179
+ minTxsPerBlock: 0
1180
+ });
1419
1181
  try {
1420
- // Attempt to sync the world state if necessary
1421
- blockSyncedTo = await this.#syncWorldState();
1422
- } catch (err) {
1423
- this.log.error(`Error getting world state: ${err}`);
1182
+ // Trigger the sequencer to produce a block immediately
1183
+ void this.sequencer.trigger();
1184
+ // Wait for the new L2 block to appear
1185
+ await retryUntil(async ()=>{
1186
+ const newBlockNumber = await this.getBlockNumber();
1187
+ return newBlockNumber > currentBlockNumber ? true : undefined;
1188
+ }, 'mineBlock', timeoutSeconds, 0.1);
1189
+ } finally{
1190
+ this.sequencer.updateConfig({
1191
+ minTxsPerBlock: originalMinTxsPerBlock
1192
+ });
1424
1193
  }
1425
- if (block === 'latest') {
1426
- this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
1427
- return this.worldStateSynchronizer.getCommitted();
1194
+ }
1195
+ async prove(upToCheckpoint) {
1196
+ if (!this.automineSequencer) {
1197
+ throw new BadRequestError('Cannot prove checkpoint: no automine sequencer is running');
1428
1198
  }
1429
- if (BlockHash.isBlockHash(block)) {
1430
- const initialBlockHash = await this.#getInitialHeaderHash();
1431
- if (block.equals(initialBlockHash)) {
1432
- // Block source doesn't handle initial header so we need to handle the case separately.
1433
- return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1434
- }
1435
- const header = await this.blockSource.getBlockHeaderByHash(block);
1436
- if (!header) {
1437
- 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.`);
1438
- }
1439
- const blockNumber = header.getBlockNumber();
1440
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1441
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1199
+ return await this.automineSequencer.prove(upToCheckpoint);
1200
+ }
1201
+ async warpL2TimeAtLeastTo(targetTimestamp) {
1202
+ if (!this.automineSequencer) {
1203
+ throw new BadRequestError('Cannot warp L2 time: no automine sequencer is running');
1442
1204
  }
1443
- // Block number provided
1444
- {
1445
- const blockNumber = block;
1446
- if (blockNumber > blockSyncedTo) {
1447
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1448
- }
1449
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1450
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1205
+ await this.automineSequencer.warpTo(targetTimestamp);
1206
+ }
1207
+ async warpL2TimeAtLeastBy(duration) {
1208
+ if (!this.automineSequencer) {
1209
+ throw new BadRequestError('Cannot warp L2 time: no automine sequencer is running');
1451
1210
  }
1211
+ await this.automineSequencer.warpBy(duration);
1452
1212
  }
1453
1213
  /**
1454
- * Ensure we fully sync the world state
1455
- * @returns A promise that fulfils once the world state is synced
1456
- */ async #syncWorldState() {
1457
- const blockSourceHeight = await this.blockSource.getBlockNumber();
1458
- return await this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
1214
+ * Returns a committed world-state view at `block`, driving sync first. Delegates to
1215
+ * {@link NodeWorldStateQueries.getWorldState}; kept as a protected method so subclasses and tests can
1216
+ * exercise the node's block-resolution and reorg-aware sync behavior.
1217
+ */ getWorldState(block) {
1218
+ return this.worldStateQueries.getWorldState(block);
1459
1219
  }
1460
1220
  }