@aztec/aztec-node 0.0.1-commit.993d240 → 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 (52) hide show
  1. package/dest/aztec-node/config.d.ts +10 -1
  2. package/dest/aztec-node/config.d.ts.map +1 -1
  3. package/dest/aztec-node/config.js +10 -0
  4. package/dest/aztec-node/node_public_calls_simulator.d.ts +97 -0
  5. package/dest/aztec-node/node_public_calls_simulator.d.ts.map +1 -0
  6. package/dest/aztec-node/node_public_calls_simulator.js +351 -0
  7. package/dest/aztec-node/register_node_rpc_handlers.d.ts +10 -0
  8. package/dest/aztec-node/register_node_rpc_handlers.d.ts.map +1 -0
  9. package/dest/aztec-node/register_node_rpc_handlers.js +31 -0
  10. package/dest/aztec-node/server.d.ts +102 -66
  11. package/dest/aztec-node/server.d.ts.map +1 -1
  12. package/dest/aztec-node/server.js +237 -1095
  13. package/dest/bin/index.js +15 -10
  14. package/dest/factory.d.ts +33 -0
  15. package/dest/factory.d.ts.map +1 -0
  16. package/dest/factory.js +531 -0
  17. package/dest/index.d.ts +3 -1
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +2 -0
  20. package/dest/modules/block_parameter.d.ts +25 -0
  21. package/dest/modules/block_parameter.d.ts.map +1 -0
  22. package/dest/modules/block_parameter.js +100 -0
  23. package/dest/modules/node_block_provider.d.ts +19 -0
  24. package/dest/modules/node_block_provider.d.ts.map +1 -0
  25. package/dest/modules/node_block_provider.js +112 -0
  26. package/dest/modules/node_tx_receipt.d.ts +24 -0
  27. package/dest/modules/node_tx_receipt.d.ts.map +1 -0
  28. package/dest/modules/node_tx_receipt.js +70 -0
  29. package/dest/modules/node_world_state_queries.d.ts +65 -0
  30. package/dest/modules/node_world_state_queries.d.ts.map +1 -0
  31. package/dest/modules/node_world_state_queries.js +272 -0
  32. package/dest/sentinel/factory.d.ts +3 -3
  33. package/dest/sentinel/factory.d.ts.map +1 -1
  34. package/dest/sentinel/factory.js +8 -1
  35. package/dest/sentinel/sentinel.d.ts +21 -21
  36. package/dest/sentinel/sentinel.d.ts.map +1 -1
  37. package/dest/sentinel/sentinel.js +27 -47
  38. package/package.json +28 -27
  39. package/src/aztec-node/config.ts +19 -0
  40. package/src/aztec-node/node_public_calls_simulator.ts +394 -0
  41. package/src/aztec-node/register_node_rpc_handlers.ts +29 -0
  42. package/src/aztec-node/server.ts +339 -1260
  43. package/src/bin/index.ts +19 -12
  44. package/src/factory.ts +697 -0
  45. package/src/index.ts +2 -0
  46. package/src/modules/block_parameter.ts +93 -0
  47. package/src/modules/node_block_provider.ts +149 -0
  48. package/src/modules/node_tx_receipt.ts +115 -0
  49. package/src/modules/node_world_state_queries.ts +374 -0
  50. package/src/sentinel/README.md +3 -3
  51. package/src/sentinel/factory.ts +15 -3
  52. package/src/sentinel/sentinel.ts +34 -72
