@aztec/aztec-node 0.0.1-commit.85d7d01 → 0.0.1-commit.8655d4a

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 (37) 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 +8 -5
  5. package/dest/aztec-node/config.d.ts.map +1 -1
  6. package/dest/aztec-node/config.js +6 -6
  7. package/dest/aztec-node/public_data_overrides.d.ts +13 -0
  8. package/dest/aztec-node/public_data_overrides.d.ts.map +1 -0
  9. package/dest/aztec-node/public_data_overrides.js +21 -0
  10. package/dest/aztec-node/server.d.ts +65 -106
  11. package/dest/aztec-node/server.d.ts.map +1 -1
  12. package/dest/aztec-node/server.js +972 -498
  13. package/dest/sentinel/config.d.ts +3 -2
  14. package/dest/sentinel/config.d.ts.map +1 -1
  15. package/dest/sentinel/config.js +15 -5
  16. package/dest/sentinel/factory.d.ts +5 -3
  17. package/dest/sentinel/factory.d.ts.map +1 -1
  18. package/dest/sentinel/factory.js +4 -4
  19. package/dest/sentinel/sentinel.d.ts +133 -9
  20. package/dest/sentinel/sentinel.d.ts.map +1 -1
  21. package/dest/sentinel/sentinel.js +215 -73
  22. package/dest/sentinel/store.d.ts +8 -8
  23. package/dest/sentinel/store.d.ts.map +1 -1
  24. package/dest/sentinel/store.js +25 -17
  25. package/dest/test/index.d.ts +3 -3
  26. package/dest/test/index.d.ts.map +1 -1
  27. package/package.json +27 -27
  28. package/src/aztec-node/block_response_helpers.ts +161 -0
  29. package/src/aztec-node/config.ts +12 -8
  30. package/src/aztec-node/public_data_overrides.ts +35 -0
  31. package/src/aztec-node/server.ts +1036 -610
  32. package/src/sentinel/README.md +103 -0
  33. package/src/sentinel/config.ts +18 -6
  34. package/src/sentinel/factory.ts +8 -5
  35. package/src/sentinel/sentinel.ts +270 -85
  36. package/src/sentinel/store.ts +26 -18
  37. package/src/test/index.ts +2 -2
@@ -1,3 +1,68 @@
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
+ }
1
66
  function applyDecs2203RFactory() {
2
67
  function createAddInitializerMethod(initializers, decoratorFinishedRef) {
3
68
  return function addInitializer(initializer) {
@@ -371,23 +436,27 @@ function _apply_decs_2203_r(targetClass, memberDecs, classDecs, parentClass) {
371
436
  return (_apply_decs_2203_r = applyDecs2203RFactory())(targetClass, memberDecs, classDecs, parentClass);
372
437
  }
373
438
  var _dec, _initProto;
374
- import { createArchiver } from '@aztec/archiver';
375
- import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
439
+ import { L1ToL2MessagesNotReadyError, createArchiver } from '@aztec/archiver';
440
+ import { BBCircuitVerifier, BatchChonkVerifier, QueuedIVCVerifier } from '@aztec/bb-prover';
441
+ import { TestCircuitVerifier } from '@aztec/bb-prover/test';
376
442
  import { createBlobClientWithFileStores } from '@aztec/blob-client/client';
377
443
  import { Blob } from '@aztec/blob-lib';
378
444
  import { EpochCache } from '@aztec/epoch-cache';
379
445
  import { createEthereumChain } from '@aztec/ethereum/chain';
380
- import { getPublicClient } from '@aztec/ethereum/client';
446
+ import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
381
447
  import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
382
- import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
383
- import { compactArray, pick, unique } from '@aztec/foundation/collection';
448
+ 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';
384
451
  import { Fr } from '@aztec/foundation/curves/bn254';
385
452
  import { EthAddress } from '@aztec/foundation/eth-address';
386
453
  import { BadRequestError } from '@aztec/foundation/json-rpc';
387
454
  import { createLogger } from '@aztec/foundation/log';
455
+ import { retryUntil } from '@aztec/foundation/retry';
388
456
  import { count } from '@aztec/foundation/string';
389
457
  import { DateProvider, Timer } from '@aztec/foundation/timer';
390
458
  import { MembershipWitness } from '@aztec/foundation/trees';
459
+ import { isErrorClass } from '@aztec/foundation/types';
391
460
  import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
392
461
  import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
393
462
  import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
@@ -395,28 +464,33 @@ import { createP2PClient, createTxValidatorForAcceptingTxsOverRPC, getDefaultAll
395
464
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
396
465
  import { createProverNode } from '@aztec/prover-node';
397
466
  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';
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
+ import { STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS } from '@aztec/standard-contracts/multi-call-entrypoint';
401
471
  import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
402
472
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
403
- import { BlockHash, L2Block } from '@aztec/stdlib/block';
473
+ import { BlockHash, BlockTag, inspectBlockParameter } from '@aztec/stdlib/block';
474
+ import { CheckpointReexecutionTracker } from '@aztec/stdlib/checkpoint';
404
475
  import { GasFees } from '@aztec/stdlib/gas';
405
476
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
406
477
  import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
407
478
  import { tryStop } from '@aztec/stdlib/interfaces/server';
408
479
  import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
409
- import { InboxLeaf } from '@aztec/stdlib/messaging';
480
+ import { InboxLeaf, appendL1ToL2MessagesToTree } from '@aztec/stdlib/messaging';
481
+ import { MIN_EXECUTION_TIME } from '@aztec/stdlib/timetable';
410
482
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
411
483
  import { PublicSimulationOutput, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
412
484
  import { getPackageVersion } from '@aztec/stdlib/update-checker';
413
485
  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';
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';
417
489
  import { createSentinel } from '../sentinel/factory.js';
490
+ import { blockResponseFromBlockData, blockResponseFromL2Block, checkpointResponseFromCheckpointData, checkpointResponseFromPublishedCheckpoint, projectProposedToCheckpointResponse } from './block_response_helpers.js';
418
491
  import { createKeyStoreForValidator } from './config.js';
419
492
  import { NodeMetrics } from './node_metrics.js';
493
+ import { applyPublicDataOverrides } from './public_data_overrides.js';
420
494
  _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
421
495
  [Attributes.TX_HASH]: tx.getTxHash().toString()
422
496
  }));
@@ -434,19 +508,22 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
434
508
  proverNode;
435
509
  slasherClient;
436
510
  validatorsSentinel;
437
- epochPruneWatcher;
511
+ stopStartedWatchers;
438
512
  l1ChainId;
439
513
  version;
440
514
  globalVariableBuilder;
515
+ feeProvider;
441
516
  epochCache;
442
517
  packageVersion;
443
- proofVerifier;
518
+ peerProofVerifier;
519
+ rpcProofVerifier;
444
520
  telemetry;
445
521
  log;
446
522
  blobClient;
447
523
  validatorClient;
448
524
  keyStoreManager;
449
525
  debugLogStore;
526
+ automineSequencer;
450
527
  static{
451
528
  ({ e: [_initProto] } = _apply_decs_2203_r(this, [
452
529
  [
@@ -457,11 +534,12 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
457
534
  ], []));
458
535
  }
459
536
  metrics;
460
- initialHeaderHashPromise;
461
537
  // Prevent two snapshot operations to happen simultaneously
462
538
  isUploadingSnapshot;
539
+ // Saved minTxsPerBlock used by `pauseSequencer` to restore production-sequencer config on resume.
540
+ sequencerPausedMinTxsPerBlock;
463
541
  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()){
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){
465
543
  this.config = config;
466
544
  this.p2pClient = p2pClient;
467
545
  this.blockSource = blockSource;
@@ -473,25 +551,27 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
473
551
  this.proverNode = proverNode;
474
552
  this.slasherClient = slasherClient;
475
553
  this.validatorsSentinel = validatorsSentinel;
476
- this.epochPruneWatcher = epochPruneWatcher;
554
+ this.stopStartedWatchers = stopStartedWatchers;
477
555
  this.l1ChainId = l1ChainId;
478
556
  this.version = version;
479
557
  this.globalVariableBuilder = globalVariableBuilder;
558
+ this.feeProvider = feeProvider;
480
559
  this.epochCache = epochCache;
481
560
  this.packageVersion = packageVersion;
482
- this.proofVerifier = proofVerifier;
561
+ this.peerProofVerifier = peerProofVerifier;
562
+ this.rpcProofVerifier = rpcProofVerifier;
483
563
  this.telemetry = telemetry;
484
564
  this.log = log;
485
565
  this.blobClient = blobClient;
486
566
  this.validatorClient = validatorClient;
487
567
  this.keyStoreManager = keyStoreManager;
488
568
  this.debugLogStore = debugLogStore;
489
- this.initialHeaderHashPromise = (_initProto(this), undefined);
490
- this.isUploadingSnapshot = false;
569
+ this.automineSequencer = automineSequencer;
570
+ this.isUploadingSnapshot = (_initProto(this), false);
491
571
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
492
572
  this.tracer = telemetry.getTracer('AztecNodeService');
493
573
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
494
- this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
574
+ this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, pickL1ContractAddresses(config));
495
575
  // A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
496
576
  // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
497
577
  // memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
@@ -499,12 +579,249 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
499
579
  throw new Error('debugLogStore should never be enabled when realProofs are set');
500
580
  }
501
581
  }
