@aztec/aztec-node 0.0.1-commit.96dac018d → 0.0.1-commit.9a89641

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 +17 -5
  5. package/dest/aztec-node/config.d.ts.map +1 -1
  6. package/dest/aztec-node/config.js +16 -6
  7. package/dest/aztec-node/node_public_calls_simulator.d.ts +97 -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 +351 -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 +134 -140
  17. package/dest/aztec-node/server.d.ts.map +1 -1
  18. package/dest/aztec-node/server.js +413 -787
  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 +531 -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 +145 -21
  45. package/dest/sentinel/sentinel.d.ts.map +1 -1
  46. package/dest/sentinel/sentinel.js +230 -108
  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 +25 -17
  50. package/dest/test/index.d.ts +3 -3
  51. package/dest/test/index.d.ts.map +1 -1
  52. package/package.json +28 -27
  53. package/src/aztec-node/block_response_helpers.ts +161 -0
  54. package/src/aztec-node/config.ts +31 -8
  55. package/src/aztec-node/node_public_calls_simulator.ts +394 -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 +537 -1020
  59. package/src/bin/index.ts +19 -12
  60. package/src/factory.ts +697 -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 +280 -133
  70. package/src/sentinel/store.ts +26 -18
  71. package/src/test/index.ts +2 -2
@@ -371,59 +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 { Blob } from '@aztec/blob-lib';
378
- import { EpochCache } from '@aztec/epoch-cache';
379
- import { createEthereumChain } from '@aztec/ethereum/chain';
380
- import { getPublicClient } from '@aztec/ethereum/client';
381
- import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
382
- import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
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';
383
378
  import { compactArray, pick, unique } from '@aztec/foundation/collection';
384
- import { Fr } from '@aztec/foundation/curves/bn254';
385
379
  import { EthAddress } from '@aztec/foundation/eth-address';
386
380
  import { BadRequestError } from '@aztec/foundation/json-rpc';
387
381
  import { createLogger } from '@aztec/foundation/log';
382
+ import { retryUntil } from '@aztec/foundation/retry';
388
383
  import { count } from '@aztec/foundation/string';
389
- import { DateProvider, Timer } from '@aztec/foundation/timer';
390
- import { MembershipWitness } from '@aztec/foundation/trees';
384
+ import { Timer } from '@aztec/foundation/timer';
391
385
  import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
392
- import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
393
- import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
394
- import { createP2PClient, createTxValidatorForAcceptingTxsOverRPC, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
386
+ import { uploadSnapshot } from '@aztec/node-lib/actions';
387
+ import { createTxValidatorForAcceptingTxsOverRPC, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
395
388
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
396
- import { createProverNode } from '@aztec/prover-node';
397
- import { createKeyStoreForProver } from '@aztec/prover-node/config';
398
- import { GlobalVariableBuilder, SequencerClient } from '@aztec/sequencer-client';
399
- import { PublicProcessorFactory } from '@aztec/simulator/server';
400
- import { AttestationsBlockWatcher, EpochPruneWatcher, createSlasher } from '@aztec/slasher';
401
- import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
402
- import { AztecAddress } from '@aztec/stdlib/aztec-address';
403
- import { BlockHash, L2Block } from '@aztec/stdlib/block';
404
- import { GasFees } from '@aztec/stdlib/gas';
405
- 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';
406
392
  import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
407
393
  import { tryStop } from '@aztec/stdlib/interfaces/server';
408
- import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
409
- import { InboxLeaf } from '@aztec/stdlib/messaging';
410
- import { P2PClientType } from '@aztec/stdlib/p2p';
411
- import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
412
- import { PublicSimulationOutput, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
413
- import { getPackageVersion } from '@aztec/stdlib/update-checker';
394
+ import { NullDebugLogStore } from '@aztec/stdlib/logs';
414
395
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
415
- import { FullNodeCheckpointsBuilder as CheckpointsBuilder, FullNodeCheckpointsBuilder, NodeKeystoreAdapter, ValidatorClient, createBlockProposalHandler, createValidatorClient } from '@aztec/validator-client';
416
- import { createWorldStateSynchronizer } from '@aztec/world-state';
417
- import { createPublicClient, fallback, http } from 'viem';
418
- import { createSentinel } from '../sentinel/factory.js';
419
- 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';
420
400
  import { NodeMetrics } from './node_metrics.js';
401
+ import { NodePublicCallsSimulator } from './node_public_calls_simulator.js';
421
402
  _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
422
403
  [Attributes.TX_HASH]: tx.getTxHash().toString()
423
404
  }));