@@ -1,68 +1,3 @@
1
- function _ts_add_disposable_resource(env, value, async) {
2
- if (value !== null && value !== void 0) {
3
- if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
4
- var dispose, inner;
5
- if (async) {
6
- if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
7
- dispose = value[Symbol.asyncDispose];
8
- }
9
- if (dispose === void 0) {
10
- if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
11
- dispose = value[Symbol.dispose];
12
- if (async) inner = dispose;
13
- }
14
- if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
15
- if (inner) dispose = function() {
16
- try {
17
- inner.call(this);
18
- } catch (e) {
19
- return Promise.reject(e);
20
- }
21
- };
22
- env.stack.push({
23
- value: value,
24
- dispose: dispose,
25
- async: async
26
- });
27
- } else if (async) {
28
- env.stack.push({
29
- async: true
30
- });
31
- }
32
- return value;
33
- }
34
- function _ts_dispose_resources(env) {
35
- var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
36
- var e = new Error(message);
37
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
38
- };
39
- return (_ts_dispose_resources = function _ts_dispose_resources(env) {
40
- function fail(e) {
41
- env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
42
- env.hasError = true;
43
- }
44
- var r, s = 0;
45
- function next() {
46
- while(r = env.stack.pop()){
47
- try {
48
- if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
49
- if (r.dispose) {
50
- var result = r.dispose.call(r.value);
51
- if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) {
52
- fail(e);
53
- return next();
54
- });
55
- } else s |= 1;
56
- } catch (e) {
57
- fail(e);
58
- }
59
- }
60
- if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
61
- if (env.hasError) throw env.error;
62
- }
63
- return next();
64
- })(env);
65
- }
66
1
  function applyDecs2203RFactory() {
67
2
  function createAddInitializerMethod(initializers, decoratorFinishedRef) {
68
3
  return function addInitializer(initializer) {
@@ -436,67 +371,59 @@ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
436
371
  return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
437
372
  }
438
373
  var _dec, _initProto;
439
- import { L1ToL2MessagesNotReadyError, createArchiver } from '@aztec/archiver';
440
374
  import { BBCircuitVerifier, BatchChonkVerifier, QueuedIVCVerifier } from '@aztec/bb-prover';
441
375
  import { TestCircuitVerifier } from '@aztec/bb-prover/test';
442
- import { createBlobClientWithFileStores } from '@aztec/blob-client/client';
443
- import { Blob } from '@aztec/blob-lib';
444
- import { EpochCache } from '@aztec/epoch-cache';
445
- import { createEthereumChain } from '@aztec/ethereum/chain';
446
- import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
447
- import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
448
376
  import { pickL1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
449
- import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
450
- import { chunkBy, compactArray, pick, unique } from '@aztec/foundation/collection';
451
- import { Fr } from '@aztec/foundation/curves/bn254';
377
+ import { BlockNumber } from '@aztec/foundation/branded-types';
378
+ import { compactArray, pick, unique } from '@aztec/foundation/collection';
452
379
  import { EthAddress } from '@aztec/foundation/eth-address';
453
380
  import { BadRequestError } from '@aztec/foundation/json-rpc';
454
381
  import { createLogger } from '@aztec/foundation/log';
455
382
  import { retryUntil } from '@aztec/foundation/retry';
456
383
  import { count } from '@aztec/foundation/string';
457
- import { DateProvider, Timer } from '@aztec/foundation/timer';
458
- import { MembershipWitness } from '@aztec/foundation/trees';
459
- import { isErrorClass } from '@aztec/foundation/types';
384
+ import { Timer } from '@aztec/foundation/timer';
460
385
  import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
461
- import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
462
- import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
463
- import { createP2PClient, createTxValidatorForAcceptingTxsOverRPC, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
386
+ import { uploadSnapshot } from '@aztec/node-lib/actions';
387
+ import { createTxValidatorForAcceptingTxsOverRPC, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
464
388
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
465
- import { createProverNode } from '@aztec/prover-node';
466
- import { createKeyStoreForProver } from '@aztec/prover-node/config';
467
- import { FeeProviderImpl, GlobalVariableBuilder, SequencerClient, createAutomineSequencer } from '@aztec/sequencer-client';
468
- import { PublicContractsDB, PublicProcessorFactory } from '@aztec/simulator/server';
469
- import { AttestationsBlockWatcher, AttestedInvalidProposalWatcher, BroadcastedInvalidCheckpointProposalWatcher, CheckpointEquivocationWatcher, DataWithholdingWatcher, createSlasher } from '@aztec/slasher';
470
389
  import { STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS } from '@aztec/standard-contracts/multi-call-entrypoint';
471
- import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
472
- import { AztecAddress } from '@aztec/stdlib/aztec-address';
473
- import { BlockHash, BlockTag, inspectBlockParameter } from '@aztec/stdlib/block';
474
- import { CheckpointReexecutionTracker } from '@aztec/stdlib/checkpoint';
475
- import { GasFees } from '@aztec/stdlib/gas';
476
- import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
390
+ import { inspectBlockParameter } from '@aztec/stdlib/block';
391
+ import { GasFees, getNetworkTxGasLimits } from '@aztec/stdlib/gas';
477
392
  import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
478
393
  import { tryStop } from '@aztec/stdlib/interfaces/server';
479
- import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
480
- import { InboxLeaf, appendL1ToL2MessagesToTree } from '@aztec/stdlib/messaging';
481
- import { MIN_EXECUTION_TIME } from '@aztec/stdlib/timetable';
482
- import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
483
- import { PublicSimulationOutput, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
484
- import { getPackageVersion } from '@aztec/stdlib/update-checker';
394
+ import { NullDebugLogStore } from '@aztec/stdlib/logs';
485
395
  import { Attributes, getTelemetryClient, trackSpan } from '@aztec/telemetry-client';
486
- import { FullNodeCheckpointsBuilder as CheckpointsBuilder, FullNodeCheckpointsBuilder, NodeKeystoreAdapter, ValidatorClient, createProposalHandler, createValidatorClient } from '@aztec/validator-client';
487
- import { createWorldState, createWorldStateSynchronizer } from '@aztec/world-state';
488
- import { createPublicClient } from 'viem';
489
- import { createSentinel } from '../sentinel/factory.js';
490
- import { blockResponseFromBlockData, blockResponseFromL2Block, checkpointResponseFromCheckpointData, checkpointResponseFromPublishedCheckpoint, projectProposedToCheckpointResponse } from './block_response_helpers.js';
491
- 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';
492
400
  import { NodeMetrics } from './node_metrics.js';
493
- import { applyPublicDataOverrides } from './public_data_overrides.js';
401
+ import { NodePublicCallsSimulator } from './node_public_calls_simulator.js';
494
402
  _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
495
403
  [Attributes.TX_HASH]: tx.getTxHash().toString()
496
404
  }));
497
405
  /**
498
406
  * The aztec node.
499
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;
500
427
  config;
501
428
  p2pClient;
502
429
  blockSource;
@@ -512,6 +439,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
512
439
  l1ChainId;
513
440
  version;
514
441
  globalVariableBuilder;
442
+ rollupContract;
515
443
  feeProvider;
516
444
  epochCache;
517
445
  packageVersion;
@@ -524,58 +452,76 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
524
452
  keyStoreManager;
525
453
  debugLogStore;
526
454
  automineSequencer;
527
- static{
528
- ({ e: [_initProto] } = _apply_decs_2203_r(this, [
529
- [
530
- _dec,
531
- 2,
532
- "simulatePublicCalls"
533
- ]
534
- ], []));
535
- }
536
- metrics;
537
- // Prevent two snapshot operations to happen simultaneously
538
- isUploadingSnapshot;
539
- // Saved minTxsPerBlock used by `pauseSequencer` to restore production-sequencer config on resume.
540
- sequencerPausedMinTxsPerBlock;
541
- tracer;
542
- constructor(config, p2pClient, blockSource, logsSource, contractDataSource, l1ToL2MessageSource, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, stopStartedWatchers, l1ChainId, version, globalVariableBuilder, feeProvider, epochCache, packageVersion, peerProofVerifier, rpcProofVerifier, telemetry = getTelemetryClient(), log = createLogger('node'), blobClient, validatorClient, keyStoreManager, debugLogStore = new NullDebugLogStore(), automineSequencer){
543
- this.config = config;
544
- this.p2pClient = p2pClient;
545
- this.blockSource = blockSource;
546
- this.logsSource = logsSource;
547
- this.contractDataSource = contractDataSource;
548
- this.l1ToL2MessageSource = l1ToL2MessageSource;
549
- this.worldStateSynchronizer = worldStateSynchronizer;
550
- this.sequencer = sequencer;
551
- this.proverNode = proverNode;
552
- this.slasherClient = slasherClient;
553
- this.validatorsSentinel = validatorsSentinel;
554
- this.stopStartedWatchers = stopStartedWatchers;
555
- this.l1ChainId = l1ChainId;
556
- this.version = version;
557
- this.globalVariableBuilder = globalVariableBuilder;
558
- this.feeProvider = feeProvider;
559
- this.epochCache = epochCache;
560
- this.packageVersion = packageVersion;
561
- this.peerProofVerifier = peerProofVerifier;
562
- this.rpcProofVerifier = rpcProofVerifier;
563
- this.telemetry = telemetry;
564
- this.log = log;
565
- this.blobClient = blobClient;
566
- this.validatorClient = validatorClient;
567
- this.keyStoreManager = keyStoreManager;
568
- this.debugLogStore = debugLogStore;
569
- this.automineSequencer = automineSequencer;
570
- this.isUploadingSnapshot = (_initProto(this), false);
571
- this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
572
- this.tracer = telemetry.getTracer('AztecNodeService');
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
+ });
573
519
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
574
- this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, pickL1ContractAddresses(config));
575
- // 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
576
522
  // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
577
523
  // memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
578
- if (debugLogStore.isEnabled && config.realProofs) {
524
+ if (this.debugLogStore.isEnabled && this.config.realProofs) {
579
525
  throw new Error('debugLogStore should never be enabled when realProofs are set');
580
526
  }
581
527
  }
@@ -586,14 +532,20 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
586
532
  const status = await this.worldStateSynchronizer.status();
587
533
  return status.syncSummary;
588
534
  }
589
- async getChainTips() {
590
- const { proposed, checkpointed, proven, finalized } = await this.blockSource.getL2Tips();
591
- return {
592
- proposed,
593
- checkpointed,
594
- proven,
595
- finalized
596
- };
535
+ getChainTips() {
536
+ return this.blockSource.getL2Tips();
537
+ }
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();
597
549
  }
598
550
  getCheckpointsData(query) {
599
551
  return this.blockSource.getCheckpointsData(query);
@@ -612,620 +564,26 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
612
564
  case undefined:
613
565
  case 'checkpointed':
614
566
  return tips.checkpointed.checkpoint.number;
615
- case 'proposed':
616
- return tips.proposedCheckpoint.checkpoint.number;
617
567
  case 'proven':
618
568
  return tips.proven.checkpoint.number;
619
569
  case 'finalized':
620
570
  return tips.finalized.checkpoint.number;
621
571
  }
622
572
  }
623
- isChainTip(value) {
624
- return value === 'proposed' || value === 'checkpointed' || value === 'proven' || value === 'finalized';
625
- }
626
- /**
627
- * Normalizes a {@link BlockParameter} (which may be a bare value) into a
628
- * {@link NormalizedBlockParameter} object form. Performs no chain-tip resolution — tag
629
- * lookups are deferred to the underlying block source.
630
- */ normalizeBlockParameter(param) {
631
- if (BlockHash.isBlockHash(param)) {
632
- return {
633
- hash: param
634
- };
635
- }
636
- if (typeof param === 'number') {
637
- return {
638
- number: param
639
- };
640
- }
641
- if (typeof param === 'string') {
642
- if (this.isBlockTag(param)) {
643
- return {
644
- tag: param === 'latest' ? 'proposed' : param
645
- };
646
- }
647
- throw new BadRequestError(`Invalid BlockParameter tag: ${param}`);
648
- }
649
- if (typeof param === 'object' && param !== null) {
650
- if ('number' in param) {
651
- return {
652
- number: param.number
653
- };
654
- }
655
- if ('hash' in param) {
656
- return {
657
- hash: param.hash
658
- };
659
- }
660
- if ('archive' in param) {
661
- return {
662
- archive: param.archive
663
- };
664
- }
665
- if ('tag' in param) {
666
- if (this.isBlockTag(param.tag)) {
667
- return {
668
- tag: param.tag
669
- };
670
- }
671
- throw new BadRequestError(`Invalid BlockParameter tag: ${param.tag}`);
672
- }
673
- }
674
- throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(param)}`);
675
- }
676
- isBlockTag(value) {
677
- return BlockTag.includes(value);
678
- }
679
- /**
680
- * Resolves a {@link CheckpointParameter} into a concrete `{ number }` or `{ slot }` query.
681
- *
682
- * Tag-based parameters (`'proposed'`, `'checkpointed'`, `'proven'`, `'finalized'`) are
683
- * translated up-front to the corresponding tip's checkpoint number via {@link L2BlockSource.getL2Tips}.
684
- * After resolution the unified {@link getCheckpoint} flow can perform a single
685
- * confirmed→proposed lookup against either store.
686
- */ async resolveCheckpointParameter(param) {
687
- if (typeof param === 'number') {
688
- return {
689
- number: param
690
- };
691
- }
692
- if (this.isChainTip(param)) {
693
- const tips = await this.blockSource.getL2Tips();
694
- switch(param){
695
- case 'proposed':
696
- return {
697
- number: tips.proposedCheckpoint.checkpoint.number
698
- };
699
- case 'checkpointed':
700
- return {
701
- number: tips.checkpointed.checkpoint.number
702
- };
703
- case 'proven':
704
- return {
705
- number: tips.proven.checkpoint.number
706
- };
707
- case 'finalized':
708
- return {
709
- number: tips.finalized.checkpoint.number
710
- };
711
- }
712
- }
713
- if (typeof param === 'object' && param !== null) {
714
- if ('number' in param) {
715
- return {
716
- number: param.number
717
- };
718
- }
719
- if ('slot' in param) {
720
- return {
721
- slot: param.slot
722
- };
723
- }
724
- }
725
- throw new BadRequestError(`Invalid CheckpointParameter: ${JSON.stringify(param)}`);
726
- }
727
- /** Fetches checkpoint-level L1 and attestation data for use as block response context. */ async #getCheckpointContext(checkpointNumber) {
728
- const checkpoint = await this.blockSource.getCheckpointData({
729
- number: checkpointNumber
730
- });
731
- if (!checkpoint) {
732
- return undefined;
733
- }
734
- return {
735
- l1: checkpoint.l1,
736
- attestations: checkpoint.attestations
737
- };
738
- }
739
- async getBlock(param, options = {}) {
740
- const query = this.normalizeBlockParameter(param);
741
- const wantTxs = !!options.includeTransactions;
742
- const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
743
- if (wantTxs) {
744
- const block = await this.blockSource.getBlock(query);
745
- if (!block) {
746
- return undefined;
747
- }
748
- const ctx = wantContext ? await this.#getCheckpointContext(block.checkpointNumber) : undefined;
749
- return await blockResponseFromL2Block(block, options, ctx);
750
- }
751
- const data = await this.blockSource.getBlockData(query);
752
- if (!data) {
753
- return undefined;
754
- }
755
- const ctx = wantContext ? await this.#getCheckpointContext(data.checkpointNumber) : undefined;
756
- return blockResponseFromBlockData(data, options, ctx);
573
+ getBlock(param, options = {}) {
574
+ return this.blockProvider.getBlock(param, options);
757
575
  }
758
576
  getBlockData(param) {
759
- const query = this.normalizeBlockParameter(param);
760
- return this.blockSource.getBlockData(query);
761
- }
762
- async getBlocks(from, limit, options = {}) {
763
- const wantTxs = !!options.includeTransactions;
764
- const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
765
- const onlyCheckpointed = !!options.onlyCheckpointed;
766
- if (wantTxs) {
767
- const blocks = await this.blockSource.getBlocks({
768
- from,
769
- limit,
770
- onlyCheckpointed
771
- });
772
- const ctxByCheckpoint = await this.#getCheckpointContextsForBlocks(wantContext ? blocks : []);
773
- return await Promise.all(blocks.map((block)=>blockResponseFromL2Block(block, options, ctxByCheckpoint.get(block.checkpointNumber))));
774
- }
775
- const dataItems = await this.blockSource.getBlocksData({
776
- from,
777
- limit,
778
- onlyCheckpointed
779
- });
780
- const ctxByCheckpoint = await this.#getCheckpointContextsForBlocks(wantContext ? dataItems : []);
781
- return await Promise.all(dataItems.map((data)=>blockResponseFromBlockData(data, options, ctxByCheckpoint.get(data.checkpointNumber))));
782
- }
783
- /** Fetches checkpoint context for a set of blocks, deduplicating shared checkpoints. */ async #getCheckpointContextsForBlocks(blocks) {
784
- const unique = Array.from(new Set(blocks.map((b)=>b.checkpointNumber)));
785
- const entries = await Promise.all(unique.map(async (n)=>[
786
- n,
787
- await this.#getCheckpointContext(n)
788
- ]));
789
- return new Map(entries);
790
- }
791
- async getCheckpoint(param, options = {}) {
792
- const query = await this.resolveCheckpointParameter(param);
793
- // Try the confirmed store first.
794
- const confirmed = options.includeBlocks ? await this.blockSource.getCheckpoint(query) : await this.blockSource.getCheckpointData(query);
795
- if (confirmed) {
796
- return await (options.includeBlocks ? checkpointResponseFromPublishedCheckpoint(confirmed, options) : checkpointResponseFromCheckpointData(confirmed, options));
797
- }
798
- // Fall back to the proposed store.
799
- const proposed = await this.blockSource.getProposedCheckpointData(query);
800
- if (proposed) {
801
- if (options.includeAttestations || options.includeL1PublishInfo) {
802
- throw new BadRequestError(`Options includeL1PublishInfo or includeAttestations cannot be satisfied for a proposed checkpoint`);
803
- }
804
- const blocks = options.includeBlocks ? await this.blockSource.getBlocks({
805
- from: proposed.startBlock,
806
- limit: proposed.blockCount
807
- }) : undefined;
808
- return await projectProposedToCheckpointResponse(proposed, options, blocks);
809
- }
810
- return undefined;
577
+ return this.blockProvider.getBlockData(param);
811
578
  }
812
- async getCheckpoints(from, limit, options = {}) {
813
- if (options.includeBlocks) {
814
- const checkpoints = await this.blockSource.getCheckpoints({
815
- from,
816
- limit
817
- });
818
- return await Promise.all(checkpoints.map((cp)=>checkpointResponseFromPublishedCheckpoint(cp, options)));
819
- }
820
- const datas = await this.blockSource.getCheckpointsData({
821
- from,
822
- limit
823
- });
824
- return datas.map((d)=>checkpointResponseFromCheckpointData(d, options));
579
+ getBlocks(from, limit, options = {}) {
580
+ return this.blockProvider.getBlocks(from, limit, options);
825
581
  }
826
- /**
827
- * initializes the Aztec Node, wait for component to sync.
828
- * @param config - The configuration to be used by the aztec node.
829
- * @returns - A fully synced Aztec Node for use in development/testing.
830
- */ static async createAndSync(inputConfig, deps = {}, options = {}) {
831
- const config = {
832
- ...inputConfig
833
- }; // Copy the config so we dont mutate the input object
834
- const log = deps.logger ?? createLogger('node');
835
- const packageVersion = getPackageVersion();
836
- const telemetry = deps.telemetry ?? getTelemetryClient();
837
- const dateProvider = deps.dateProvider ?? new DateProvider();
838
- const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
839
- // Build a key store from file if given or from environment otherwise.
840
- // We keep the raw KeyStore available so we can merge with prover keys if enableProverNode is set.
841
- let keyStoreManager;
842
- const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
843
- if (keyStoreProvided) {
844
- const keyStores = loadKeystores(config.keyStoreDirectory);
845
- keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
846
- } else {
847
- const rawKeyStores = [];
848
- const validatorKeyStore = createKeyStoreForValidator(config);
849
- if (validatorKeyStore) {
850
- rawKeyStores.push(validatorKeyStore);
851
- }
852
- if (config.enableProverNode) {
853
- const proverKeyStore = createKeyStoreForProver(config);
854
- if (proverKeyStore) {
855
- rawKeyStores.push(proverKeyStore);
856
- }
857
- }
858
- if (rawKeyStores.length > 0) {
859
- keyStoreManager = new KeystoreManager(rawKeyStores.length === 1 ? rawKeyStores[0] : mergeKeystores(rawKeyStores));
860
- }
861
- }
862
- await keyStoreManager?.validateSigners();
863
- // If we are a validator, verify our configuration before doing too much more.
864
- if (!config.disableValidator) {
865
- if (keyStoreManager === undefined) {
866
- throw new Error('Failed to create key store, a requirement for running a validator');
867
- }
868
- if (!keyStoreProvided && process.env.NODE_ENV !== 'test') {
869
- log.warn("Keystore created from env: it's recommended to use a file-based key store for production");
870
- }
871
- ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
872
- }
873
- // validate that the actual chain id matches that specified in configuration
874
- if (config.l1ChainId !== ethereumChain.chainInfo.id) {
875
- throw new Error(`RPC URL configured for chain id ${ethereumChain.chainInfo.id} but expected id ${config.l1ChainId}`);
876
- }
877
- const publicClient = createPublicClient({
878
- chain: ethereumChain.chainInfo,
879
- transport: makeL1HttpTransport(config.l1RpcUrls, {
880
- timeout: config.l1HttpTimeoutMS
881
- }),
882
- pollingInterval: config.viemPollingIntervalMS
883
- });
884
- const l1ContractsAddresses = await RegistryContract.collectAddresses(publicClient, config.registryAddress, config.rollupVersion ?? 'canonical');
885
- Object.assign(config, l1ContractsAddresses);
886
- const rollupContract = new RollupContract(publicClient, config.rollupAddress.toString());
887
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
888
- rollupContract.getL1GenesisTime(),
889
- rollupContract.getSlotDuration(),
890
- rollupContract.getVersion(),
891
- rollupContract.getManaLimit().then(Number)
892
- ]);
893
- config.rollupVersion ??= Number(rollupVersionFromRollup);
894
- if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
895
- 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}).`);
896
- }
897
- const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
898
- // attempt snapshot sync if possible
899
- await trySnapshotSync(config, log);
900
- const epochCache = await EpochCache.create(config.rollupAddress, config, {
901
- dateProvider
902
- });
903
- // Track started resources so we can clean up on partial failure during node creation.
904
- const started = [];
905
- try {
906
- // Default the orphan-prune grace window from the block build duration when unset, so the archiver
907
- // waits roughly one build slot for a proposed checkpoint to arrive before pruning a block-only tip.
908
- config.orphanProposedBlockPruneGraceSeconds ??= config.blockDurationMs !== undefined ? Math.ceil(config.blockDurationMs / 1000) : MIN_EXECUTION_TIME;
909
- // Create world-state first so we can retrieve the initial header before constructing the archiver.
910
- const nativeWs = await createWorldState(config, options.genesis);
911
- const initialHeader = nativeWs.getInitialHeader();
912
- const initialBlockHash = await initialHeader.hash();
913
- const archiver = await createArchiver(config, {
914
- blobClient,
915
- epochCache,
916
- telemetry,
917
- dateProvider
918
- }, {
919
- blockUntilSync: !config.skipArchiverInitialSync
920
- }, initialHeader, initialBlockHash);
921
- started.push(archiver);
922
- // The synchronizer takes ownership of the native world-state from here
923
- const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, nativeWs, telemetry);
924
- started.push(worldStateSynchronizer);
925
- const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
926
- let peerProofVerifier;
927
- let rpcProofVerifier;
928
- if (useRealVerifiers) {
929
- peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
930
- const rpcVerifier = await BBCircuitVerifier.new(config);
931
- rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
932
- } else {
933
- peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
934
- rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
935
- }
936
- started.push(peerProofVerifier, rpcProofVerifier);
937
- let debugLogStore;
938
- if (!config.realProofs) {
939
- log.warn(`Aztec node is accepting fake proofs`);
940
- debugLogStore = new InMemoryDebugLogStore();
941
- log.info('Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served');
942
- } else {
943
- debugLogStore = new NullDebugLogStore();
944
- }
945
- const globalVariableBuilderConfig = {
946
- rollupAddress: config.rollupAddress,
947
- ethereumSlotDuration: config.ethereumSlotDuration,
948
- rollupVersion: BigInt(config.rollupVersion),
949
- l1GenesisTime,
950
- slotDuration: Number(slotDuration)
951
- };
952
- const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, globalVariableBuilderConfig);
953
- const feeProvider = new FeeProviderImpl(dateProvider, publicClient, globalVariableBuilderConfig);
954
- const proverOnly = config.enableProverNode && config.disableValidator;
955
- if (proverOnly) {
956
- log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
957
- }
958
- // create the tx pool and the p2p client, which will need the l2 block source
959
- const p2pClient = await createP2PClient(config, archiver, peerProofVerifier, worldStateSynchronizer, epochCache, feeProvider, packageVersion, dateProvider, telemetry, deps.p2pClientDeps, initialBlockHash);
960
- started.push(p2pClient);
961
- // We'll accumulate sentinel watchers here
962
- const watchers = [];
963
- // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
964
- // Override maxTxsPerCheckpoint with the validator-specific limit if set.
965
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder({
966
- ...config,
967
- l1GenesisTime,
968
- slotDuration: Number(slotDuration),
969
- rollupManaLimit,
970
- maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint
971
- }, worldStateSynchronizer, archiver, dateProvider, telemetry);
972
- let validatorClient;
973
- // Tracks successful checkpoint re-execution by a checkpoint proposal handler.
974
- const reexecutionTracker = new CheckpointReexecutionTracker();
975
- if (!config.disableValidator) {
976
- // Create validator client if required
977
- validatorClient = await createValidatorClient(config, {
978
- checkpointsBuilder: validatorCheckpointsBuilder,
979
- worldState: worldStateSynchronizer,
980
- p2pClient,
981
- telemetry,
982
- dateProvider,
983
- epochCache,
984
- blockSource: archiver,
985
- l1ToL2MessageSource: archiver,
986
- keyStoreManager,
987
- blobClient,
988
- reexecutionTracker,
989
- slashingProtectionDb: deps.slashingProtectionDb
990
- });
991
- // If we have a validator client, register it as a source of offenses for the slasher,
992
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
993
- // like attestations or auths will fail.
994
- if (validatorClient) {
995
- watchers.push(validatorClient);
996
- const vc = validatorClient;
997
- const getValidatorAddresses = ()=>vc.getValidatorAddresses().map((a)=>a.toString());
998
- validatorClient.getProposalHandler().register(p2pClient, true, archiver, getValidatorAddresses);
999
- if (!options.dontStartSequencer) {
1000
- await validatorClient.registerHandlers();
1001
- }
1002
- }
1003
- }
1004
- // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
1005
- // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
1006
- // while non-reexecution is used for validating the proposals and collecting their txs.
1007
- // Checkpoint proposals rebuild blobs if the blob client can upload blobs.
1008
- if (!validatorClient) {
1009
- const reexecute = !!config.alwaysReexecuteBlockProposals;
1010
- log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
1011
- createProposalHandler(config, {
1012
- checkpointsBuilder: validatorCheckpointsBuilder,
1013
- worldState: worldStateSynchronizer,
1014
- epochCache,
1015
- blockSource: archiver,
1016
- l1ToL2MessageSource: archiver,
1017
- p2pClient,
1018
- blobClient,
1019
- dateProvider,
1020
- telemetry,
1021
- reexecutionTracker
1022
- }).register(p2pClient, reexecute, archiver);
1023
- }
1024
- // Start world state and wait for it to sync to the archiver.
1025
- await worldStateSynchronizer.start();
1026
- // Start p2p. Note that it depends on world state to be running.
1027
- await p2pClient.start();
1028
- let validatorsSentinel;
1029
- let dataWithholdingWatcher;
1030
- let attestationsBlockWatcher;
1031
- let attestedInvalidProposalWatcher;
1032
- let broadcastedInvalidCheckpointProposalWatcher;
1033
- let checkpointEquivocationWatcher;
1034
- if (!proverOnly) {
1035
- validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, reexecutionTracker, config);
1036
- if (validatorsSentinel) {
1037
- watchers.push(validatorsSentinel);
1038
- }
1039
- dataWithholdingWatcher = new DataWithholdingWatcher(epochCache, archiver, p2pClient.getTxProvider(), p2pClient, reexecutionTracker, {
1040
- chainId: config.l1ChainId,
1041
- rollupAddress: config.rollupAddress
1042
- }, config);
1043
- watchers.push(dataWithholdingWatcher);
1044
- broadcastedInvalidCheckpointProposalWatcher = new BroadcastedInvalidCheckpointProposalWatcher(p2pClient, archiver, epochCache, config);
1045
- watchers.push(broadcastedInvalidCheckpointProposalWatcher);
1046
- if (validatorClient) {
1047
- attestedInvalidProposalWatcher = new AttestedInvalidProposalWatcher(p2pClient, validatorClient, archiver, epochCache, config, {
1048
- log: log.createChild('attested-invalid-proposal-watcher')
1049
- });
1050
- watchers.push(attestedInvalidProposalWatcher);
1051
- }
1052
- checkpointEquivocationWatcher = new CheckpointEquivocationWatcher(archiver, epochCache, config);
1053
- watchers.push(checkpointEquivocationWatcher);
1054
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config, log.getBindings());
1055
- watchers.push(attestationsBlockWatcher);
1056
- }
1057
- const watchersToStart = compactArray([
1058
- validatorsSentinel,
1059
- dataWithholdingWatcher,
1060
- attestationsBlockWatcher,
1061
- broadcastedInvalidCheckpointProposalWatcher,
1062
- attestedInvalidProposalWatcher,
1063
- checkpointEquivocationWatcher
1064
- ]);
1065
- const startedWatchers = [];
1066
- const stopStartedWatchers = async ()=>{
1067
- for (const watcher of startedWatchers){
1068
- await tryStop(watcher);
1069
- }
1070
- };
1071
- // Start p2p-related services once the archiver has completed sync
1072
- void archiver.waitForInitialSync().then(async ()=>{
1073
- for (const watcher of watchersToStart){
1074
- await watcher.start();
1075
- startedWatchers.push(watcher);
1076
- }
1077
- log.info(`All p2p services started`);
1078
- }).catch((err)=>log.error('Failed to start p2p services after archiver sync', err));
1079
- started.push({
1080
- stop: stopStartedWatchers
1081
- });
1082
- // Validator enabled, create/start relevant service
1083
- let sequencer;
1084
- let automineSequencer;
1085
- let slasherClient;
1086
- if (!config.disableValidator && validatorClient) {
1087
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
1088
- // as they are executed when the node is selected as proposer.
1089
- const validatorAddresses = keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses() : [];
1090
- slasherClient = await createSlasher(config, pickL1ContractAddresses(config), getPublicClient(config), watchers, dateProvider, epochCache, validatorAddresses, undefined);
1091
- await slasherClient.start();
1092
- started.push(slasherClient);
1093
- const l1TxUtils = config.sequencerPublisherForwarderAddress ? await createForwarderL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), config.sequencerPublisherForwarderAddress, {
1094
- ...config,
1095
- scope: 'sequencer'
1096
- }, {
1097
- telemetry,
1098
- logger: log.createChild('l1-tx-utils'),
1099
- dateProvider,
1100
- kzg: Blob.getViemKzgInstance()
1101
- }) : await createL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
1102
- ...config,
1103
- scope: 'sequencer'
1104
- }, {
1105
- telemetry,
1106
- logger: log.createChild('l1-tx-utils'),
1107
- dateProvider,
1108
- kzg: Blob.getViemKzgInstance()
1109
- });
1110
- // Create a funder L1TxUtils from the keystore funding account (if configured)
1111
- const fundingSigner = keyStoreManager?.createFundingSigner();
1112
- let funderL1TxUtils;
1113
- if (fundingSigner) {
1114
- const [funder] = await createL1TxUtilsFromSigners(publicClient, [
1115
- fundingSigner
1116
- ], {
1117
- ...config,
1118
- scope: 'sequencer'
1119
- }, {
1120
- telemetry,
1121
- logger: log.createChild('l1-tx-utils:funder'),
1122
- dateProvider
1123
- });
1124
- funderL1TxUtils = funder;
1125
- }
1126
- // Create and start the sequencer client
1127
- const checkpointsBuilder = new CheckpointsBuilder({
1128
- ...config,
1129
- l1GenesisTime,
1130
- slotDuration: Number(slotDuration),
1131
- rollupManaLimit
1132
- }, worldStateSynchronizer, archiver, dateProvider, telemetry, debugLogStore);
1133
- if (config.useAutomineSequencer) {
1134
- // Test-only path: deterministic, queue-driven sequencer for non-block-building e2e tests.
1135
- // See `AUTOMINE_E2E_OPTS` in `end-to-end/src/fixtures/fixtures.ts`.
1136
- automineSequencer = await createAutomineSequencer({
1137
- config,
1138
- l1TxUtils,
1139
- funderL1TxUtils,
1140
- publicClient,
1141
- rollupContract,
1142
- epochCache,
1143
- blobClient,
1144
- telemetry,
1145
- dateProvider,
1146
- keyStoreManager: keyStoreManager,
1147
- validatorClient,
1148
- checkpointsBuilder,
1149
- globalVariableBuilder,
1150
- worldStateSynchronizer,
1151
- archiver,
1152
- p2pClient,
1153
- l1Constants: {
1154
- l1GenesisTime,
1155
- slotDuration: Number(slotDuration),
1156
- ethereumSlotDuration: config.ethereumSlotDuration,
1157
- rollupManaLimit
1158
- },
1159
- log
1160
- });
1161
- } else {
1162
- sequencer = await SequencerClient.new(config, {
1163
- ...deps,
1164
- epochCache,
1165
- l1TxUtils,
1166
- funderL1TxUtils,
1167
- validatorClient,
1168
- p2pClient,
1169
- worldStateSynchronizer,
1170
- slasherClient,
1171
- checkpointsBuilder,
1172
- l2BlockSource: archiver,
1173
- l1ToL2MessageSource: archiver,
1174
- telemetry,
1175
- dateProvider,
1176
- blobClient,
1177
- nodeKeyStore: keyStoreManager,
1178
- globalVariableBuilder
1179
- });
1180
- }
1181
- }
1182
- if (!options.dontStartSequencer && sequencer) {
1183
- await sequencer.start();
1184
- started.push(sequencer);
1185
- log.verbose(`Sequencer started`);
1186
- } else if (sequencer) {
1187
- log.warn(`Sequencer created but not started`);
1188
- }
1189
- if (!options.dontStartSequencer && automineSequencer) {
1190
- await automineSequencer.start();
1191
- started.push({
1192
- stop: ()=>automineSequencer.stop()
1193
- });
1194
- log.verbose(`AutomineSequencer started`);
1195
- } else if (automineSequencer) {
1196
- log.warn(`AutomineSequencer created but not started`);
1197
- }
1198
- // Create prover node subsystem if enabled
1199
- let proverNode;
1200
- if (config.enableProverNode) {
1201
- proverNode = await createProverNode(config, {
1202
- ...deps.proverNodeDeps,
1203
- telemetry,
1204
- dateProvider,
1205
- archiver,
1206
- worldStateSynchronizer,
1207
- p2pClient,
1208
- epochCache,
1209
- blobClient,
1210
- keyStoreManager
1211
- });
1212
- if (!options.dontStartProverNode) {
1213
- await proverNode.start();
1214
- started.push(proverNode);
1215
- log.info(`Prover node subsystem started`);
1216
- } else {
1217
- log.info(`Prover node subsystem created but not started`);
1218
- }
1219
- }
1220
- const node = new AztecNodeService(config, p2pClient, archiver, archiver, archiver, archiver, worldStateSynchronizer, sequencer, proverNode, slasherClient, validatorsSentinel, stopStartedWatchers, ethereumChain.chainInfo.id, config.rollupVersion, globalVariableBuilder, feeProvider, epochCache, packageVersion, peerProofVerifier, rpcProofVerifier, telemetry, log, blobClient, validatorClient, keyStoreManager, debugLogStore, automineSequencer);
1221
- return node;
1222
- } catch (err) {
1223
- log.error('Failed during node creation, stopping started resources', err);
1224
- for (const resource of started.reverse()){
1225
- await tryStop(resource);
1226
- }
1227
- throw err;
1228
- }
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);
1229
587
  }