582
+ /** @internal Exposed for testing — returns the RPC proof verifier. */ getProofVerifier() {
583
+ return this.rpcProofVerifier;
584
+ }
502
585
  async getWorldStateSyncStatus() {
503
586
  const status = await this.worldStateSynchronizer.status();
504
587
  return status.syncSummary;
505
588
  }
506
- getL2Tips() {
507
- return this.blockSource.getL2Tips();
589
+ async getChainTips() {
590
+ const { proposed, checkpointed, proven, finalized } = await this.blockSource.getL2Tips();
591
+ return {
592
+ proposed,
593
+ checkpointed,
594
+ proven,
595
+ finalized
596
+ };
597
+ }
598
+ getCheckpointsData(query) {
599
+ return this.blockSource.getCheckpointsData(query);
600
+ }
601
+ async getBlockNumber(tip) {
602
+ if (tip === undefined || tip === 'proposed') {
603
+ return this.blockSource.getBlockNumber();
604
+ }
605
+ return await this.blockSource.getBlockNumber({
606
+ tag: tip
607
+ }) ?? BlockNumber.ZERO;
608
+ }
609
+ async getCheckpointNumber(tip) {
610
+ const tips = await this.blockSource.getL2Tips();
611
+ switch(tip){
612
+ case undefined:
613
+ case 'checkpointed':
614
+ return tips.checkpointed.checkpoint.number;
615
+ case 'proposed':
616
+ return tips.proposedCheckpoint.checkpoint.number;
617
+ case 'proven':
618
+ return tips.proven.checkpoint.number;
619
+ case 'finalized':
620
+ return tips.finalized.checkpoint.number;
621
+ }
622
+ }
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);
757
+ }
758
+ 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;
811
+ }
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));
508
825
  }