424
405
  /**
425
406
  * The aztec node.
426
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;
427
427
  config;
428
428
  p2pClient;
429
429
  blockSource;
@@ -435,338 +435,155 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
435
435
  proverNode;
436
436
  slasherClient;
437
437
  validatorsSentinel;
438
- epochPruneWatcher;
438
+ stopStartedWatchers;
439
439
  l1ChainId;
440
440
  version;
441
441
  globalVariableBuilder;
442
+ rollupContract;
443
+ feeProvider;
442
444
  epochCache;
443
445
  packageVersion;
444
- proofVerifier;
446
+ peerProofVerifier;
447
+ rpcProofVerifier;
445
448
  telemetry;
446
449
  log;
447
450
  blobClient;
448
451
  validatorClient;
449
452
  keyStoreManager;
450
453
  debugLogStore;
451
- static{
452
- ({ e: [_initProto] } = _apply_decs_2203_r(this, [
453
- [
454
- _dec,
455
- 2,
456
- "simulatePublicCalls"
457
- ]
458
- ], []));
459
- }
460
- metrics;
461
- initialHeaderHashPromise;
462
- // Prevent two snapshot operations to happen simultaneously
463
- isUploadingSnapshot;
464
- tracer;
465
- constructor(config, p2pClient, blockSource, logsSource, contractDataSource, l1ToL2MessageSource, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, epochPruneWatcher, l1ChainId, version, globalVariableBuilder, epochCache, packageVersion, proofVerifier, telemetry = getTelemetryClient(), log = createLogger('node'), blobClient, validatorClient, keyStoreManager, debugLogStore = new NullDebugLogStore()){
466
- this.config = config;
467
- this.p2pClient = p2pClient;
468
- this.blockSource = blockSource;
469
- this.logsSource = logsSource;
470
- this.contractDataSource = contractDataSource;
471
- this.l1ToL2MessageSource = l1ToL2MessageSource;
472
- this.worldStateSynchronizer = worldStateSynchronizer;
473
- this.sequencer = sequencer;
474
- this.proverNode = proverNode;
475
- this.slasherClient = slasherClient;
476
- this.validatorsSentinel = validatorsSentinel;
477
- this.epochPruneWatcher = epochPruneWatcher;
478
- this.l1ChainId = l1ChainId;
479
- this.version = version;
480
- this.globalVariableBuilder = globalVariableBuilder;
481
- this.epochCache = epochCache;
482
- this.packageVersion = packageVersion;
483
- this.proofVerifier = proofVerifier;
484
- this.telemetry = telemetry;
485
- this.log = log;
486
- this.blobClient = blobClient;
487
- this.validatorClient = validatorClient;
488
- this.keyStoreManager = keyStoreManager;
489
- this.debugLogStore = debugLogStore;
490
- this.initialHeaderHashPromise = (_initProto(this), undefined);
491
- this.isUploadingSnapshot = false;
492
- this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
493
- this.tracer = telemetry.getTracer('AztecNodeService');
454
+ automineSequencer;
455
+ avmSimulator;
456
+ constructor(deps){
457
+ this.config = deps.config;
458
+ this.p2pClient = deps.p2pClient;
459
+ this.blockSource = deps.blockSource;
460
+ this.logsSource = deps.logsSource;
461
+ this.contractDataSource = deps.contractDataSource;
462
+ this.l1ToL2MessageSource = deps.l1ToL2MessageSource;
463
+ this.worldStateSynchronizer = deps.worldStateSynchronizer;
464
+ this.sequencer = deps.sequencer;
465
+ this.proverNode = deps.proverNode;
466
+ this.slasherClient = deps.slasherClient;
467
+ this.validatorsSentinel = deps.validatorsSentinel;
468
+ this.stopStartedWatchers = deps.stopStartedWatchers;
469
+ this.l1ChainId = deps.l1ChainId;
470
+ this.version = deps.version;
471
+ this.globalVariableBuilder = deps.globalVariableBuilder;
472
+ this.rollupContract = deps.rollupContract;
473
+ this.feeProvider = deps.feeProvider;
474
+ this.epochCache = deps.epochCache;
475
+ this.packageVersion = deps.packageVersion;
476
+ this.peerProofVerifier = deps.peerProofVerifier;
477
+ this.rpcProofVerifier = deps.rpcProofVerifier;
478
+ this.telemetry = deps.telemetry ?? getTelemetryClient();
479
+ this.log = deps.log ?? createLogger('node');
480
+ this.blobClient = deps.blobClient;
481
+ this.validatorClient = deps.validatorClient;
482
+ this.keyStoreManager = deps.keyStoreManager;
483
+ this.debugLogStore = deps.debugLogStore ?? new NullDebugLogStore();
484
+ this.automineSequencer = deps.automineSequencer;
485
+ this.avmSimulator = deps.avmSimulator;
486
+ this.metrics = new NodeMetrics(this.telemetry, 'AztecNodeService');
487
+ this.tracer = this.telemetry.getTracer('AztecNodeService');
488
+ // The node never represents a proposer's payout addresses, so the simulator zeroes coinbase and
489
+ // fee recipient. The signature context only needs chain id + rollup address (see signature_utils).
490
+ this.nodePublicCallsSimulator = new NodePublicCallsSimulator({
491
+ blockSource: this.blockSource,
492
+ worldStateSynchronizer: this.worldStateSynchronizer,
493
+ l1ToL2MessageSource: this.l1ToL2MessageSource,
494
+ contractDataSource: this.contractDataSource,
495
+ globalVariableBuilder: this.globalVariableBuilder,
496
+ rollupContract: this.rollupContract,
497
+ epochCache: this.epochCache,
498
+ signatureContext: {
499
+ chainId: this.l1ChainId,
500
+ rollupAddress: this.config.rollupAddress
501
+ },
502
+ config: this.config,
503
+ avmSimulator: this.avmSimulator,
504
+ telemetry: this.telemetry,
505
+ log: this.log.createChild('public-calls-simulator')
506
+ });
507
+ this.worldStateQueries = new NodeWorldStateQueries({
508
+ worldStateSynchronizer: this.worldStateSynchronizer,
509
+ blockSource: this.blockSource,
510
+ l1ToL2MessageSource: this.l1ToL2MessageSource,
511
+ log: this.log.createChild('world-state-queries')
512
+ });
513
+ this.blockProvider = new NodeBlockProvider(this.blockSource);
514
+ this.txReceiptBuilder = new NodeTxReceiptBuilder({
515
+ p2pClient: this.p2pClient,
516
+ blockSource: this.blockSource,
517
+ debugLogStore: this.debugLogStore
518
+ });
494
519
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
495
- this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
496
- // A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
520
+ this.log.info(`Aztec Node started on chain 0x${this.l1ChainId.toString(16)}`, pickL1ContractAddresses(this.config));
521
+ // A defensive check that protects us against introducing a bug in the complex node creation flow. We must
497
522
  // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
498
523
  // memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
499
- if (debugLogStore.isEnabled && config.realProofs) {
524
+ if (this.debugLogStore.isEnabled && this.config.realProofs) {
500
525
  throw new Error('debugLogStore should never be enabled when realProofs are set');
501
526
  }
502
527
  }
528
+ /** @internal Exposed for testing — returns the RPC proof verifier. */ getProofVerifier() {
529
+ return this.rpcProofVerifier;
530
+ }
503
531
  async getWorldStateSyncStatus() {
504
532
  const status = await this.worldStateSynchronizer.status();
505
533
  return status.syncSummary;
506
534
  }
