@aztec/aztec-node 0.0.1-commit.f504929 → 0.0.1-commit.f5a9928

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