509
826
  /**
510
827
  * initializes the Aztec Node, wait for component to sync.
@@ -515,7 +832,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
515
832
  ...inputConfig
516
833
  }; // Copy the config so we dont mutate the input object
517
834
  const log = deps.logger ?? createLogger('node');
518
- const packageVersion = getPackageVersion() ?? '';
835
+ const packageVersion = getPackageVersion();
519
836
  const telemetry = deps.telemetry ?? getTelemetryClient();
520
837
  const dateProvider = deps.dateProvider ?? new DateProvider();
521
838
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
@@ -559,22 +876,19 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
559
876
  }
560
877
  const publicClient = createPublicClient({
561
878
  chain: ethereumChain.chainInfo,
562
- transport: fallback(config.l1RpcUrls.map((url)=>http(url, {
563
- batch: false
564
- }))),
879
+ transport: makeL1HttpTransport(config.l1RpcUrls, {
880
+ timeout: config.l1HttpTimeoutMS
881
+ }),
565
882
  pollingInterval: config.viemPollingIntervalMS
566
883
  });
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([
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([
575
888
  rollupContract.getL1GenesisTime(),
576
889
  rollupContract.getSlotDuration(),
577
- rollupContract.getVersion()
890
+ rollupContract.getVersion(),
891
+ rollupContract.getManaLimit().then(Number)
578
892
  ]);
579
893
  config.rollupVersion ??= Number(rollupVersionFromRollup);
580
894
  if (config.rollupVersion !== Number(rollupVersionFromRollup)) {
@@ -583,199 +897,335 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
583
897
  const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
584
898
  // attempt snapshot sync if possible
585
899
  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,
900
+ const epochCache = await EpochCache.create(config.rollupAddress, config, {
593
901
  dateProvider
594
- }, {
595
- blockUntilSync: !config.skipArchiverInitialSync
596
902
  });
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 should really not be modifying the config object
616
- config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
617
- // We'll accumulate sentinel watchers here
618
- const watchers = [];
619
- // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation
620
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder({
621
- ...config,
622
- l1GenesisTime,
623
- slotDuration: Number(slotDuration)
624
- }, worldStateSynchronizer, archiver, dateProvider, telemetry);
625
- let validatorClient;
626
- if (!proverOnly) {
627
- // Create validator client if required
628
- validatorClient = await createValidatorClient(config, {
629
- checkpointsBuilder: validatorCheckpointsBuilder,
630
- worldState: worldStateSynchronizer,
631
- p2pClient,
632
- telemetry,
633
- dateProvider,
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,
634
915
  epochCache,
635
- blockSource: archiver,
636
- l1ToL2MessageSource: archiver,
637
- keyStoreManager,
638
- blobClient
639
- });
640
- // If we have a validator client, register it as a source of offenses for the slasher,
641
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
642
- // like attestations or auths will fail.
643
- if (validatorClient) {
644
- watchers.push(validatorClient);
645
- if (!options.dontStartSequencer) {
646
- await validatorClient.registerHandlers();
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
+ }
647
1002
  }
648
1003
  }
649
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
650
- // create a BlockProposalHandler to reexecute block proposals for monitoring
651
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
652
- log.info('Setting up block proposal reexecution for monitoring');
653
- createBlockProposalHandler(config, {
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, {
654
1012
  checkpointsBuilder: validatorCheckpointsBuilder,
655
1013
  worldState: worldStateSynchronizer,
656
1014
  epochCache,
657
1015
  blockSource: archiver,
658
1016
  l1ToL2MessageSource: archiver,
659
1017
  p2pClient,
1018
+ blobClient,
660
1019
  dateProvider,
661
- telemetry
662
- }).registerForReexecution(p2pClient);
663
- }
664
- }
665
- // Start world state and wait for it to sync to the archiver.
666
- await worldStateSynchronizer.start();
667
- // Start p2p. Note that it depends on world state to be running.
668
- await p2pClient.start();
669
- let validatorsSentinel;
670
- let epochPruneWatcher;
671
- let attestationsBlockWatcher;
672
- if (!proverOnly) {
673
- validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
674
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
675
- watchers.push(validatorsSentinel);
676
- }
677
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
678
- epochPruneWatcher = new EpochPruneWatcher(archiver, archiver, epochCache, p2pClient.getTxProvider(), validatorCheckpointsBuilder, config);
679
- watchers.push(epochPruneWatcher);
680
- }
681
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
682
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
683
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
684
- watchers.push(attestationsBlockWatcher);
1020
+ telemetry,
1021
+ reexecutionTracker
1022
+ }).register(p2pClient, reexecute, archiver);
685
1023
  }
686
- }
687
- // Start p2p-related services once the archiver has completed sync
688
- void archiver.waitForInitialSync().then(async ()=>{
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.
689
1027
  await p2pClient.start();
690
- await validatorsSentinel?.start();
691
- await epochPruneWatcher?.start();
692
- await attestationsBlockWatcher?.start();
693
- log.info(`All p2p services started`);
694
- }).catch((err)=>log.error('Failed to start p2p services after archiver sync', err));
695
- // Validator enabled, create/start relevant service
696
- let sequencer;
697
- let slasherClient;
698
- if (!config.disableValidator && validatorClient) {
699
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
700
- // as they are executed when the node is selected as proposer.
701
- const validatorAddresses = keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses() : [];
702
- slasherClient = await createSlasher(config, config.l1Contracts, getPublicClient(config), watchers, dateProvider, epochCache, validatorAddresses, undefined);
703
- await slasherClient.start();
704
- const l1TxUtils = config.sequencerPublisherForwarderAddress ? await createForwarderL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), config.sequencerPublisherForwarderAddress, {
705
- ...config,
706
- scope: 'sequencer'
707
- }, {
708
- telemetry,
709
- logger: log.createChild('l1-tx-utils'),
710
- dateProvider,
711
- kzg: Blob.getViemKzgInstance()
712
- }) : await createL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
713
- ...config,
714
- scope: 'sequencer'
715
- }, {
716
- telemetry,
717
- logger: log.createChild('l1-tx-utils'),
718
- dateProvider,
719
- kzg: Blob.getViemKzgInstance()
720
- });
721
- // Create and start the sequencer client
722
- const checkpointsBuilder = new CheckpointsBuilder({
723
- ...config,
724
- l1GenesisTime,
725
- slotDuration: Number(slotDuration)
726
- }, worldStateSynchronizer, archiver, dateProvider, telemetry, debugLogStore);
727
- sequencer = await SequencerClient.new(config, {
728
- ...deps,
729
- epochCache,
730
- l1TxUtils,
731
- validatorClient,
732
- p2pClient,
733
- worldStateSynchronizer,
734
- slasherClient,
735
- checkpointsBuilder,
736
- l2BlockSource: archiver,
737
- l1ToL2MessageSource: archiver,
738
- telemetry,
739
- dateProvider,
740
- blobClient,
741
- nodeKeyStore: keyStoreManager
742
- });
743
- }
744
- if (!options.dontStartSequencer && sequencer) {
745
- await sequencer.start();
746
- log.verbose(`Sequencer started`);
747
- } else if (sequencer) {
748
- log.warn(`Sequencer created but not started`);
749
- }
750
- // Create prover node subsystem if enabled
751
- let proverNode;
752
- if (config.enableProverNode) {
753
- proverNode = await createProverNode(config, {
754
- ...deps.proverNodeDeps,
755
- telemetry,
756
- dateProvider,
757
- archiver,
758
- worldStateSynchronizer,
759
- p2pClient,
760
- epochCache,
761
- blobClient,
762
- keyStoreManager
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
763
1081
  });
764
- if (!options.dontStartProverNode) {
765
- await proverNode.start();
766
- log.info(`Prover node subsystem started`);
767
- } else {
768
- log.info(`Prover node subsystem created but not started`);
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`);
769
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;
770
1228
  }
771
- const globalVariableBuilder = new GlobalVariableBuilder({
772
- ...config,
773
- rollupVersion: BigInt(config.rollupVersion),
774
- l1GenesisTime,
775
- slotDuration: Number(slotDuration)
776
- });
777
- 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);
778
- return node;
779
1229
  }
780
1230
  /**
781
1231
  * Returns the sequencer client instance.
@@ -783,6 +1233,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
783
1233
  */ getSequencer() {
784
1234
  return this.sequencer;
785
1235
  }
1236
+ /** Test-only: returns the AutomineSequencer when wired via `useAutomineSequencer`. */ getAutomineSequencer() {
1237
+ return this.automineSequencer;
1238
+ }
786
1239
  /** Returns the prover node subsystem, if enabled. */ getProverNode() {
787
1240
  return this.proverNode;
788
1241
  }
@@ -799,13 +1252,16 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
799
1252
  * Method to return the currently deployed L1 contract addresses.