507
- getL2Tips() {
535
+ getChainTips() {
508
536
  return this.blockSource.getL2Tips();
509
537
  }
510
- /**
511
- * initializes the Aztec Node, wait for component to sync.
512
- * @param config - The configuration to be used by the aztec node.
513
- * @returns - A fully synced Aztec Node for use in development/testing.
514
- */ static async createAndSync(inputConfig, deps = {}, options = {}) {
515
- const config = {
516
- ...inputConfig
517
- }; // Copy the config so we dont mutate the input object
518
- const log = deps.logger ?? createLogger('node');
519
- const packageVersion = getPackageVersion() ?? '';
520
- const telemetry = deps.telemetry ?? getTelemetryClient();
521
- const dateProvider = deps.dateProvider ?? new DateProvider();
522
- const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
523
- // Build a key store from file if given or from environment otherwise.
524
- // We keep the raw KeyStore available so we can merge with prover keys if enableProverNode is set.
525
- let keyStoreManager;
526
- const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
527
- if (keyStoreProvided) {
528
- const keyStores = loadKeystores(config.keyStoreDirectory);
529
- keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
530
- } else {
531
- const rawKeyStores = [];
532
- const validatorKeyStore = createKeyStoreForValidator(config);
533
- if (validatorKeyStore) {
534
- rawKeyStores.push(validatorKeyStore);
535
- }
536
- if (config.enableProverNode) {
537
- const proverKeyStore = createKeyStoreForProver(config);
538
- if (proverKeyStore) {
539
- rawKeyStores.push(proverKeyStore);
540
- }
541
- }
542
- if (rawKeyStores.length > 0) {
543
- keyStoreManager = new KeystoreManager(rawKeyStores.length === 1 ? rawKeyStores[0] : mergeKeystores(rawKeyStores));
544
- }
545
- }
546
- await keyStoreManager?.validateSigners();
547
- // If we are a validator, verify our configuration before doing too much more.
548
- if (!config.disableValidator) {
549
- if (keyStoreManager === undefined) {
550
- throw new Error('Failed to create key store, a requirement for running a validator');
551
- }
552
- if (!keyStoreProvided && process.env.NODE_ENV !== 'test') {
553
- log.warn("Keystore created from env: it's recommended to use a file-based key store for production");
554
- }
555
- ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
556
- }
557
- // validate that the actual chain id matches that specified in configuration
558
- if (config.l1ChainId !== ethereumChain.chainInfo.id) {
559
- throw new Error(`RPC URL configured for chain id ${ethereumChain.chainInfo.id} but expected id ${config.l1ChainId}`);
560
- }
561
- const publicClient = createPublicClient({
562
- chain: ethereumChain.chainInfo,
563
- transport: fallback(config.l1RpcUrls.map((url)=>http(url, {
564
- batch: false
565
- }))),
566
- pollingInterval: config.viemPollingIntervalMS
567
- });
568
- const l1ContractsAddresses = await RegistryContract.collectAddresses(publicClient, config.l1Contracts.registryAddress, config.rollupVersion ?? 'canonical');
569
- // Overwrite the passed in vars.
570
- config.l1Contracts = {
571
- ...config.l1Contracts,
572
- ...l1ContractsAddresses
573
- };
574
- const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
575
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
576
- rollupContract.getL1GenesisTime(),
577
- rollupContract.getSlotDuration(),
578
- rollupContract.getVersion()
579
- ]);
580
- config.rollupVersion ??= Number(rollupVersionFromRollup);
581
- if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
582
- log.warn(`Registry looked up and returned a rollup with version (${config.rollupVersion}), but this does not match with version detected from the rollup directly: (${rollupVersionFromRollup}).`);
583
- }
584
- const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
585
- // attempt snapshot sync if possible
586
- await trySnapshotSync(config, log);
587
- const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, {
588
- dateProvider
589
- });
590
- const archiver = await createArchiver(config, {
591
- blobClient,
592
- epochCache,
593
- telemetry,
594
- dateProvider
595
- }, {
596
- blockUntilSync: !config.skipArchiverInitialSync
597
- });
598
- // now create the merkle trees and the world state synchronizer
599
- const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.prefilledPublicData, telemetry);
600
- const circuitVerifier = config.realProofs || config.debugForceTxProofVerification ? await BBCircuitVerifier.new(config) : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
601
- let debugLogStore;
602
- if (!config.realProofs) {
603
- log.warn(`Aztec node is accepting fake proofs`);
604
- debugLogStore = new InMemoryDebugLogStore();
605
- log.info('Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served');
606
- } else {
607
- debugLogStore = new NullDebugLogStore();
608
- }
609
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
610
- // create the tx pool and the p2p client, which will need the l2 block source
611
- const p2pClient = await createP2PClient(P2PClientType.Full, config, archiver, proofVerifier, worldStateSynchronizer, epochCache, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
612
- // We should really not be modifying the config object
613
- config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
614
- // Create FullNodeCheckpointsBuilder for validator and non-validator block proposal handling
615
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder({
616
- ...config,
617
- l1GenesisTime,
618
- slotDuration: Number(slotDuration)
619
- }, worldStateSynchronizer, archiver, dateProvider, telemetry);
620
- // We'll accumulate sentinel watchers here
621
- const watchers = [];
622
- // Create validator client if required
623
- const validatorClient = await createValidatorClient(config, {
624
- checkpointsBuilder: validatorCheckpointsBuilder,
625
- worldState: worldStateSynchronizer,
626
- p2pClient,
627
- telemetry,
628
- dateProvider,
629
- epochCache,
630
- blockSource: archiver,
631
- l1ToL2MessageSource: archiver,
632
- keyStoreManager,
633
- blobClient
634
- });
635
- // If we have a validator client, register it as a source of offenses for the slasher,
636
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
637
- // like attestations or auths will fail.
638
- if (validatorClient) {
639
- watchers.push(validatorClient);
640
- if (!options.dontStartSequencer) {
641
- await validatorClient.registerHandlers();
642
- }
643
- }
644
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
645
- // create a BlockProposalHandler to reexecute block proposals for monitoring
646
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
647
- log.info('Setting up block proposal reexecution for monitoring');
648
- createBlockProposalHandler(config, {
649
- checkpointsBuilder: validatorCheckpointsBuilder,
650
- worldState: worldStateSynchronizer,
651
- epochCache,
652
- blockSource: archiver,
653
- l1ToL2MessageSource: archiver,
654
- p2pClient,
655
- dateProvider,
656
- telemetry
657
- }).registerForReexecution(p2pClient);
658
- }
659
- // Start world state and wait for it to sync to the archiver.
660
- await worldStateSynchronizer.start();
661
- // Start p2p. Note that it depends on world state to be running.
662
- await p2pClient.start();
663
- const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
664
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
665
- watchers.push(validatorsSentinel);
666
- }
667
- let epochPruneWatcher;
668
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
669
- epochPruneWatcher = new EpochPruneWatcher(archiver, archiver, epochCache, p2pClient.getTxProvider(), validatorCheckpointsBuilder, config);
670
- watchers.push(epochPruneWatcher);
671
- }
672
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
673
- let attestationsBlockWatcher;
674
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
675
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
676
- watchers.push(attestationsBlockWatcher);
677
- }
678
- // Start p2p-related services once the archiver has completed sync
679
- void archiver.waitForInitialSync().then(async ()=>{
680
- await p2pClient.start();
681
- await validatorsSentinel?.start();
682
- await epochPruneWatcher?.start();
683
- await attestationsBlockWatcher?.start();
684
- log.info(`All p2p services started`);
685
- }).catch((err)=>log.error('Failed to start p2p services after archiver sync', err));
686
- // Validator enabled, create/start relevant service
687
- let sequencer;
688
- let slasherClient;
689
- if (!config.disableValidator && validatorClient) {
690
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
691
- // as they are executed when the node is selected as proposer.
692
- const validatorAddresses = keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses() : [];
693
- slasherClient = await createSlasher(config, config.l1Contracts, getPublicClient(config), watchers, dateProvider, epochCache, validatorAddresses, undefined);
694
- await slasherClient.start();
695
- const l1TxUtils = config.sequencerPublisherForwarderAddress ? await createForwarderL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), config.sequencerPublisherForwarderAddress, {
696
- ...config,
697
- scope: 'sequencer'
698
- }, {
699
- telemetry,
700
- logger: log.createChild('l1-tx-utils'),
701
- dateProvider,
702
- kzg: Blob.getViemKzgInstance()
703
- }) : await createL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
704
- ...config,
705
- scope: 'sequencer'
706
- }, {
707
- telemetry,
708
- logger: log.createChild('l1-tx-utils'),
709
- dateProvider,
710
- kzg: Blob.getViemKzgInstance()
711
- });
712
- // Create and start the sequencer client
713
- const checkpointsBuilder = new CheckpointsBuilder({
714
- ...config,
715
- l1GenesisTime,
716
- slotDuration: Number(slotDuration)
717
- }, worldStateSynchronizer, archiver, dateProvider, telemetry, debugLogStore);
718
- sequencer = await SequencerClient.new(config, {
719
- ...deps,
720
- epochCache,
721
- l1TxUtils,
722
- validatorClient,
723
- p2pClient,
724
- worldStateSynchronizer,
725
- slasherClient,
726
- checkpointsBuilder,
727
- l2BlockSource: archiver,
728
- l1ToL2MessageSource: archiver,
729
- telemetry,
730
- dateProvider,
731
- blobClient,
732
- nodeKeyStore: keyStoreManager
733
- });
734
- }
735
- if (!options.dontStartSequencer && sequencer) {
736
- await sequencer.start();
737
- log.verbose(`Sequencer started`);
738
- } else if (sequencer) {
739
- log.warn(`Sequencer created but not started`);
538
+ getL1Constants() {
539
+ return this.blockSource.getL1Constants();
540
+ }
541
+ getSyncedL2SlotNumber() {
542
+ return this.blockSource.getSyncedL2SlotNumber();
543
+ }
544
+ getSyncedL2EpochNumber() {
545
+ return this.blockSource.getSyncedL2EpochNumber();
546
+ }
547
+ getSyncedL1Timestamp() {
548
+ return this.blockSource.getL1Timestamp();
549
+ }
550
+ getCheckpointsData(query) {
551
+ return this.blockSource.getCheckpointsData(query);
552
+ }
553
+ async getBlockNumber(tip) {
554
+ if (tip === undefined || tip === 'proposed') {
555
+ return this.blockSource.getBlockNumber();
740
556
  }
741
- // Create prover node subsystem if enabled
742
- let proverNode;
743
- if (config.enableProverNode) {
744
- proverNode = await createProverNode(config, {
745
- ...deps.proverNodeDeps,
746
- telemetry,
747
- dateProvider,
748
- archiver,
749
- worldStateSynchronizer,
750
- p2pClient,
751
- epochCache,
752
- blobClient,
753
- keyStoreManager
754
- });
755
- if (!options.dontStartProverNode) {
756
- await proverNode.start();
757
- log.info(`Prover node subsystem started`);
758
- } else {
759
- log.info(`Prover node subsystem created but not started`);
760
- }
557
+ return await this.blockSource.getBlockNumber({
558
+ tag: tip
559
+ }) ?? BlockNumber.ZERO;
560
+ }
561
+ async getCheckpointNumber(tip) {
562
+ const tips = await this.blockSource.getL2Tips();
563
+ switch(tip){
564
+ case undefined:
565
+ case 'checkpointed':
566
+ return tips.checkpointed.checkpoint.number;
567
+ case 'proven':
568
+ return tips.proven.checkpoint.number;
569
+ case 'finalized':
570
+ return tips.finalized.checkpoint.number;
761
571
  }
762
- const globalVariableBuilder = new GlobalVariableBuilder({
763
- ...config,
764
- rollupVersion: BigInt(config.rollupVersion),
765
- l1GenesisTime,
766
- slotDuration: Number(slotDuration)
767
- });
768
- const node = new AztecNodeService(config, p2pClient, archiver, archiver, archiver, archiver, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, epochPruneWatcher, ethereumChain.chainInfo.id, config.rollupVersion, globalVariableBuilder, epochCache, packageVersion, proofVerifier, telemetry, log, blobClient, validatorClient, keyStoreManager, debugLogStore);
769
- return node;
572
+ }
573
+ getBlock(param, options = {}) {
574
+ return this.blockProvider.getBlock(param, options);
575
+ }
576
+ getBlockData(param) {
577
+ return this.blockProvider.getBlockData(param);
578
+ }
579
+ getBlocks(from, limit, options = {}) {
580
+ return this.blockProvider.getBlocks(from, limit, options);
581
+ }
582
+ getCheckpoint(param, options = {}) {
583
+ return this.blockProvider.getCheckpoint(param, options);
584
+ }
585
+ getCheckpoints(from, limit, options = {}) {
586
+ return this.blockProvider.getCheckpoints(from, limit, options);
770
587
  }
771
588
  /**
772
589
  * Returns the sequencer client instance.
@@ -774,6 +591,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
774
591
  */ getSequencer() {
775
592
  return this.sequencer;
776
593
  }
594
+ /** Test-only: returns the AutomineSequencer when wired via `useAutomineSequencer`. */ getAutomineSequencer() {
595
+ return this.automineSequencer;
596
+ }
777
597
  /** Returns the prover node subsystem, if enabled. */ getProverNode() {
778
598
  return this.proverNode;
779
599
  }
@@ -790,13 +610,16 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
790
610
  * Method to return the currently deployed L1 contract addresses.
791
611
  * @returns - The currently deployed L1 contract addresses.
792
612
  */ getL1ContractAddresses() {
793
- return Promise.resolve(this.config.l1Contracts);
613
+ return Promise.resolve(pickL1ContractAddresses(this.config));
794
614
  }
795
615
  getEncodedEnr() {
796
616
  return Promise.resolve(this.p2pClient.getEnr()?.encodeTxt());
797
617
  }
798
618
  async getAllowedPublicSetup() {
799
- return this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
619
+ return [
620
+ ...await getDefaultAllowedSetupFunctions(),
621
+ ...this.config.txPublicSetupAllowListExtend ?? []
622
+ ];
800
623
  }
801
624
  /**
802
625
  * Method to determine if the node is ready to accept transactions.
@@ -805,14 +628,20 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
805
628
  return Promise.resolve(this.p2pClient.isReady() ?? false);
806
629
  }
807
630
  async getNodeInfo() {
808
- const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses] = await Promise.all([
631
+ const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses, l1Constants] = await Promise.all([
809
632
  this.getNodeVersion(),
810
633
  this.getVersion(),
811
634
  this.getChainId(),
812
635
  this.getEncodedEnr(),
813
636
  this.getL1ContractAddresses(),
814
- this.getProtocolContractAddresses()
637
+ this.getProtocolContractAddresses(),
638
+ this.blockSource.getL1Constants()
815
639
  ]);
640
+ // Gas limits a single tx may declare on this network, derived from network-wide constants only (the
641
+ // timetable's blocks-per-checkpoint and the network-minimum per-block multipliers) — never this node's
642
+ // local caps or configured multipliers, which can make the node stricter at block-building time but
643
+ // cannot define what the network accepts for relay. Clients read txsLimits to set fallback gas limits.
644
+ const maxTxGas = getNetworkTxGasLimits(this.config, l1Constants);
816
645
  const nodeInfo = {
817
646
  nodeVersion,
818
647
  l1ChainId: chainId,
@@ -820,68 +649,26 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
820
649
  enr,
821
650
  l1ContractAddresses: contractAddresses,
822
651
  protocolContractAddresses: protocolContractAddresses,
823
- realProofs: !!this.config.realProofs
652
+ realProofs: !!this.config.realProofs,
653
+ txsLimits: {
654
+ gas: {
655
+ daGas: maxTxGas.daGas,
656
+ l2Gas: maxTxGas.l2Gas
657
+ }
658
+ }
824
659
  };
825
660
  return nodeInfo;
826
661
  }
827
- /**
828
- * Get a block specified by its block number, block hash, or 'latest'.
829
- * @param block - The block parameter (block number, block hash, or 'latest').
830
- * @returns The requested block.
831
- */ async getBlock(block) {
832
- if (BlockHash.isBlockHash(block)) {
833
- return this.getBlockByHash(block);
834
- }
835
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
836
- if (blockNumber === BlockNumber.ZERO) {
837
- return this.buildInitialBlock();
838
- }
839
- return await this.blockSource.getL2Block(blockNumber);
840
- }
841
- /**
842
- * Get a block specified by its hash.
843
- * @param blockHash - The block hash being requested.
844
- * @returns The requested block.
845
- */ async getBlockByHash(blockHash) {
846
- const initialBlockHash = await this.#getInitialHeaderHash();
847
- if (blockHash.equals(initialBlockHash)) {
848
- return this.buildInitialBlock();
849
- }
850
- return await this.blockSource.getL2BlockByHash(blockHash);
851
- }
852
- buildInitialBlock() {
853
- const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
854
- return L2Block.empty(initialHeader);
855
- }
856
- /**
857
- * Get a block specified by its archive root.
858
- * @param archive - The archive root being requested.
859
- * @returns The requested block.
860
- */ async getBlockByArchive(archive) {
861
- return await this.blockSource.getL2BlockByArchive(archive);
862
- }
863
- /**
864
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
865
- * @param from - The start of the range of blocks to return.
866
- * @param limit - The maximum number of blocks to obtain.
867
- * @returns The blocks requested.
868
- */ async getBlocks(from, limit) {
869
- return await this.blockSource.getBlocks(from, BlockNumber(limit)) ?? [];
870
- }
871
- async getCheckpoints(from, limit) {
872
- return await this.blockSource.getCheckpoints(from, limit) ?? [];
662
+ async getCurrentMinFees() {
663
+ return await this.feeProvider.getCurrentMinFees();
873
664
  }
874
- async getCheckpointedBlocks(from, limit) {
875
- return await this.blockSource.getCheckpointedBlocks(from, limit) ?? [];
876
- }
877
- /**
878
- * Method to fetch the current min L2 fees.
879
- * @returns The current min L2 fees.
880
- */ async getCurrentMinFees() {
881
- return await this.globalVariableBuilder.getCurrentMinFees();
665
+ /** Returns predicted min fees for the current slot and next N slots. */ async getPredictedMinFees(manaUsage) {
666
+ return await this.feeProvider.getPredictedMinFees(manaUsage);
882
667
  }
883
668
  async getMaxPriorityFees() {
884
- for await (const tx of this.p2pClient.iteratePendingTxs()){
669
+ for await (const tx of this.p2pClient.iteratePendingTxs({
670
+ includeProof: false
671
+ })){
885
672
  return tx.getGasSettings().maxPriorityFeesPerGas;
886
673
  }
887
674
  return GasFees.from({
@@ -890,18 +677,6 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
890
677
  });
891
678
  }
892
679
  /**
893
- * Method to fetch the latest block number synchronized by the node.
894
- * @returns The block number.
895
- */ async getBlockNumber() {
896
- return await this.blockSource.getBlockNumber();
897
- }
898
- async getProvenBlockNumber() {
899
- return await this.blockSource.getProvenBlockNumber();
900
- }
901
- async getCheckpointedBlockNumber() {
902
- return await this.blockSource.getCheckpointedL2BlockNumber();
903
- }
904
- /**
905
680
  * Method to fetch the version of the package.
906
681
  * @returns The node package version
907
682
  */ getNodeVersion() {
@@ -922,46 +697,18 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
922
697
  getContractClass(id) {
923
698
  return this.contractDataSource.getContractClass(id);
924
699
  }
925
- getContract(address) {
926
- return this.contractDataSource.getContract(address);
927
- }
928
- async getPrivateLogsByTags(tags, page, referenceBlock) {
929
- if (referenceBlock) {
930
- const initialBlockHash = await this.#getInitialHeaderHash();
931
- if (!referenceBlock.equals(initialBlockHash)) {
932
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
933
- if (!header) {
934
- throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
935
- }
936
- }
700
+ async getContract(address, referenceBlock = 'latest') {
701
+ const blockData = await this.getBlockData(referenceBlock);
702
+ if (!blockData) {
703
+ 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.`);
937
704
  }
938
- return this.logsSource.getPrivateLogsByTags(tags, page);
939
- }
940
- async getPublicLogsByTagsFromContract(contractAddress, tags, page, referenceBlock) {
941
- if (referenceBlock) {
942
- const initialBlockHash = await this.#getInitialHeaderHash();
943
- if (!referenceBlock.equals(initialBlockHash)) {
944
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
945
- if (!header) {
946
- throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
947
- }
948
- }
949
- }
950
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
705
+ return this.contractDataSource.getContract(address, blockData.header.globalVariables.timestamp);
951
706
  }
952
- /**
953
- * Gets public logs based on the provided filter.
954
- * @param filter - The filter to apply to the logs.
955
- * @returns The requested logs.
956
- */ getPublicLogs(filter) {
957
- return this.logsSource.getPublicLogs(filter);
707
+ getPrivateLogsByTags(query) {
708
+ return this.logsSource.getPrivateLogsByTags(query);
958
709
  }
959
- /**
960
- * Gets contract class logs based on the provided filter.
961
- * @param filter - The filter to apply to the logs.
962
- * @returns The requested logs.
963
- */ getContractClassLogs(filter) {
964
- return this.logsSource.getContractClassLogs(filter);
710
+ getPublicLogsByTags(query) {
711
+ return this.logsSource.getPublicLogsByTags(query);
965
712
  }
966
713
  /**
967
714
  * Method to submit a transaction to the p2p pool.
@@ -981,33 +728,23 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
981
728
  });
982
729
  throw new Error(`Invalid tx: ${reason}`);
983
730
  }
984
- await this.p2pClient.sendTx(tx);
985
- this.metrics.receivedTx(timer.ms(), true);
986
- this.log.info(`Received tx ${txHash}`, {
731
+ try {
732
+ await this.p2pClient.sendTx(tx);
733
+ } catch (err) {
734
+ this.metrics.receivedTx(timer.ms(), false);
735
+ this.log.warn(`Mempool rejected tx ${txHash}: ${err.message}`, {
736
+ txHash
737
+ });
738
+ throw err;
739
+ }
740
+ const duration = timer.ms();
741
+ this.metrics.receivedTx(duration, true);
742
+ this.log.info(`Received tx ${txHash} in ${duration}ms`, {
987
743
  txHash
988
744
  });
989
745
  }
990
- async getTxReceipt(txHash) {
991
- // Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
992
- // as a fallback if we don't find a settled receipt in the archiver.
993
- const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
994
- const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
995
- // Then get the actual tx from the archiver, which tracks every tx in a mined block.
996
- const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
997
- let receipt;
998
- if (settledTxReceipt) {
999
- receipt = settledTxReceipt;
1000
- } else if (isKnownToPool) {
1001
- // If the tx is in the pool but not in the archiver, it's pending.
1002
- // This handles race conditions between archiver and p2p, where the archiver
1003
- // has pruned the block in which a tx was mined, but p2p has not caught up yet.
1004
- receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
1005
- } else {
1006
- // Otherwise, if we don't know the tx, we consider it dropped.
1007
- receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
1008
- }
1009
- this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
1010
- return receipt;
746
+ getTxReceipt(txHash, options) {
747
+ return this.txReceiptBuilder.getTxReceipt(txHash, options);
1011
748
  }
1012
749
  getTxEffect(txHash) {
1013
750
  return this.blockSource.getTxEffect(txHash);
@@ -1016,13 +753,20 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1016
753
  * Method to stop the aztec node.
1017
754
  */ async stop() {
1018
755
  this.log.info(`Stopping Aztec Node`);
1019
- await tryStop(this.validatorsSentinel);
1020
- await tryStop(this.epochPruneWatcher);
756
+ await this.stopStartedWatchers();
1021
757
  await tryStop(this.slasherClient);
1022
- await tryStop(this.proofVerifier);
758
+ await Promise.all([
759
+ tryStop(this.peerProofVerifier),
760
+ tryStop(this.rpcProofVerifier)
761
+ ]);
1023
762
  await tryStop(this.sequencer);
763
+ await tryStop(this.automineSequencer);
1024
764
  await tryStop(this.proverNode);
1025
765
  await tryStop(this.p2pClient);
766
+ // Dispose the AVM backend before world state: it kills the bb-avm-sim processes and closes the CDB IPC
767
+ // server, releasing their connections to the WSDB so it shuts down cleanly (and freeing the
768
+ // Server/Socket/ChildProcess handles that would otherwise keep the process alive after teardown).
769
+ await this.avmSimulator?.[Symbol.asyncDispose]();
1026
770
  await tryStop(this.worldStateSynchronizer);
1027
771
  await tryStop(this.blockSource);
1028
772
  await tryStop(this.blobClient);
@@ -1040,302 +784,120 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1040
784
  * @param limit - The number of items to returns
1041
785
  * @param after - The last known pending tx. Used for pagination
1042
786
  * @returns - The pending txs.
1043
- */ getPendingTxs(limit, after) {
1044
- return this.p2pClient.getPendingTxs(limit, after);
787
+ */ getPendingTxs(limit, after, options) {
788
+ return this.p2pClient.getPendingTxs(limit, after, options);
1045
789
  }
1046
790
  getPendingTxCount() {
1047
791
  return this.p2pClient.getPendingTxCount();
1048
792
  }
793
+ getPeers(includePending) {
794
+ return this.p2pClient.getPeers(includePending);
795
+ }
796
+ getCheckpointAttestationsForSlot(slot, proposalPayloadHash) {
797
+ return this.p2pClient.getCheckpointAttestationsForSlot(slot, proposalPayloadHash);
798
+ }
799
+ getProposalsForSlot(slot) {
800
+ return this.p2pClient.getProposalsForSlot(slot);
801
+ }
1049
802
  /**
1050
- * Method to retrieve a single tx from the mempool or unfinalized chain.
803
+ * Method to retrieve a single tx from the mempool or unfinalized chain. The tx's proof is only loaded and returned
804
+ * when `includeProof` is set.
1051
805
  * @param txHash - The transaction hash to return.
806
+ * @param options - Options for the returned tx (eg whether to include its proof).
1052
807
  * @returns - The tx if it exists.
1053
- */ getTxByHash(txHash) {
1054
- return Promise.resolve(this.p2pClient.getTxByHashFromPool(txHash));
808
+ */ getTxByHash(txHash, options) {
809
+ return this.p2pClient.getTxByHashFromPool(txHash, {
810
+ includeProof: !!options?.includeProof
811
+ });
1055
812
  }
1056
813
  /**
1057
- * Method to retrieve txs from the mempool or unfinalized chain.
814
+ * Method to retrieve txs from the mempool or unfinalized chain. The txs' proofs are only loaded and returned when
815
+ * `includeProof` is set.
1058
816
  * @param txHash - The transaction hash to return.
817
+ * @param options - Options for the returned txs (eg whether to include their proofs).
1059
818
  * @returns - The txs if it exists.
1060
- */ async getTxsByHash(txHashes) {
1061
- return compactArray(await Promise.all(txHashes.map((txHash)=>this.getTxByHash(txHash))));
1062
- }
1063
- async findLeavesIndexes(referenceBlock, treeId, leafValues) {
1064
- const committedDb = await this.#getWorldState(referenceBlock);
1065
- const maybeIndices = await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
1066
- // We filter out undefined values
1067
- const indices = maybeIndices.filter((x)=>x !== undefined);
1068
- // Now we find the block numbers for the indices
1069
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
1070
- // If any of the block numbers are undefined, we throw an error.
1071
- for(let i = 0; i < indices.length; i++){
1072
- if (blockNumbers[i] === undefined) {
1073
- throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
1074
- }
1075
- }
1076
- // Get unique block numbers in order to optimize num calls to getLeafValue function.
1077
- const uniqueBlockNumbers = [
1078
- ...new Set(blockNumbers.filter((x)=>x !== undefined))
1079
- ];
1080
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
1081
- // (note that block number corresponds to the leaf index in the archive tree).
1082
- const blockHashes = await Promise.all(uniqueBlockNumbers.map((blockNumber)=>{
1083
- return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1084
- }));
1085
- // If any of the block hashes are undefined, we throw an error.
1086
- for(let i = 0; i < uniqueBlockNumbers.length; i++){
1087
- if (blockHashes[i] === undefined) {
1088
- throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
1089
- }
1090
- }
1091
- // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
1092
- return maybeIndices.map((index, i)=>{
1093
- if (index === undefined) {
1094
- return undefined;
1095
- }
1096
- const blockNumber = blockNumbers[i];
1097
- if (blockNumber === undefined) {
1098
- return undefined;
1099
- }
1100
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
1101
- const blockHash = blockHashes[blockHashIndex];
1102
- if (!blockHash) {
1103
- return undefined;
1104
- }
1105
- return {
1106
- l2BlockNumber: BlockNumber(Number(blockNumber)),
1107
- l2BlockHash: new BlockHash(blockHash),
1108
- data: index
1109
- };
819
+ */ async getTxsByHash(txHashes, options) {
820
+ const txs = await this.p2pClient.getTxsByHashFromPool(txHashes, {
821
+ includeProof: !!options?.includeProof
1110
822
  });
823
+ return compactArray(txs);
1111
824
  }
1112
- async getBlockHashMembershipWitness(referenceBlock, blockHash) {
1113
- const committedDb = await this.#getWorldState(referenceBlock);
1114
- const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE, [
1115
- blockHash
1116
- ]);
1117
- return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
825
+ findLeavesIndexes(referenceBlock, treeId, leafValues) {
826
+ return this.worldStateQueries.findLeavesIndexes(referenceBlock, treeId, leafValues);
1118
827
  }
1119
- async getNoteHashMembershipWitness(referenceBlock, noteHash) {
1120
- const committedDb = await this.#getWorldState(referenceBlock);
1121
- const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE, [
1122
- noteHash
1123
- ]);
1124
- return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
828
+ getBlockHashMembershipWitness(referenceBlock, blockHash) {
829
+ return this.worldStateQueries.getBlockHashMembershipWitness(referenceBlock, blockHash);
1125
830
  }
1126
- async getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
1127
- const db = await this.#getWorldState(referenceBlock);
1128
- const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
1129
- l1ToL2Message
1130
- ]);
1131
- if (!witness) {
1132
- return undefined;
1133
- }
1134
- // REFACTOR: Return a MembershipWitness object
1135
- return [
1136
- witness.index,
1137
- witness.path
1138
- ];
831
+ getNoteHashMembershipWitness(referenceBlock, noteHash) {
832
+ return this.worldStateQueries.getNoteHashMembershipWitness(referenceBlock, noteHash);
1139
833
  }
1140
- async getL1ToL2MessageBlock(l1ToL2Message) {
1141
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1142
- return messageIndex ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex)) : undefined;
834
+ getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
835
+ return this.worldStateQueries.getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message);
1143
836
  }
1144
- /**
1145
- * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
1146
- * @param l1ToL2Message - The L1 to L2 message to check.
1147
- * @returns Whether the message is synced and ready to be included in a block.
1148
- */ async isL1ToL2MessageSynced(l1ToL2Message) {
1149
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1150
- return messageIndex !== undefined;
837
+ getL1ToL2MessageCheckpoint(l1ToL2Message) {
838
+ return this.worldStateQueries.getL1ToL2MessageCheckpoint(l1ToL2Message);
1151
839
  }
1152
840
  /**
1153
841
  * Returns all the L2 to L1 messages in an epoch.
842
+ *
843
+ * @deprecated Use {@link getL2ToL1MembershipWitness} to get an L2-to-L1 message witness directly.
844
+ *
1154
845
  * @param epoch - The epoch at which to get the data.
1155
846
  * @returns The L2 to L1 messages (empty array if the epoch is not found).
1156
- */ async getL2ToL1Messages(epoch) {
1157
- // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1158
- const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1159
- const blocksInCheckpoints = [];
1160
- let previousSlotNumber = SlotNumber.ZERO;
1161
- let checkpointIndex = -1;
1162
- for (const checkpointedBlock of checkpointedBlocks){
1163
- const block = checkpointedBlock.block;
1164
- const slotNumber = block.header.globalVariables.slotNumber;
1165
- if (slotNumber !== previousSlotNumber) {
1166
- checkpointIndex++;
1167
- blocksInCheckpoints.push([]);
1168
- previousSlotNumber = slotNumber;
1169
- }
1170
- blocksInCheckpoints[checkpointIndex].push(block);
1171
- }
1172
- return blocksInCheckpoints.map((blocks)=>blocks.map((block)=>block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs)));
1173
- }
1174
- async getNullifierMembershipWitness(referenceBlock, nullifier) {
1175
- const db = await this.#getWorldState(referenceBlock);
1176
- const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [
1177
- nullifier.toBuffer()
1178
- ]);
1179
- if (!witness) {
1180
- return undefined;
1181
- }
1182
- const { index, path } = witness;
1183
- const leafPreimage = await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1184
- if (!leafPreimage) {
1185
- return undefined;
1186
- }
1187
- return new NullifierMembershipWitness(index, leafPreimage, path);
847
+ */ getL2ToL1Messages(epoch) {
848
+ return this.worldStateQueries.getL2ToL1Messages(epoch);
1188
849
  }
1189
850
  /**
1190
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1191
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1192
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1193
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1194
- * @returns The low nullifier membership witness (if found).
1195
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1196
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1197
- * we are trying to prove non-inclusion for.
1198
- *
1199
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1200
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1201
- * index of the nullifier itself when it already exists in the tree.
1202
- * TODO: This is a confusing behavior and we should eventually address that.
1203
- */ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1204
- const committedDb = await this.#getWorldState(referenceBlock);
1205
- const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1206
- if (!findResult) {
1207
- return undefined;
1208
- }
1209
- const { index, alreadyPresent } = findResult;
1210
- if (alreadyPresent) {
1211
- this.log.warn(`Nullifier ${nullifier.toBigInt()} already exists in the tree`);
1212
- }
1213
- const preimageData = await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1214
- const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1215
- return new NullifierMembershipWitness(BigInt(index), preimageData, siblingPath);
1216
- }
1217
- async getPublicDataWitness(referenceBlock, leafSlot) {
1218
- const committedDb = await this.#getWorldState(referenceBlock);
1219
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1220
- if (!lowLeafResult) {
1221
- return undefined;
1222
- } else {
1223
- const preimage = await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1224
- const path = await committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1225
- return new PublicDataWitness(lowLeafResult.index, preimage, path);
1226
- }
851
+ * Returns the L2-to-L1 membership witness for a message in `txHash`. Passthrough to the
852
+ * archiver's locally-cached resolver — see {@link Archiver.getL2ToL1MembershipWitness}.
853
+ */ getL2ToL1MembershipWitness(txHash, message, messageIndexInTx) {
854
+ return this.worldStateQueries.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
1227
855
  }
1228
- async getPublicStorageAt(referenceBlock, contract, slot) {
1229
- const committedDb = await this.#getWorldState(referenceBlock);
1230
- const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1231
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1232
- if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
1233
- return Fr.ZERO;
1234
- }
1235
- const preimage = await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1236
- return preimage.leaf.value;
1237
- }
1238
- async getBlockHeader(block = 'latest') {
1239
- if (BlockHash.isBlockHash(block)) {
1240
- const initialBlockHash = await this.#getInitialHeaderHash();
1241
- if (block.equals(initialBlockHash)) {
1242
- // Block source doesn't handle initial header so we need to handle the case separately.
1243
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1244
- }
1245
- return this.blockSource.getBlockHeaderByHash(block);
1246
- } else {
1247
- // Block source doesn't handle initial header so we need to handle the case separately.
1248
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
1249
- if (blockNumber === BlockNumber.ZERO) {
1250
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1251
- }
1252
- return this.blockSource.getBlockHeader(block);
1253
- }
856
+ getNullifierMembershipWitness(referenceBlock, nullifier) {
857
+ return this.worldStateQueries.getNullifierMembershipWitness(referenceBlock, nullifier);
1254
858
  }
1255
- /**
1256
- * Get a block header specified by its archive root.
1257
- * @param archive - The archive root being requested.
1258
- * @returns The requested block header.
1259
- */ async getBlockHeaderByArchive(archive) {
1260
- return await this.blockSource.getBlockHeaderByArchive(archive);
859
+ getLowNullifierMembershipWitness(referenceBlock, nullifier) {
860
+ return this.worldStateQueries.getLowNullifierMembershipWitness(referenceBlock, nullifier);
1261
861
  }
1262
- getBlockData(number) {
1263
- return this.blockSource.getBlockData(number);
862
+ getPublicDataWitness(referenceBlock, leafSlot) {
863
+ return this.worldStateQueries.getPublicDataWitness(referenceBlock, leafSlot);
1264
864
  }
1265
- getBlockDataByArchive(archive) {
1266
- return this.blockSource.getBlockDataByArchive(archive);
865
+ getPublicStorageAt(referenceBlock, contract, slot) {
866
+ return this.worldStateQueries.getPublicStorageAt(referenceBlock, contract, slot);
1267
867
  }
1268
868
  /**
1269
869
  * Simulates the public part of a transaction with the current state.
1270
870
  * @param tx - The transaction to simulate.
1271
- **/ async simulatePublicCalls(tx, skipFeeEnforcement = false) {
1272
- // Check total gas limit for simulation
1273
- const gasSettings = tx.data.constants.txContext.gasSettings;
1274
- const txGasLimit = gasSettings.gasLimits.l2Gas;
1275
- const teardownGasLimit = gasSettings.teardownGasLimits.l2Gas;
1276
- if (txGasLimit + teardownGasLimit > this.config.rpcSimulatePublicMaxGasLimit) {
1277
- throw new BadRequestError(`Transaction total gas limit ${txGasLimit + teardownGasLimit} (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${this.config.rpcSimulatePublicMaxGasLimit} for simulation`);
1278
- }
1279
- const txHash = tx.getTxHash();
1280
- const latestBlockNumber = await this.blockSource.getBlockNumber();
1281
- const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1282
- // If sequencer is not initialized, we just set these values to zero for simulation.
1283
- const coinbase = EthAddress.ZERO;
1284
- const feeRecipient = AztecAddress.ZERO;
1285
- const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(blockNumber, coinbase, feeRecipient);
1286
- const publicProcessorFactory = new PublicProcessorFactory(this.contractDataSource, new DateProvider(), this.telemetry, this.log.getBindings());
1287
- this.log.verbose(`Simulating public calls for tx ${txHash}`, {
1288
- globalVariables: newGlobalVariables.toInspect(),
1289
- txHash,
1290
- blockNumber
1291
- });
1292
- // Ensure world-state has caught up with the latest block we loaded from the archiver
1293
- await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1294
- const merkleTreeFork = await this.worldStateSynchronizer.fork();
1295
- try {
1296
- const config = PublicSimulatorConfig.from({
1297
- skipFeeEnforcement,
1298
- collectDebugLogs: true,
1299
- collectHints: false,
1300
- collectCallMetadata: true,
1301
- collectStatistics: false,
1302
- collectionLimits: CollectionLimitsConfig.from({
1303
- maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads
1304
- })
1305
- });
1306
- const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1307
- // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1308
- const [processedTxs, failedTxs, _usedTxs, returns, _blobFields, debugLogs] = await processor.process([
1309
- tx
1310
- ]);
1311
- // REFACTOR: Consider returning the error rather than throwing
1312
- if (failedTxs.length) {
1313
- this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, {
1314
- txHash
1315
- });
1316
- throw failedTxs[0].error;
1317
- }
1318
- const [processedTx] = processedTxs;
1319
- return new PublicSimulationOutput(processedTx.revertReason, processedTx.globalVariables, processedTx.txEffect, returns, processedTx.gasUsed, debugLogs);
1320
- } finally{
1321
- await merkleTreeFork.close();
1322
- }
871
+ * @param skipFeeEnforcement - If true, fee enforcement is skipped.
872
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
873
+ **/ simulatePublicCalls(tx, skipFeeEnforcement = false, overrides) {
874
+ return this.nodePublicCallsSimulator.simulate(tx, skipFeeEnforcement, overrides);
1323
875
  }
1324
876
  async isValidTx(tx, { isSimulation, skipFeeEnforcement } = {}) {
1325
877
  const db = this.worldStateSynchronizer.getCommitted();
1326
- const verifier = isSimulation ? undefined : this.proofVerifier;
878
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1327
879
  // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1328
880
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1329
881
  const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
882
+ const l1Constants = await this.blockSource.getL1Constants();
883
+ // Enforce the same network admission limit the node advertises in getNodeInfo (network-wide, not this
884
+ // node's local caps), so a tx the wallet sized against txsLimits is not rejected here.
885
+ const networkTxGasLimits = getNetworkTxGasLimits(this.config, l1Constants);
1330
886
  const validator = createTxValidatorForAcceptingTxsOverRPC(db, this.contractDataSource, verifier, {
1331
887
  timestamp: nextSlotTimestamp,
1332
888
  blockNumber,
1333
889
  l1ChainId: this.l1ChainId,
1334
890
  rollupVersion: this.version,
1335
- setupAllowList: this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions(),
891
+ setupAllowList: [
892
+ ...await getDefaultAllowedSetupFunctions(),
893
+ ...this.config.txPublicSetupAllowListExtend ?? []
894
+ ],
1336
895
  gasFees: await this.getCurrentMinFees(),
1337
896
  skipFeeEnforcement,
1338
- txsPermitted: !this.config.disableTransactions
897
+ isSimulation,
898
+ txsPermitted: !this.config.disableTransactions,
899
+ maxTxL2Gas: networkTxGasLimits.l2Gas,
900
+ maxTxDAGas: networkTxGasLimits.daGas
1339
901
  }, this.log.getBindings());
1340
902
  return await validator.validateTx(tx);
1341
903
  }
@@ -1349,7 +911,20 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1349
911
  ...this.config,
1350
912
  ...config
1351
913
  };
1352
- this.sequencer?.updateConfig(config);
914
+ // If the sequencer is currently paused via pauseSequencer(), record the caller's desired
915
+ // minTxsPerBlock as the restore value (so resumeSequencer applies it) and keep the freeze
916
+ // (MAX_SAFE_INTEGER) applied to the underlying sequencer. Without this guard, forwarding
917
+ // the new minTxsPerBlock to the sequencer would silently unpause block production while
918
+ // pauseSequencer() still considers it paused.
919
+ const sequencerUpdate = {
920
+ ...config
921
+ };
922
+ if (this.sequencerPausedMinTxsPerBlock !== undefined && sequencerUpdate.minTxsPerBlock !== undefined) {
923
+ this.sequencerPausedMinTxsPerBlock = sequencerUpdate.minTxsPerBlock;
924
+ delete sequencerUpdate.minTxsPerBlock;
925
+ }
926
+ this.sequencer?.updateConfig(sequencerUpdate);
927
+ this.automineSequencer?.updateConfig(sequencerUpdate);
1353
928
  this.slasherClient?.updateConfig(config);
1354
929
  this.validatorsSentinel?.updateConfig(config);
1355
930
  await this.p2pClient.updateP2PConfig(config);
@@ -1358,7 +933,18 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1358
933
  archiver.updateConfig(config);
1359
934
  }
1360
935
  if (newConfig.realProofs !== this.config.realProofs) {
1361
- this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
936
+ await Promise.all([
937
+ tryStop(this.peerProofVerifier),
938
+ tryStop(this.rpcProofVerifier)
939
+ ]);
940
+ if (newConfig.realProofs) {
941
+ this.peerProofVerifier = await BatchChonkVerifier.new(newConfig, newConfig.bbChonkVerifyMaxBatch, 'peer');
942
+ const rpcVerifier = await BBCircuitVerifier.new(newConfig);
943
+ this.rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, newConfig.numConcurrentIVCVerifiers);
944
+ } else {
945
+ this.peerProofVerifier = new TestCircuitVerifier();
946
+ this.rpcProofVerifier = new TestCircuitVerifier();
947
+ }
1362
948
  }
1363
949
  this.config = newConfig;
1364
950
  }
@@ -1367,7 +953,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1367
953
  classRegistry: ProtocolContractAddress.ContractClassRegistry,
1368
954
  feeJuice: ProtocolContractAddress.FeeJuice,
1369
955
  instanceRegistry: ProtocolContractAddress.ContractInstanceRegistry,
1370
- multiCallEntrypoint: ProtocolContractAddress.MultiCallEntrypoint
956
+ multiCallEntrypoint: STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS
1371
957
  });
1372
958
  }
1373
959
  registerContractFunctionSignatures(signatures) {
@@ -1418,7 +1004,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1418
1004
  });
1419
1005
  return Promise.resolve();
1420
1006
  }
1421
- async rollbackTo(targetBlock, force) {
1007
+ async rollbackTo(targetBlock, force, resumeSync = true) {
1422
1008
  const archiver = this.blockSource;
1423
1009
  if (!('rollbackTo' in archiver)) {
1424
1010
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1446,9 +1032,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1446
1032
  this.log.error(`Error during rollback`, err);
1447
1033
  throw err;
1448
1034
  } finally{
1449
- this.log.info(`Resuming world state and archiver sync.`);
1450
- this.worldStateSynchronizer.resumeSync();
1451
- archiver.resume();
1035
+ if (resumeSync) {
1036
+ this.log.info(`Resuming world state and archiver sync.`);
1037
+ this.worldStateSynchronizer.resumeSync();
1038
+ archiver.resume();
1039
+ } else {
1040
+ this.log.info(`Sync left paused after rollback (resumeSync=false).`);
1041
+ }
1452
1042
  }
1453
1043
  }
1454
1044
  async pauseSync() {
@@ -1462,18 +1052,51 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1462
1052
  this.blockSource.resume();
1463
1053
  return Promise.resolve();
1464
1054
  }
1465
- getSlashPayloads() {
1466
- if (!this.slasherClient) {
1467
- throw new Error(`Slasher client not enabled`);
1055
+ pauseSequencer() {
1056
+ if (this.automineSequencer) {
1057
+ this.automineSequencer.pause();
1058
+ return Promise.resolve();
1468
1059
  }
1469
- return this.slasherClient.getSlashPayloads();
1060
+ if (this.sequencer) {
1061
+ if (this.sequencerPausedMinTxsPerBlock === undefined) {
1062
+ this.sequencerPausedMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock ?? 0;
1063
+ this.sequencer.updateConfig({
1064
+ minTxsPerBlock: Number.MAX_SAFE_INTEGER
1065
+ });
1066
+ this.log.info(`Sequencer paused (minTxsPerBlock set to MAX_SAFE_INTEGER)`, {
1067
+ previousMinTxsPerBlock: this.sequencerPausedMinTxsPerBlock
1068
+ });
1069
+ }
1070
+ return Promise.resolve();
1071
+ }
1072
+ throw new BadRequestError('Cannot pause sequencer: no sequencer is running');
1073
+ }
1074
+ resumeSequencer() {
1075
+ if (this.automineSequencer) {
1076
+ this.automineSequencer.resume();
1077
+ return Promise.resolve();
1078
+ }
1079
+ if (this.sequencer) {
1080
+ if (this.sequencerPausedMinTxsPerBlock !== undefined) {
1081
+ const restored = this.sequencerPausedMinTxsPerBlock;
1082
+ this.sequencerPausedMinTxsPerBlock = undefined;
1083
+ this.sequencer.updateConfig({
1084
+ minTxsPerBlock: restored
1085
+ });
1086
+ this.log.info(`Sequencer resumed (minTxsPerBlock restored)`, {
1087
+ minTxsPerBlock: restored
1088
+ });
1089
+ }
1090
+ return Promise.resolve();
1091
+ }
1092
+ throw new BadRequestError('Cannot resume sequencer: no sequencer is running');
1470
1093
  }
1471
1094
  getSlashOffenses(round) {
1472
1095
  if (!this.slasherClient) {
1473
1096
  throw new Error(`Slasher client not enabled`);
1474
1097
  }
1475
1098
  if (round === 'all') {
1476
- return this.slasherClient.getPendingOffenses();
1099
+ return this.slasherClient.getOffenses();
1477
1100
  } else {
1478
1101
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1479
1102
  }
@@ -1545,57 +1168,60 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1545
1168
  this.keyStoreManager = newManager;
1546
1169
  this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1547
1170
  }
1548
- #getInitialHeaderHash() {
1549
- if (!this.initialHeaderHashPromise) {
1550
- this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
1551
- }
1552
- return this.initialHeaderHashPromise;
1553
- }
1554
- /**
1555
- * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1556
- * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1557
- * @returns An instance of a committed MerkleTreeOperations
1558
- */ async #getWorldState(block) {
1559
- let blockSyncedTo = BlockNumber.ZERO;
1171
+ async mineBlock() {
1172
+ if (this.automineSequencer) {
1173
+ await this.automineSequencer.buildEmptyBlock();
1174
+ return;
1175
+ }
1176
+ if (!this.sequencer) {
1177
+ throw new BadRequestError('Cannot mine block: no sequencer is running');
1178
+ }
1179
+ const currentBlockNumber = await this.getBlockNumber();
1180
+ // Use slot duration + 50% buffer as the timeout so this works on running networks too
1181
+ const { slotDuration } = await this.blockSource.getL1Constants();
1182
+ const timeoutSeconds = Math.ceil(slotDuration * 1.5);
1183
+ // Temporarily set minTxsPerBlock to 0 so the sequencer produces a block even with no txs
1184
+ const originalMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock;
1185
+ this.sequencer.updateConfig({
1186
+ minTxsPerBlock: 0
1187
+ });
1560
1188
  try {
1561
- // Attempt to sync the world state if necessary
1562
- blockSyncedTo = await this.#syncWorldState();
1563
- } catch (err) {
1564
- this.log.error(`Error getting world state: ${err}`);
1189
+ // Trigger the sequencer to produce a block immediately
1190
+ void this.sequencer.trigger();
1191
+ // Wait for the new L2 block to appear
1192
+ await retryUntil(async ()=>{
1193
+ const newBlockNumber = await this.getBlockNumber();
1194
+ return newBlockNumber > currentBlockNumber ? true : undefined;
1195
+ }, 'mineBlock', timeoutSeconds, 0.1);
1196
+ } finally{
1197
+ this.sequencer.updateConfig({
1198
+ minTxsPerBlock: originalMinTxsPerBlock
1199
+ });
1565
1200
  }
1566
- if (block === 'latest') {
1567
- this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
1568
- return this.worldStateSynchronizer.getCommitted();
1201
+ }
1202
+ async prove(upToCheckpoint) {
1203
+ if (!this.automineSequencer) {
1204
+ throw new BadRequestError('Cannot prove checkpoint: no automine sequencer is running');
1569
1205
  }
1570
- if (BlockHash.isBlockHash(block)) {
1571
- const initialBlockHash = await this.#getInitialHeaderHash();
1572
- if (block.equals(initialBlockHash)) {
1573
- // Block source doesn't handle initial header so we need to handle the case separately.
1574
- return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1575
- }
1576
- const header = await this.blockSource.getBlockHeaderByHash(block);
1577
- if (!header) {
1578
- 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.`);
1579
- }
1580
- const blockNumber = header.getBlockNumber();
1581
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1582
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1206
+ return await this.automineSequencer.prove(upToCheckpoint);
1207
+ }
1208
+ async warpL2TimeAtLeastTo(targetTimestamp) {
1209
+ if (!this.automineSequencer) {
1210
+ throw new BadRequestError('Cannot warp L2 time: no automine sequencer is running');
1583
1211
  }
1584
- // Block number provided
1585
- {
1586
- const blockNumber = block;
1587
- if (blockNumber > blockSyncedTo) {
1588
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1589
- }
1590
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1591
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1212
+ await this.automineSequencer.warpTo(targetTimestamp);
1213
+ }
1214
+ async warpL2TimeAtLeastBy(duration) {
1215
+ if (!this.automineSequencer) {
1216
+ throw new BadRequestError('Cannot warp L2 time: no automine sequencer is running');
1592
1217
  }
1218
+ await this.automineSequencer.warpBy(duration);
1593
1219
  }
1594
1220
  /**
1595
- * Ensure we fully sync the world state
1596
- * @returns A promise that fulfils once the world state is synced
1597
- */ async #syncWorldState() {
1598
- const blockSourceHeight = await this.blockSource.getBlockNumber();
1599
- return await this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
1221
+ * Returns a committed world-state view at `block`, driving sync first. Delegates to
1222
+ * {@link NodeWorldStateQueries.getWorldState}; kept as a protected method so subclasses and tests can
1223
+ * exercise the node's block-resolution and reorg-aware sync behavior.
1224
+ */ getWorldState(block) {
1225
+ return this.worldStateQueries.getWorldState(block);
1600
1226
  }
1601
1227
  }