1230
588
  /**
1231
589
  * Returns the sequencer client instance.
@@ -1270,14 +628,20 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1270
628
  return Promise.resolve(this.p2pClient.isReady() ?? false);
1271
629
  }
1272
630
  async getNodeInfo() {
1273
- const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses] = await Promise.all([
631
+ const [nodeVersion, rollupVersion, chainId, enr, contractAddresses, protocolContractAddresses, l1Constants] = await Promise.all([
1274
632
  this.getNodeVersion(),
1275
633
  this.getVersion(),
1276
634
  this.getChainId(),
1277
635
  this.getEncodedEnr(),
1278
636
  this.getL1ContractAddresses(),
1279
- this.getProtocolContractAddresses()
637
+ this.getProtocolContractAddresses(),
638
+ this.blockSource.getL1Constants()
1280
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);
1281
645
  const nodeInfo = {
1282
646
  nodeVersion,
1283
647
  l1ChainId: chainId,
@@ -1285,7 +649,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1285
649
  enr,
1286
650
  l1ContractAddresses: contractAddresses,
1287
651
  protocolContractAddresses: protocolContractAddresses,
1288
- realProofs: !!this.config.realProofs
652
+ realProofs: !!this.config.realProofs,
653
+ txsLimits: {
654
+ gas: {
655
+ daGas: maxTxGas.daGas,
656
+ l2Gas: maxTxGas.l2Gas
657
+ }
658
+ }
1289
659
  };
1290
660
  return nodeInfo;
1291
661
  }
@@ -1296,7 +666,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1296
666
  return await this.feeProvider.getPredictedMinFees(manaUsage);
1297
667
  }
1298
668
  async getMaxPriorityFees() {
1299
- for await (const tx of this.p2pClient.iteratePendingTxs()){
669
+ for await (const tx of this.p2pClient.iteratePendingTxs({
670
+ includeProof: false
671
+ })){
1300
672
  return tx.getGasSettings().maxPriorityFeesPerGas;
1301
673
  }
1302
674
  return GasFees.from({
@@ -1325,8 +697,12 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1325
697
  getContractClass(id) {
1326
698
  return this.contractDataSource.getContractClass(id);
1327
699
  }
1328
- getContract(address) {
1329
- return this.contractDataSource.getContract(address);
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.`);
704
+ }
705
+ return this.contractDataSource.getContract(address, blockData.header.globalVariables.timestamp);
1330
706
  }
1331
707
  getPrivateLogsByTags(query) {
1332
708
  return this.logsSource.getPrivateLogsByTags(query);
@@ -1367,27 +743,8 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1367
743
  txHash
1368
744
  });
1369
745
  }
1370
- async getTxReceipt(txHash) {
1371
- // Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
1372
- // as a fallback if we don't find a settled receipt in the archiver.
1373
- const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
1374
- const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
1375
- // Then get the actual tx from the archiver, which tracks every tx in a mined block.
1376
- const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
1377
- let receipt;
1378
- if (settledTxReceipt) {
1379
- receipt = settledTxReceipt;
1380
- } else if (isKnownToPool) {
1381
- // If the tx is in the pool but not in the archiver, it's pending.
1382
- // This handles race conditions between archiver and p2p, where the archiver
1383
- // has pruned the block in which a tx was mined, but p2p has not caught up yet.
1384
- receipt = new TxReceipt(txHash, TxStatus.PENDING, /*executionResult=*/ undefined, /*error=*/ undefined);
1385
- } else {
1386
- // Otherwise, if we don't know the tx, we consider it dropped.
1387
- receipt = new TxReceipt(txHash, TxStatus.DROPPED, /*executionResult=*/ undefined, /*error=*/ 'Tx dropped by P2P node');
1388
- }
1389
- this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
1390
- return receipt;
746
+ getTxReceipt(txHash, options) {
747
+ return this.txReceiptBuilder.getTxReceipt(txHash, options);
1391
748
  }