800
1253
  * @returns - The currently deployed L1 contract addresses.
801
1254
  */ getL1ContractAddresses() {
802
- return Promise.resolve(this.config.l1Contracts);
1255
+ return Promise.resolve(pickL1ContractAddresses(this.config));
803
1256
  }
804
1257
  getEncodedEnr() {
805
1258
  return Promise.resolve(this.p2pClient.getEnr()?.encodeTxt());
806
1259
  }
807
1260
  async getAllowedPublicSetup() {
808
- return this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions();
1261
+ return [
1262
+ ...await getDefaultAllowedSetupFunctions(),
1263
+ ...this.config.txPublicSetupAllowListExtend ?? []
1264
+ ];
809
1265
  }
810
1266
  /**
811
1267
  * Method to determine if the node is ready to accept transactions.
@@ -833,61 +1289,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
833
1289
  };
834
1290
  return nodeInfo;
835
1291
  }
836
- /**
837
- * Get a block specified by its block number, block hash, or 'latest'.
838
- * @param block - The block parameter (block number, block hash, or 'latest').
839
- * @returns The requested block.
840
- */ async getBlock(block) {
841
- if (BlockHash.isBlockHash(block)) {
842
- return this.getBlockByHash(block);
843
- }
844
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
845
- if (blockNumber === BlockNumber.ZERO) {
846
- return this.buildInitialBlock();
847
- }
848
- return await this.blockSource.getL2Block(blockNumber);
1292
+ async getCurrentMinFees() {
1293
+ return await this.feeProvider.getCurrentMinFees();
849
1294
  }
850
- /**
851
- * Get a block specified by its hash.
852
- * @param blockHash - The block hash being requested.
853
- * @returns The requested block.
854
- */ async getBlockByHash(blockHash) {
855
- const initialBlockHash = await this.#getInitialHeaderHash();
856
- if (blockHash.equals(initialBlockHash)) {
857
- return this.buildInitialBlock();
858
- }
859
- return await this.blockSource.getL2BlockByHash(blockHash);
860
- }
861
- buildInitialBlock() {
862
- const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
863
- return L2Block.empty(initialHeader);
864
- }
865
- /**
866
- * Get a block specified by its archive root.
867
- * @param archive - The archive root being requested.
868
- * @returns The requested block.
869
- */ async getBlockByArchive(archive) {
870
- return await this.blockSource.getL2BlockByArchive(archive);
871
- }
872
- /**
873
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
874
- * @param from - The start of the range of blocks to return.
875
- * @param limit - The maximum number of blocks to obtain.
876
- * @returns The blocks requested.
877
- */ async getBlocks(from, limit) {
878
- return await this.blockSource.getBlocks(from, BlockNumber(limit)) ?? [];
879
- }
880
- async getCheckpoints(from, limit) {
881
- return await this.blockSource.getCheckpoints(from, limit) ?? [];
882
- }
883
- async getCheckpointedBlocks(from, limit) {
884
- return await this.blockSource.getCheckpointedBlocks(from, limit) ?? [];
885
- }
886
- /**
887
- * Method to fetch the current min L2 fees.
888
- * @returns The current min L2 fees.
889
- */ async getCurrentMinFees() {
890
- return await this.globalVariableBuilder.getCurrentMinFees();
1295
+ /** Returns predicted min fees for the current slot and next N slots. */ async getPredictedMinFees(manaUsage) {
1296
+ return await this.feeProvider.getPredictedMinFees(manaUsage);
891
1297
  }
892
1298
  async getMaxPriorityFees() {
893
1299
  for await (const tx of this.p2pClient.iteratePendingTxs()){
@@ -899,18 +1305,6 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
899
1305
  });
900
1306
  }
901
1307
  /**
902
- * Method to fetch the latest block number synchronized by the node.
903
- * @returns The block number.
904
- */ async getBlockNumber() {
905
- return await this.blockSource.getBlockNumber();
906
- }
907
- async getProvenBlockNumber() {
908
- return await this.blockSource.getProvenBlockNumber();
909
- }
910
- async getCheckpointedBlockNumber() {
911
- return await this.blockSource.getCheckpointedL2BlockNumber();
912
- }
913
- /**
914
1308
  * Method to fetch the version of the package.
915
1309
  * @returns The node package version
916
1310
  */ getNodeVersion() {
@@ -934,43 +1328,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
934
1328
  getContract(address) {
935
1329
  return this.contractDataSource.getContract(address);
936
1330
  }
937
- async getPrivateLogsByTags(tags, page, referenceBlock) {
938
- if (referenceBlock) {
939
- const initialBlockHash = await this.#getInitialHeaderHash();
940
- if (!referenceBlock.equals(initialBlockHash)) {
941
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
942
- if (!header) {
943
- throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
944
- }
945
- }
946
- }
947
- return this.logsSource.getPrivateLogsByTags(tags, page);
948
- }
949
- async getPublicLogsByTagsFromContract(contractAddress, tags, page, referenceBlock) {
950
- if (referenceBlock) {
951
- const initialBlockHash = await this.#getInitialHeaderHash();
952
- if (!referenceBlock.equals(initialBlockHash)) {
953
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
954
- if (!header) {
955
- throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
956
- }
957
- }
958
- }
959
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
960
- }
961
- /**
962
- * Gets public logs based on the provided filter.
963
- * @param filter - The filter to apply to the logs.
964
- * @returns The requested logs.
965
- */ getPublicLogs(filter) {
966
- return this.logsSource.getPublicLogs(filter);
1331
+ getPrivateLogsByTags(query) {
1332
+ return this.logsSource.getPrivateLogsByTags(query);
967
1333
  }
968
- /**
969
- * Gets contract class logs based on the provided filter.
970
- * @param filter - The filter to apply to the logs.
971
- * @returns The requested logs.
972
- */ getContractClassLogs(filter) {
973
- return this.logsSource.getContractClassLogs(filter);
1334
+ getPublicLogsByTags(query) {
1335
+ return this.logsSource.getPublicLogsByTags(query);
974
1336
  }
975
1337
  /**
976
1338
  * Method to submit a transaction to the p2p pool.
@@ -990,7 +1352,15 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
990
1352
  });
991
1353
  throw new Error(`Invalid tx: ${reason}`);
992
1354
  }
993
- await this.p2pClient.sendTx(tx);
1355
+ try {
1356
+ await this.p2pClient.sendTx(tx);
1357
+ } catch (err) {
1358
+ this.metrics.receivedTx(timer.ms(), false);
1359
+ this.log.warn(`Mempool rejected tx ${txHash}: ${err.message}`, {
1360
+ txHash
1361
+ });
1362
+ throw err;
1363
+ }
994
1364
  const duration = timer.ms();
995
1365
  this.metrics.receivedTx(duration, true);
996
1366
  this.log.info(`Received tx ${txHash} in ${duration}ms`, {
@@ -1011,10 +1381,10 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1011
1381
  // If the tx is in the pool but not in the archiver, it's pending.
1012
1382
  // This handles race conditions between archiver and p2p, where the archiver
1013
1383
  // has pruned the block in which a tx was mined, but p2p has not caught up yet.
1014
- receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
1384
+ receipt = new TxReceipt(txHash, TxStatus.PENDING, /*executionResult=*/ undefined, /*error=*/ undefined);
1015
1385
  } else {
1016
1386
  // Otherwise, if we don't know the tx, we consider it dropped.
1017
- receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
1387
+ receipt = new TxReceipt(txHash, TxStatus.DROPPED, /*executionResult=*/ undefined, /*error=*/ 'Tx dropped by P2P node');
1018
1388
  }
1019
1389
  this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
1020
1390
  return receipt;
@@ -1026,11 +1396,14 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1026
1396
  * Method to stop the aztec node.
1027
1397
  */ async stop() {
1028
1398
  this.log.info(`Stopping Aztec Node`);
1029
- await tryStop(this.validatorsSentinel);
1030
- await tryStop(this.epochPruneWatcher);
1399
+ await this.stopStartedWatchers();
1031
1400
  await tryStop(this.slasherClient);
1032
- await tryStop(this.proofVerifier);
1401
+ await Promise.all([
1402
+ tryStop(this.peerProofVerifier),
1403
+ tryStop(this.rpcProofVerifier)
1404
+ ]);
1033
1405
  await tryStop(this.sequencer);
1406
+ await tryStop(this.automineSequencer);
1034
1407
  await tryStop(this.proverNode);
1035
1408
  await tryStop(this.p2pClient);
1036
1409
  await tryStop(this.worldStateSynchronizer);
@@ -1071,70 +1444,82 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1071
1444
  return compactArray(await Promise.all(txHashes.map((txHash)=>this.getTxByHash(txHash))));
1072
1445
  }
1073
1446
  async findLeavesIndexes(referenceBlock, treeId, leafValues) {
1074
- const committedDb = await this.#getWorldState(referenceBlock);
1447
+ const committedDb = await this.getWorldState(referenceBlock);
1075
1448
  const maybeIndices = await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
1076
- // We filter out undefined values
1077
- const indices = maybeIndices.filter((x)=>x !== undefined);
1078
- // Now we find the block numbers for the indices
1079
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
1080
- // If any of the block numbers are undefined, we throw an error.
1081
- for(let i = 0; i < indices.length; i++){
1082
- if (blockNumbers[i] === undefined) {
1083
- throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
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]}`);
1084
1459
  }
1460
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
1085
1461
  }
1086
1462
  // Get unique block numbers in order to optimize num calls to getLeafValue function.
1087
1463
  const uniqueBlockNumbers = [
1088
- ...new Set(blockNumbers.filter((x)=>x !== undefined))
1464
+ ...new Set(indexToBlockNumber.values())
1089
1465
  ];
1090
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
1091
- // (note that block number corresponds to the leaf index in the archive tree).
1466
+ // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
1092
1467
  const blockHashes = await Promise.all(uniqueBlockNumbers.map((blockNumber)=>{
1093
1468
  return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1094
1469
  }));
1095
- // If any of the block hashes are undefined, we throw an error.
1470
+ // Build a map from block number to block hash
1471
+ const blockNumberToHash = new Map();
1096
1472
  for(let i = 0; i < uniqueBlockNumbers.length; i++){
1097
- if (blockHashes[i] === undefined) {
1473
+ const blockHash = blockHashes[i];
1474
+ if (blockHash === undefined) {
1098
1475
  throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
1099
1476
  }
1477
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
1100
1478
  }
1101
1479
  // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
1102
- return maybeIndices.map((index, i)=>{
1480
+ return maybeIndices.map((index)=>{
1103
1481
  if (index === undefined) {
1104
1482
  return undefined;
1105
1483
  }
1106
- const blockNumber = blockNumbers[i];
1484
+ const blockNumber = indexToBlockNumber.get(index);
1107
1485
  if (blockNumber === undefined) {
1108
- return undefined;
1486
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1109
1487
  }
1110
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
1111
- const blockHash = blockHashes[blockHashIndex];
1112
- if (!blockHash) {
1113
- return undefined;
1488
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
1489
+ if (l2BlockHash === undefined) {
1490
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
1114
1491
  }
1115
1492
  return {
1116
- l2BlockNumber: BlockNumber(Number(blockNumber)),
1117
- l2BlockHash: new BlockHash(blockHash),
1493
+ l2BlockNumber: blockNumber,
1494
+ l2BlockHash,
1118
1495
  data: index
1119
1496
  };
1120
1497
  });
1121
1498
  }
1122
1499
  async getBlockHashMembershipWitness(referenceBlock, blockHash) {
1123
- const committedDb = await this.#getWorldState(referenceBlock);
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));
1124
1509
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE, [
1125
1510
  blockHash
1126
1511
  ]);
1127
1512
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1128
1513
  }
1129
1514
  async getNoteHashMembershipWitness(referenceBlock, noteHash) {
1130
- const committedDb = await this.#getWorldState(referenceBlock);
1515
+ const committedDb = await this.getWorldState(referenceBlock);
1131
1516
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE, [
1132
1517
  noteHash
1133
1518
  ]);
1134
1519
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1135
1520
  }
1136
1521
  async getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
1137
- const db = await this.#getWorldState(referenceBlock);
1522
+ const db = await this.getWorldState(referenceBlock);
1138
1523
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
1139
1524
  l1ToL2Message
1140
1525
  ]);
@@ -1147,42 +1532,24 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1147
1532
  witness.path
1148
1533
  ];
1149
1534
  }
1150
- async getL1ToL2MessageBlock(l1ToL2Message) {
1151
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1152
- return messageIndex ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex)) : undefined;
1153
- }
1154
- /**
1155
- * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
1156
- * @param l1ToL2Message - The L1 to L2 message to check.
1157
- * @returns Whether the message is synced and ready to be included in a block.
1158
- */ async isL1ToL2MessageSynced(l1ToL2Message) {
1535
+ async getL1ToL2MessageCheckpoint(l1ToL2Message) {
1159
1536
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1160
- return messageIndex !== undefined;
1537
+ return messageIndex !== undefined ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1161
1538
  }
1162
1539
  /**
1163
1540
  * Returns all the L2 to L1 messages in an epoch.
1164
1541
  * @param epoch - The epoch at which to get the data.
1165
1542
  * @returns The L2 to L1 messages (empty array if the epoch is not found).
1166
1543
  */ async getL2ToL1Messages(epoch) {
1167
- // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1168
- const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1169
- const blocksInCheckpoints = [];
1170
- let previousSlotNumber = SlotNumber.ZERO;
1171
- let checkpointIndex = -1;
1172
- for (const checkpointedBlock of checkpointedBlocks){
1173
- const block = checkpointedBlock.block;
1174
- const slotNumber = block.header.globalVariables.slotNumber;
1175
- if (slotNumber !== previousSlotNumber) {
1176
- checkpointIndex++;
1177
- blocksInCheckpoints.push([]);
1178
- previousSlotNumber = slotNumber;
1179
- }
1180
- blocksInCheckpoints[checkpointIndex].push(block);
1181
- }
1182
- return blocksInCheckpoints.map((blocks)=>blocks.map((block)=>block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs)));
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)));
1183
1550
  }
1184
1551
  async getNullifierMembershipWitness(referenceBlock, nullifier) {
1185
- const db = await this.#getWorldState(referenceBlock);
1552
+ const db = await this.getWorldState(referenceBlock);
1186
1553
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [
1187
1554
  nullifier.toBuffer()
1188
1555
  ]);
@@ -1196,36 +1563,22 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1196
1563
  }
1197
1564
  return new NullifierMembershipWitness(index, leafPreimage, path);
1198
1565
  }
1199
- /**
1200
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1201
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1202
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1203
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1204
- * @returns The low nullifier membership witness (if found).
1205
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1206
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1207
- * we are trying to prove non-inclusion for.
1208
- *
1209
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1210
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1211
- * index of the nullifier itself when it already exists in the tree.
1212
- * TODO: This is a confusing behavior and we should eventually address that.
1213
- */ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1214
- const committedDb = await this.#getWorldState(referenceBlock);
1566
+ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1567
+ const committedDb = await this.getWorldState(referenceBlock);
1215
1568
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1216
1569
  if (!findResult) {
1217
1570
  return undefined;
1218
1571
  }
1219
1572
  const { index, alreadyPresent } = findResult;
1220
1573
  if (alreadyPresent) {
1221
- this.log.warn(`Nullifier ${nullifier.toBigInt()} already exists in the tree`);
1574
+ throw new Error(`Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`);
1222
1575
  }
1223
1576
  const preimageData = await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1224
1577
  const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1225
1578
  return new NullifierMembershipWitness(BigInt(index), preimageData, siblingPath);
1226
1579
  }
1227
1580
  async getPublicDataWitness(referenceBlock, leafSlot) {
1228
- const committedDb = await this.#getWorldState(referenceBlock);
1581
+ const committedDb = await this.getWorldState(referenceBlock);
1229
1582
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1230
1583
  if (!lowLeafResult) {
1231
1584
  return undefined;
@@ -1236,7 +1589,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1236
1589
  }
1237
1590
  }
1238
1591
  async getPublicStorageAt(referenceBlock, contract, slot) {
1239
- const committedDb = await this.#getWorldState(referenceBlock);
1592
+ const committedDb = await this.getWorldState(referenceBlock);
1240
1593
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1241
1594
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1242
1595
  if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
@@ -1245,64 +1598,62 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1245
1598
  const preimage = await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1246
1599
  return preimage.leaf.value;
1247
1600
  }
1248
- async getBlockHeader(block = 'latest') {
1249
- if (BlockHash.isBlockHash(block)) {
1250
- const initialBlockHash = await this.#getInitialHeaderHash();
1251
- if (block.equals(initialBlockHash)) {
1252
- // Block source doesn't handle initial header so we need to handle the case separately.
1253
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1254
- }
1255
- return this.blockSource.getBlockHeaderByHash(block);
1256
- } else {
1257
- // Block source doesn't handle initial header so we need to handle the case separately.
1258
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
1259
- if (blockNumber === BlockNumber.ZERO) {
1260
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1261
- }
1262
- return this.blockSource.getBlockHeader(block);
1263
- }
1264
- }
1265
- /**
1266
- * Get a block header specified by its archive root.
1267
- * @param archive - The archive root being requested.
1268
- * @returns The requested block header.
1269
- */ async getBlockHeaderByArchive(archive) {
1270
- return await this.blockSource.getBlockHeaderByArchive(archive);
1271
- }
1272
- getBlockData(number) {
1273
- return this.blockSource.getBlockData(number);
1274
- }
1275
- getBlockDataByArchive(archive) {
1276
- return this.blockSource.getBlockDataByArchive(archive);
1277
- }
1278
1601
  /**
1279
1602
  * Simulates the public part of a transaction with the current state.
1280
1603
  * @param tx - The transaction to simulate.
1281
- **/ async simulatePublicCalls(tx, skipFeeEnforcement = false) {
1282
- // Check total gas limit for simulation
1283
- const gasSettings = tx.data.constants.txContext.gasSettings;
1284
- const txGasLimit = gasSettings.gasLimits.l2Gas;
1285
- const teardownGasLimit = gasSettings.teardownGasLimits.l2Gas;
1286
- if (txGasLimit + teardownGasLimit > this.config.rpcSimulatePublicMaxGasLimit) {
1287
- throw new BadRequestError(`Transaction total gas limit ${txGasLimit + teardownGasLimit} (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${this.config.rpcSimulatePublicMaxGasLimit} for simulation`);
1288
- }
1289
- const txHash = tx.getTxHash();
1290
- const latestBlockNumber = await this.blockSource.getBlockNumber();
1291
- const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1292
- // If sequencer is not initialized, we just set these values to zero for simulation.
1293
- const coinbase = EthAddress.ZERO;
1294
- const feeRecipient = AztecAddress.ZERO;
1295
- const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(blockNumber, coinbase, feeRecipient);
1296
- const publicProcessorFactory = new PublicProcessorFactory(this.contractDataSource, new DateProvider(), this.telemetry, this.log.getBindings());
1297
- this.log.verbose(`Simulating public calls for tx ${txHash}`, {
1298
- globalVariables: newGlobalVariables.toInspect(),
1299
- txHash,
1300
- blockNumber
1301
- });
1302
- // Ensure world-state has caught up with the latest block we loaded from the archiver
1303
- await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1304
- const merkleTreeFork = await this.worldStateSynchronizer.fork();
1604
+ * @param skipFeeEnforcement - If true, fee enforcement is skipped.
1605
+ * @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
+ };
1305
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);
1306
1657
  const config = PublicSimulatorConfig.from({
1307
1658
  skipFeeEnforcement,
1308
1659
  collectDebugLogs: true,
@@ -1313,9 +1664,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1313
1664
  maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads
1314
1665
  })
1315
1666
  });
1316
- const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
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);
1317
1672
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1318
- const [processedTxs, failedTxs, _usedTxs, returns, _blobFields, debugLogs] = await processor.process([
1673
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([
1319
1674
  tx
1320
1675
  ]);
1321
1676
  // REFACTOR: Consider returning the error rather than throwing
@@ -1327,25 +1682,36 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1327
1682
  }
1328
1683
  const [processedTx] = processedTxs;
1329
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;
1330
1688
  } finally{
1331
- await merkleTreeFork.close();
1689
+ const result = _ts_dispose_resources(env);
1690
+ if (result) await result;
1332
1691
  }
1333
1692
  }
1334
1693
  async isValidTx(tx, { isSimulation, skipFeeEnforcement } = {}) {
1335
1694
  const db = this.worldStateSynchronizer.getCommitted();
1336
- const verifier = isSimulation ? undefined : this.proofVerifier;
1695
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1337
1696
  // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1338
1697
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1339
1698
  const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
1699
+ const l1Constants = await this.blockSource.getL1Constants();
1340
1700
  const validator = createTxValidatorForAcceptingTxsOverRPC(db, this.contractDataSource, verifier, {
1341
1701
  timestamp: nextSlotTimestamp,
1342
1702
  blockNumber,
1343
1703
  l1ChainId: this.l1ChainId,
1344
1704
  rollupVersion: this.version,
1345
- setupAllowList: this.config.txPublicSetupAllowList ?? await getDefaultAllowedSetupFunctions(),
1705
+ setupAllowList: [
1706
+ ...await getDefaultAllowedSetupFunctions(),
1707
+ ...this.config.txPublicSetupAllowListExtend ?? []
1708
+ ],
1346
1709
  gasFees: await this.getCurrentMinFees(),
1347
1710
  skipFeeEnforcement,
1348
- txsPermitted: !this.config.disableTransactions
1711
+ txsPermitted: !this.config.disableTransactions,
1712
+ rollupManaLimit: l1Constants.rollupManaLimit,
1713
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1714
+ maxBlockDAGas: this.config.validateMaxDABlockGas
1349
1715
  }, this.log.getBindings());
1350
1716
  return await validator.validateTx(tx);
1351
1717
  }
@@ -1359,7 +1725,20 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1359
1725
  ...this.config,
1360
1726
  ...config
1361
1727
  };
1362
- this.sequencer?.updateConfig(config);
1728
+ // If the sequencer is currently paused via pauseSequencer(), record the caller's desired
1729
+ // minTxsPerBlock as the restore value (so resumeSequencer applies it) and keep the freeze
1730
+ // (MAX_SAFE_INTEGER) applied to the underlying sequencer. Without this guard, forwarding
1731
+ // the new minTxsPerBlock to the sequencer would silently unpause block production while
1732
+ // pauseSequencer() still considers it paused.
1733
+ const sequencerUpdate = {
1734
+ ...config
1735
+ };
1736
+ if (this.sequencerPausedMinTxsPerBlock !== undefined && sequencerUpdate.minTxsPerBlock !== undefined) {
1737
+ this.sequencerPausedMinTxsPerBlock = sequencerUpdate.minTxsPerBlock;
1738
+ delete sequencerUpdate.minTxsPerBlock;
1739
+ }
1740
+ this.sequencer?.updateConfig(sequencerUpdate);
1741
+ this.automineSequencer?.updateConfig(sequencerUpdate);
1363
1742
  this.slasherClient?.updateConfig(config);
1364
1743
  this.validatorsSentinel?.updateConfig(config);
1365
1744
  await this.p2pClient.updateP2PConfig(config);
@@ -1368,7 +1747,18 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1368
1747
  archiver.updateConfig(config);
1369
1748
  }
1370
1749
  if (newConfig.realProofs !== this.config.realProofs) {
1371
- this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
1750
+ await Promise.all([
1751
+ tryStop(this.peerProofVerifier),
1752
+ tryStop(this.rpcProofVerifier)
1753
+ ]);
1754
+ if (newConfig.realProofs) {
1755
+ this.peerProofVerifier = await BatchChonkVerifier.new(newConfig, newConfig.bbChonkVerifyMaxBatch, 'peer');
1756
+ const rpcVerifier = await BBCircuitVerifier.new(newConfig);
1757
+ this.rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, newConfig.numConcurrentIVCVerifiers);
1758
+ } else {
1759
+ this.peerProofVerifier = new TestCircuitVerifier();
1760
+ this.rpcProofVerifier = new TestCircuitVerifier();
1761
+ }
1372
1762
  }
1373
1763
  this.config = newConfig;
1374
1764
  }
@@ -1377,7 +1767,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1377
1767
  classRegistry: ProtocolContractAddress.ContractClassRegistry,
1378
1768
  feeJuice: ProtocolContractAddress.FeeJuice,
1379
1769
  instanceRegistry: ProtocolContractAddress.ContractInstanceRegistry,
1380
- multiCallEntrypoint: ProtocolContractAddress.MultiCallEntrypoint
1770
+ multiCallEntrypoint: STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS
1381
1771
  });
1382
1772
  }
1383
1773
  registerContractFunctionSignatures(signatures) {
@@ -1428,7 +1818,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1428
1818
  });
1429
1819
  return Promise.resolve();
1430
1820
  }
1431
- async rollbackTo(targetBlock, force) {
1821
+ async rollbackTo(targetBlock, force, resumeSync = true) {
1432
1822
  const archiver = this.blockSource;
1433
1823
  if (!('rollbackTo' in archiver)) {
1434
1824
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1456,9 +1846,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1456
1846
  this.log.error(`Error during rollback`, err);
1457
1847
  throw err;
1458
1848
  } finally{
1459
- this.log.info(`Resuming world state and archiver sync.`);
1460
- this.worldStateSynchronizer.resumeSync();
1461
- archiver.resume();
1849
+ if (resumeSync) {
1850
+ this.log.info(`Resuming world state and archiver sync.`);
1851
+ this.worldStateSynchronizer.resumeSync();
1852
+ archiver.resume();
1853
+ } else {
1854
+ this.log.info(`Sync left paused after rollback (resumeSync=false).`);
1855
+ }
1462
1856
  }
1463
1857
  }
1464
1858
  async pauseSync() {
@@ -1472,18 +1866,51 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1472
1866
  this.blockSource.resume();
1473
1867
  return Promise.resolve();
1474
1868
  }
1475
- getSlashPayloads() {
1476
- if (!this.slasherClient) {
1477
- throw new Error(`Slasher client not enabled`);
1869
+ pauseSequencer() {
1870
+ if (this.automineSequencer) {
1871
+ this.automineSequencer.pause();
1872
+ return Promise.resolve();
1873
+ }
1874
+ if (this.sequencer) {
1875
+ if (this.sequencerPausedMinTxsPerBlock === undefined) {
1876
+ this.sequencerPausedMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock ?? 0;
1877
+ this.sequencer.updateConfig({
1878
+ minTxsPerBlock: Number.MAX_SAFE_INTEGER
1879
+ });
1880
+ this.log.info(`Sequencer paused (minTxsPerBlock set to MAX_SAFE_INTEGER)`, {
1881
+ previousMinTxsPerBlock: this.sequencerPausedMinTxsPerBlock
1882
+ });
1883
+ }
1884
+ return Promise.resolve();
1885
+ }
1886
+ throw new BadRequestError('Cannot pause sequencer: no sequencer is running');
1887
+ }
1888
+ resumeSequencer() {
1889
+ if (this.automineSequencer) {
1890
+ this.automineSequencer.resume();
1891
+ return Promise.resolve();
1892
+ }
1893
+ if (this.sequencer) {
1894
+ if (this.sequencerPausedMinTxsPerBlock !== undefined) {
1895
+ const restored = this.sequencerPausedMinTxsPerBlock;
1896
+ this.sequencerPausedMinTxsPerBlock = undefined;
1897
+ this.sequencer.updateConfig({
1898
+ minTxsPerBlock: restored
1899
+ });
1900
+ this.log.info(`Sequencer resumed (minTxsPerBlock restored)`, {
1901
+ minTxsPerBlock: restored
1902
+ });
1903
+ }
1904
+ return Promise.resolve();
1478
1905
  }
1479
- return this.slasherClient.getSlashPayloads();
1906
+ throw new BadRequestError('Cannot resume sequencer: no sequencer is running');
1480
1907
  }
1481
1908
  getSlashOffenses(round) {
1482
1909
  if (!this.slasherClient) {
1483
1910
  throw new Error(`Slasher client not enabled`);
1484
1911
  }
1485
1912
  if (round === 'all') {
1486
- return this.slasherClient.getPendingOffenses();
1913
+ return this.slasherClient.getOffenses();
1487
1914
  } else {
1488
1915
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1489
1916
  }
@@ -1555,57 +1982,104 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1555
1982
  this.keyStoreManager = newManager;
1556
1983
  this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1557
1984
  }
1558
- #getInitialHeaderHash() {
1559
- if (!this.initialHeaderHashPromise) {
1560
- this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
1985
+ async mineBlock() {
1986
+ if (this.automineSequencer) {
1987
+ await this.automineSequencer.buildEmptyBlock();
1988
+ return;
1989
+ }
1990
+ if (!this.sequencer) {
1991
+ throw new BadRequestError('Cannot mine block: no sequencer is running');
1992
+ }
1993
+ const currentBlockNumber = await this.getBlockNumber();
1994
+ // Use slot duration + 50% buffer as the timeout so this works on running networks too
1995
+ const { slotDuration } = await this.blockSource.getL1Constants();
1996
+ const timeoutSeconds = Math.ceil(slotDuration * 1.5);
1997
+ // Temporarily set minTxsPerBlock to 0 so the sequencer produces a block even with no txs
1998
+ const originalMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock;
1999
+ this.sequencer.updateConfig({
2000
+ minTxsPerBlock: 0
2001
+ });
2002
+ try {
2003
+ // Trigger the sequencer to produce a block immediately
2004
+ void this.sequencer.trigger();
2005
+ // Wait for the new L2 block to appear
2006
+ await retryUntil(async ()=>{
2007
+ const newBlockNumber = await this.getBlockNumber();
2008
+ return newBlockNumber > currentBlockNumber ? true : undefined;
2009
+ }, 'mineBlock', timeoutSeconds, 0.1);
2010
+ } finally{
2011
+ this.sequencer.updateConfig({
2012
+ minTxsPerBlock: originalMinTxsPerBlock
2013
+ });
1561
2014
  }
1562
- return this.initialHeaderHashPromise;
1563
2015
  }
1564
2016
  /**
1565
2017
  * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1566
2018
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1567
2019
  * @returns An instance of a committed MerkleTreeOperations
1568
- */ async #getWorldState(block) {
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;
1569
2030
  let blockSyncedTo = BlockNumber.ZERO;
1570
2031
  try {
1571
2032
  // Attempt to sync the world state if necessary
1572
- blockSyncedTo = await this.#syncWorldState();
2033
+ blockSyncedTo = await this.#syncWorldState(anchorBlockNumber, requestedHash);
1573
2034
  } catch (err) {
1574
2035
  this.log.error(`Error getting world state: ${err}`);
1575
2036
  }
1576
- if (block === 'latest') {
1577
- this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
2037
+ if ('tag' in query && query.tag === 'proposed') {
2038
+ this.log.debug(`Using committed db for latest block, world state synced upto ${blockSyncedTo}`);
1578
2039
  return this.worldStateSynchronizer.getCommitted();
1579
2040
  }
1580
- if (BlockHash.isBlockHash(block)) {
1581
- const initialBlockHash = await this.#getInitialHeaderHash();
1582
- if (block.equals(initialBlockHash)) {
1583
- // Block source doesn't handle initial header so we need to handle the case separately.
1584
- return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1585
- }
1586
- const header = await this.blockSource.getBlockHeaderByHash(block);
1587
- if (!header) {
1588
- 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.`);
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.`);
1589
2057
  }
1590
- const blockNumber = header.getBlockNumber();
1591
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1592
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1593
2058
  }
1594
- // Block number provided
1595
- {
1596
- const blockNumber = block;
1597
- if (blockNumber > blockSyncedTo) {
1598
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
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.`);
1599
2070
  }
1600
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1601
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
2071
+ throw new Error(`Block not found for ${inspectBlockParameter(block)}.`);
1602
2072
  }
2073
+ return blockNumber;
1603
2074
  }
1604
2075
  /**
1605
- * Ensure we fully sync the world state
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.
1606
2080
  * @returns A promise that fulfils once the world state is synced
1607
- */ async #syncWorldState() {
1608
- const blockSourceHeight = await this.blockSource.getBlockNumber();
1609
- return await this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
2081
+ */ async #syncWorldState(targetBlockNumber, blockHash) {
2082
+ const target = targetBlockNumber ?? await this.blockSource.getBlockNumber();
2083
+ return await this.worldStateSynchronizer.syncImmediate(target, blockHash);
1610
2084
  }
1611
2085
  }