1392
749
  getTxEffect(txHash) {
1393
750
  return this.blockSource.getTxEffect(txHash);
@@ -1406,6 +763,10 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1406
763
  await tryStop(this.automineSequencer);
1407
764
  await tryStop(this.proverNode);
1408
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]();
1409
770
  await tryStop(this.worldStateSynchronizer);
1410
771
  await tryStop(this.blockSource);
1411
772
  await tryStop(this.blobClient);
@@ -1423,272 +784,94 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1423
784
  * @param limit - The number of items to returns
1424
785
  * @param after - The last known pending tx. Used for pagination
1425
786
  * @returns - The pending txs.
1426
- */ getPendingTxs(limit, after) {
1427
- return this.p2pClient.getPendingTxs(limit, after);
787
+ */ getPendingTxs(limit, after, options) {
788
+ return this.p2pClient.getPendingTxs(limit, after, options);
1428
789
  }
1429
790
  getPendingTxCount() {
1430
791
  return this.p2pClient.getPendingTxCount();
1431
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
+ }
1432
802
  /**
1433
- * 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.
1434
805
  * @param txHash - The transaction hash to return.
806
+ * @param options - Options for the returned tx (eg whether to include its proof).
1435
807
  * @returns - The tx if it exists.
1436
- */ getTxByHash(txHash) {
1437
- return Promise.resolve(this.p2pClient.getTxByHashFromPool(txHash));
808
+ */ getTxByHash(txHash, options) {
809
+ return this.p2pClient.getTxByHashFromPool(txHash, {
810
+ includeProof: !!options?.includeProof
811
+ });
1438
812
  }
1439
813
  /**
1440
- * 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.
1441
816
  * @param txHash - The transaction hash to return.
817
+ * @param options - Options for the returned txs (eg whether to include their proofs).
1442
818
  * @returns - The txs if it exists.
1443
- */ async getTxsByHash(txHashes) {
1444
- return compactArray(await Promise.all(txHashes.map((txHash)=>this.getTxByHash(txHash))));
1445
- }
1446
- async findLeavesIndexes(referenceBlock, treeId, leafValues) {
1447
- const committedDb = await this.getWorldState(referenceBlock);
1448
- const maybeIndices = await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
1449
- // Filter out undefined values to query block numbers only for found leaves
1450
- const definedIndices = maybeIndices.filter((x)=>x !== undefined);
1451
- // Now we find the block numbers for the defined indices
1452
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
1453
- // Build a map from leaf index to block number
1454
- const indexToBlockNumber = new Map();
1455
- for(let i = 0; i < definedIndices.length; i++){
1456
- const blockNumber = blockNumbers[i];
1457
- if (blockNumber === undefined) {
1458
- throw new Error(`Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`);
1459
- }
1460
- indexToBlockNumber.set(definedIndices[i], blockNumber);
1461
- }
1462
- // Get unique block numbers in order to optimize num calls to getLeafValue function.
1463
- const uniqueBlockNumbers = [
1464
- ...new Set(indexToBlockNumber.values())
1465
- ];
1466
- // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
1467
- const blockHashes = await Promise.all(uniqueBlockNumbers.map((blockNumber)=>{
1468
- return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1469
- }));
1470
- // Build a map from block number to block hash
1471
- const blockNumberToHash = new Map();
1472
- for(let i = 0; i < uniqueBlockNumbers.length; i++){
1473
- const blockHash = blockHashes[i];
1474
- if (blockHash === undefined) {
1475
- throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
1476
- }
1477
- blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
1478
- }
1479
- // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
1480
- return maybeIndices.map((index)=>{
1481
- if (index === undefined) {
1482
- return undefined;
1483
- }
1484
- const blockNumber = indexToBlockNumber.get(index);
1485
- if (blockNumber === undefined) {
1486
- throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1487
- }
1488
- const l2BlockHash = blockNumberToHash.get(blockNumber);
1489
- if (l2BlockHash === undefined) {
1490
- throw new Error(`Block hash not found for block number ${blockNumber}`);
1491
- }
1492
- return {
1493
- l2BlockNumber: blockNumber,
1494
- l2BlockHash,
1495
- data: index
1496
- };
819
+ */ async getTxsByHash(txHashes, options) {
820
+ const txs = await this.p2pClient.getTxsByHashFromPool(txHashes, {
821
+ includeProof: !!options?.includeProof
1497
822
  });
823
+ return compactArray(txs);
1498
824
  }
1499
- async getBlockHashMembershipWitness(referenceBlock, blockHash) {
1500
- // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
1501
- // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1502
- // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1503
- const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1504
- if (referenceBlockNumber === BlockNumber.ZERO) {
1505
- // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
1506
- return undefined;
1507
- }
1508
- const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
1509
- const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE, [
1510
- blockHash
1511
- ]);
1512
- return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
825
+ findLeavesIndexes(referenceBlock, treeId, leafValues) {
826
+ return this.worldStateQueries.findLeavesIndexes(referenceBlock, treeId, leafValues);
1513
827
  }
1514
- async getNoteHashMembershipWitness(referenceBlock, noteHash) {
1515
- const committedDb = await this.getWorldState(referenceBlock);
1516
- const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE, [
1517
- noteHash
1518
- ]);
1519
- return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
828
+ getBlockHashMembershipWitness(referenceBlock, blockHash) {
829
+ return this.worldStateQueries.getBlockHashMembershipWitness(referenceBlock, blockHash);
1520
830
  }
1521
- async getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
1522
- const db = await this.getWorldState(referenceBlock);
1523
- const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
1524
- l1ToL2Message
1525
- ]);
1526
- if (!witness) {
1527
- return undefined;
1528
- }
1529
- // REFACTOR: Return a MembershipWitness object
1530
- return [
1531
- witness.index,
1532
- witness.path
1533
- ];
831
+ getNoteHashMembershipWitness(referenceBlock, noteHash) {
832
+ return this.worldStateQueries.getNoteHashMembershipWitness(referenceBlock, noteHash);
1534
833
  }
1535
- async getL1ToL2MessageCheckpoint(l1ToL2Message) {
1536
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1537
- return messageIndex !== undefined ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
834
+ getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
835
+ return this.worldStateQueries.getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message);
836
+ }
837
+ getL1ToL2MessageCheckpoint(l1ToL2Message) {
838
+ return this.worldStateQueries.getL1ToL2MessageCheckpoint(l1ToL2Message);
1538
839
  }
1539
840
  /**
1540
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
+ *
1541
845
  * @param epoch - The epoch at which to get the data.
1542
846
  * @returns The L2 to L1 messages (empty array if the epoch is not found).
1543
- */ async getL2ToL1Messages(epoch) {
1544
- const blocks = await this.blockSource.getBlocks({
1545
- epoch,
1546
- onlyCheckpointed: true
1547
- });
1548
- const blocksInCheckpoints = chunkBy(blocks, (block)=>block.header.globalVariables.slotNumber);
1549
- return blocksInCheckpoints.map((slotBlocks)=>slotBlocks.map((block)=>block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs)));
847
+ */ getL2ToL1Messages(epoch) {
848
+ return this.worldStateQueries.getL2ToL1Messages(epoch);
1550
849
  }
1551
- async getNullifierMembershipWitness(referenceBlock, nullifier) {
1552
- const db = await this.getWorldState(referenceBlock);
1553
- const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [
1554
- nullifier.toBuffer()
1555
- ]);
1556
- if (!witness) {
1557
- return undefined;
1558
- }
1559
- const { index, path } = witness;
1560
- const leafPreimage = await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1561
- if (!leafPreimage) {
1562
- return undefined;
1563
- }
1564
- return new NullifierMembershipWitness(index, leafPreimage, path);
850
+ /**
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);
1565
855
  }
1566
- async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1567
- const committedDb = await this.getWorldState(referenceBlock);
1568
- const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1569
- if (!findResult) {
1570
- return undefined;
1571
- }
1572
- const { index, alreadyPresent } = findResult;
1573
- if (alreadyPresent) {
1574
- throw new Error(`Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`);
1575
- }
1576
- const preimageData = await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1577
- const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1578
- return new NullifierMembershipWitness(BigInt(index), preimageData, siblingPath);
1579
- }
1580
- async getPublicDataWitness(referenceBlock, leafSlot) {
1581
- const committedDb = await this.getWorldState(referenceBlock);
1582
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1583
- if (!lowLeafResult) {
1584
- return undefined;
1585
- } else {
1586
- const preimage = await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1587
- const path = await committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1588
- return new PublicDataWitness(lowLeafResult.index, preimage, path);
1589
- }
856
+ getNullifierMembershipWitness(referenceBlock, nullifier) {
857
+ return this.worldStateQueries.getNullifierMembershipWitness(referenceBlock, nullifier);
1590
858
  }
1591
- async getPublicStorageAt(referenceBlock, contract, slot) {
1592
- const committedDb = await this.getWorldState(referenceBlock);
1593
- const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1594
- const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1595
- if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
1596
- return Fr.ZERO;
1597
- }
1598
- const preimage = await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1599
- return preimage.leaf.value;
859
+ getLowNullifierMembershipWitness(referenceBlock, nullifier) {
860
+ return this.worldStateQueries.getLowNullifierMembershipWitness(referenceBlock, nullifier);
861
+ }
862
+ getPublicDataWitness(referenceBlock, leafSlot) {
863
+ return this.worldStateQueries.getPublicDataWitness(referenceBlock, leafSlot);
864
+ }
865
+ getPublicStorageAt(referenceBlock, contract, slot) {
866
+ return this.worldStateQueries.getPublicStorageAt(referenceBlock, contract, slot);
1600
867
  }
1601
868
  /**
1602
869
  * Simulates the public part of a transaction with the current state.
1603
870
  * @param tx - The transaction to simulate.
1604
871
  * @param skipFeeEnforcement - If true, fee enforcement is skipped.
1605
872
  * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
1606
- **/ async simulatePublicCalls(tx, skipFeeEnforcement = false, overrides) {
1607
- const env = {
1608
- stack: [],
1609
- error: void 0,
1610
- hasError: false
1611
- };
1612
- try {
1613
- // Check total gas limit for simulation
1614
- const gasSettings = tx.data.constants.txContext.gasSettings;
1615
- const txGasLimit = gasSettings.gasLimits.l2Gas;
1616
- const teardownGasLimit = gasSettings.teardownGasLimits.l2Gas;
1617
- if (txGasLimit + teardownGasLimit > this.config.rpcSimulatePublicMaxGasLimit) {
1618
- throw new BadRequestError(`Transaction total gas limit ${txGasLimit + teardownGasLimit} (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${this.config.rpcSimulatePublicMaxGasLimit} for simulation`);
1619
- }
1620
- const txHash = tx.getTxHash();
1621
- const l2Tips = await this.blockSource.getL2Tips();
1622
- const latestBlockNumber = l2Tips.proposed.number;
1623
- const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1624
- // If sequencer is not initialized, we just set these values to zero for simulation.
1625
- const coinbase = EthAddress.ZERO;
1626
- const feeRecipient = AztecAddress.ZERO;
1627
- const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(blockNumber, coinbase, feeRecipient);
1628
- const publicProcessorFactory = new PublicProcessorFactory(this.contractDataSource, new DateProvider(), this.telemetry, this.log.getBindings());
1629
- this.log.verbose(`Simulating public calls for tx ${txHash}`, {
1630
- globalVariables: newGlobalVariables.toInspect(),
1631
- txHash,
1632
- blockNumber
1633
- });
1634
- // Ensure world-state has caught up with the latest block we loaded from the archiver
1635
- await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1636
- // If we detect the next block would start a new checkpoint, then insert L1-to-L2 messages into
1637
- // the world state tree so simulation can take them into account. We detect if the next block would
1638
- // start a new checkpoint by checking if the proposed checkpoint's block number matches the latest block number,
1639
- // which means the next block would be the first block of the next checkpoint.
1640
- const targetCheckpoint = CheckpointNumber((l2Tips.proposedCheckpoint.checkpoint.number ?? CheckpointNumber.ZERO) + 1);
1641
- const nextCheckpointMessages = l2Tips.proposedCheckpoint.block.number === l2Tips.proposed.number ? await this.l1ToL2MessageSource.getL1ToL2Messages(targetCheckpoint).catch((err)=>{
1642
- if (isErrorClass(err, L1ToL2MessagesNotReadyError)) {
1643
- this.log.warn(`L1-to-L2 messages for checkpoint ${targetCheckpoint} are not ready yet (simulating without them)`);
1644
- } else {
1645
- this.log.error(`Failed to get L1-to-L2 messages for checkpoint ${targetCheckpoint} (simulating without them)`, err);
1646
- }
1647
- return undefined;
1648
- }) : undefined;
1649
- const merkleTreeFork = _ts_add_disposable_resource(env, await this.worldStateSynchronizer.fork(latestBlockNumber), true);
1650
- if (nextCheckpointMessages !== undefined) {
1651
- this.log.debug(`Appending ${nextCheckpointMessages.length} L1-to-L2 messages to the world state tree for the next checkpoint`, {
1652
- checkpointNumber: l2Tips.proposedCheckpoint.checkpoint.number + 1
1653
- });
1654
- await appendL1ToL2MessagesToTree(merkleTreeFork, nextCheckpointMessages);
1655
- }
1656
- await applyPublicDataOverrides(merkleTreeFork, overrides?.publicStorage);
1657
- const config = PublicSimulatorConfig.from({
1658
- skipFeeEnforcement,
1659
- collectDebugLogs: true,
1660
- collectHints: false,
1661
- collectCallMetadata: true,
1662
- collectStatistics: false,
1663
- collectionLimits: CollectionLimitsConfig.from({
1664
- maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads
1665
- })
1666
- });
1667
- const contractsDB = new PublicContractsDB(this.contractDataSource, this.log.getBindings());
1668
- if (overrides?.contracts) {
1669
- contractsDB.addContracts(Object.values(overrides.contracts).map(({ instance })=>instance));
1670
- }
1671
- const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config, contractsDB);
1672
- // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1673
- const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([
1674
- tx
1675
- ]);
1676
- // REFACTOR: Consider returning the error rather than throwing
1677
- if (failedTxs.length) {
1678
- this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, {
1679
- txHash
1680
- });
1681
- throw failedTxs[0].error;
1682
- }
1683
- const [processedTx] = processedTxs;
1684
- return new PublicSimulationOutput(processedTx.revertReason, processedTx.globalVariables, processedTx.txEffect, returns, processedTx.gasUsed, debugLogs);
1685
- } catch (e) {
1686
- env.error = e;
1687
- env.hasError = true;
1688
- } finally{
1689
- const result = _ts_dispose_resources(env);
1690
- if (result) await result;
1691
- }
873
+ **/ simulatePublicCalls(tx, skipFeeEnforcement = false, overrides) {
874
+ return this.nodePublicCallsSimulator.simulate(tx, skipFeeEnforcement, overrides);
1692
875
  }
1693
876
  async isValidTx(tx, { isSimulation, skipFeeEnforcement } = {}) {
1694
877
  const db = this.worldStateSynchronizer.getCommitted();
@@ -1697,6 +880,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1697
880
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1698
881
  const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
1699
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);
1700
886
  const validator = createTxValidatorForAcceptingTxsOverRPC(db, this.contractDataSource, verifier, {
1701
887
  timestamp: nextSlotTimestamp,
1702
888
  blockNumber,
@@ -1708,10 +894,10 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1708
894
  ],
1709
895
  gasFees: await this.getCurrentMinFees(),
1710
896
  skipFeeEnforcement,
897
+ isSimulation,
1711
898
  txsPermitted: !this.config.disableTransactions,
1712
- rollupManaLimit: l1Constants.rollupManaLimit,
1713
- maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1714
- maxBlockDAGas: this.config.validateMaxDABlockGas
899
+ maxTxL2Gas: networkTxGasLimits.l2Gas,
900
+ maxTxDAGas: networkTxGasLimits.daGas
1715
901
  }, this.log.getBindings());
1716
902
  return await validator.validateTx(tx);
1717
903
  }
@@ -2013,73 +1199,29 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
2013
1199
  });
2014
1200
  }
2015
1201
  }
2016
- /**
2017
- * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
2018
- * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
2019
- * @returns An instance of a committed MerkleTreeOperations
2020
- */ async getWorldState(block) {
2021
- const query = this.normalizeBlockParameter(block);
2022
- // When the request anchors on a specific block hash, resolve it against the archiver up front and
2023
- // drive the world-state sync to that exact block number and hash. Resolving against the archiver
2024
- // first fails fast with a clear reorg error if the hash is unknown, and passing the hash to the
2025
- // synchronizer makes the sync reorg-aware: it barriers until the archive-tree commit for that block
2026
- // has landed and verifies it matches the requested fork, instead of syncing to bare latest height
2027
- // and then racing the snapshot read below against an in-flight archive-tree write.
2028
- const requestedHash = 'hash' in query ? query.hash : undefined;
2029
- const anchorBlockNumber = requestedHash !== undefined ? await this.resolveBlockNumber(query) : undefined;
2030
- let blockSyncedTo = BlockNumber.ZERO;
2031
- try {
2032
- // Attempt to sync the world state if necessary
2033
- blockSyncedTo = await this.#syncWorldState(anchorBlockNumber, requestedHash);
2034
- } catch (err) {
2035
- this.log.error(`Error getting world state: ${err}`);
1202
+ async prove(upToCheckpoint) {
1203
+ if (!this.automineSequencer) {
1204
+ throw new BadRequestError('Cannot prove checkpoint: no automine sequencer is running');
2036
1205
  }
2037
- if ('tag' in query && query.tag === 'proposed') {
2038
- this.log.debug(`Using committed db for latest block, world state synced upto ${blockSyncedTo}`);
2039
- return this.worldStateSynchronizer.getCommitted();
2040
- }
2041
- const blockNumber = anchorBlockNumber ?? await this.resolveBlockNumber(query);
2042
- // Check it's within world state sync range
2043
- if (blockNumber > blockSyncedTo) {
2044
- throw new Error(`Queried block ${inspectBlockParameter(block)} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
2045
- }
2046
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
2047
- const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
2048
- // Double-check world-state synced to the same block hash as was requested.
2049
- // Block 0 is skipped: the snapshot returned by `getSnapshot(0)` is the *pre*-genesis archive
2050
- // (size 0), so leaf 0 is not yet inserted from that snapshot's view even though block 0's hash
2051
- // does live at archive index 0 in the committed tree. The genesis hash is already validated by
2052
- // the archiver when it resolves the hash query to block number 0.
2053
- if (requestedHash !== undefined && blockNumber !== BlockNumber.ZERO) {
2054
- const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
2055
- if (!blockHash || !requestedHash.equals(blockHash)) {
2056
- throw new Error(`Block hash ${requestedHash.toString()} not found in world state at block number ${blockNumber} (world state has ${blockHash?.toString() ?? 'no hash'} at that index, genesis header hash is ${this.blockSource.getGenesisBlockHash().toString()}). If the node API has been queried with anchor block hash possibly a reorg has occurred.`);
2057
- }
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');
2058
1211
  }
2059
- return snapshot;
2060
- }
2061
- /** Resolves any {@link BlockParameter} variant to a concrete block number. */ async resolveBlockNumber(block) {
2062
- const query = this.normalizeBlockParameter(block);
2063
- const blockNumber = await this.blockSource.getBlockNumber(query);
2064
- if (blockNumber === undefined) {
2065
- if ('hash' in query) {
2066
- throw new Error(`Block hash ${query.hash.toString()} not found when querying world state. If the node API has been queried with anchor block hash possibly a reorg has occurred.`);
2067
- }
2068
- if ('archive' in query) {
2069
- throw new Error(`Block with archive ${query.archive.toString()} not found.`);
2070
- }
2071
- throw new Error(`Block not found for ${inspectBlockParameter(block)}.`);
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');
2072
1217
  }
2073
- return blockNumber;
1218
+ await this.automineSequencer.warpBy(duration);
2074
1219
  }
2075
1220
  /**
2076
- * Ensure the world state is synced.
2077
- * @param targetBlockNumber - Block to sync up to. Defaults to the latest block known to the archiver.
2078
- * @param blockHash - If provided, the synchronizer verifies the block at `targetBlockNumber` matches this
2079
- * hash, resyncing (and so detecting reorgs) if it does not yet match or has been reorged away.
2080
- * @returns A promise that fulfils once the world state is synced
2081
- */ async #syncWorldState(targetBlockNumber, blockHash) {
2082
- const target = targetBlockNumber ?? await this.blockSource.getBlockNumber();
2083
- return await this.worldStateSynchronizer.syncImmediate(target, blockHash);
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);
2084
1226
  }
2085
1227
  }