@aztec/aztec-node 0.0.1-commit.b33fc05d0 → 0.0.1-commit.b3d3157a

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 +7 -4
  5. package/dest/aztec-node/config.d.ts.map +1 -1
  6. package/dest/aztec-node/config.js +5 -5
  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 +73 -108
  11. package/dest/aztec-node/server.d.ts.map +1 -1
  12. package/dest/aztec-node/server.js +988 -495
  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 +4 -2
  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 +212 -70
  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 +11 -7
  30. package/src/aztec-node/public_data_overrides.ts +35 -0
  31. package/src/aztec-node/server.ts +1090 -615
  32. package/src/sentinel/README.md +103 -0
  33. package/src/sentinel/config.ts +18 -6
  34. package/src/sentinel/factory.ts +7 -4
  35. package/src/sentinel/sentinel.ts +267 -82
  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,34 @@ 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';
475
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
404
476
  import { GasFees } from '@aztec/stdlib/gas';
405
477
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
406
478
  import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
407
479
  import { tryStop } from '@aztec/stdlib/interfaces/server';
408
480
  import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
409
- import { InboxLeaf } from '@aztec/stdlib/messaging';
481
+ import { InboxLeaf, appendL1ToL2MessagesToTree } from '@aztec/stdlib/messaging';
482
+ import { MIN_EXECUTION_TIME } from '@aztec/stdlib/timetable';
410
483
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
411
- import { PublicSimulationOutput, TxReceipt, TxStatus } from '@aztec/stdlib/tx';
484
+ import { DroppedTxReceipt, MinedTxReceipt, PendingTxReceipt, PublicSimulationOutput, TxStatus } from '@aztec/stdlib/tx';
412
485
  import { getPackageVersion } from '@aztec/stdlib/update-checker';
413
486
  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';
487
+ import { FullNodeCheckpointsBuilder as CheckpointsBuilder, FullNodeCheckpointsBuilder, NodeKeystoreAdapter, ValidatorClient, createProposalHandler, createValidatorClient } from '@aztec/validator-client';
488
+ import { createWorldState, createWorldStateSynchronizer } from '@aztec/world-state';
489
+ import { createPublicClient } from 'viem';
417
490
  import { createSentinel } from '../sentinel/factory.js';
491
+ import { blockResponseFromBlockData, blockResponseFromL2Block, checkpointResponseFromCheckpointData, checkpointResponseFromPublishedCheckpoint, projectProposedToCheckpointResponse } from './block_response_helpers.js';
418
492
  import { createKeyStoreForValidator } from './config.js';
419
493
  import { NodeMetrics } from './node_metrics.js';
494
+ import { applyPublicDataOverrides } from './public_data_overrides.js';
420
495
  _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
421
496
  [Attributes.TX_HASH]: tx.getTxHash().toString()
422
497
  }));
@@ -434,19 +509,22 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
434
509
  proverNode;
435
510
  slasherClient;
436
511
  validatorsSentinel;
437
- epochPruneWatcher;
512
+ stopStartedWatchers;
438
513
  l1ChainId;
439
514
  version;
440
515
  globalVariableBuilder;
516
+ feeProvider;
441
517
  epochCache;
442
518
  packageVersion;
443
- proofVerifier;
519
+ peerProofVerifier;
520
+ rpcProofVerifier;
444
521
  telemetry;
445
522
  log;
446
523
  blobClient;
447
524
  validatorClient;
448
525
  keyStoreManager;
449
526
  debugLogStore;
527
+ automineSequencer;
450
528
  static{
451
529
  ({ e: [_initProto] } = _apply_decs_2203_r(this, [
452
530
  [
@@ -457,11 +535,12 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
457
535
  ], []));
458
536
  }
459
537
  metrics;
460
- initialHeaderHashPromise;
461
538
  // Prevent two snapshot operations to happen simultaneously
462
539
  isUploadingSnapshot;
540
+ // Saved minTxsPerBlock used by `pauseSequencer` to restore production-sequencer config on resume.
541
+ sequencerPausedMinTxsPerBlock;
463
542
  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()){
543
+ 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
544
  this.config = config;
466
545
  this.p2pClient = p2pClient;
467
546
  this.blockSource = blockSource;
@@ -473,25 +552,27 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
473
552
  this.proverNode = proverNode;
474
553
  this.slasherClient = slasherClient;
475
554
  this.validatorsSentinel = validatorsSentinel;
476
- this.epochPruneWatcher = epochPruneWatcher;
555
+ this.stopStartedWatchers = stopStartedWatchers;
477
556
  this.l1ChainId = l1ChainId;
478
557
  this.version = version;
479
558
  this.globalVariableBuilder = globalVariableBuilder;
559
+ this.feeProvider = feeProvider;
480
560
  this.epochCache = epochCache;
481
561
  this.packageVersion = packageVersion;
482
- this.proofVerifier = proofVerifier;
562
+ this.peerProofVerifier = peerProofVerifier;
563
+ this.rpcProofVerifier = rpcProofVerifier;
483
564
  this.telemetry = telemetry;
484
565
  this.log = log;
485
566
  this.blobClient = blobClient;
486
567
  this.validatorClient = validatorClient;
487
568
  this.keyStoreManager = keyStoreManager;
488
569
  this.debugLogStore = debugLogStore;
489
- this.initialHeaderHashPromise = (_initProto(this), undefined);
490
- this.isUploadingSnapshot = false;
570
+ this.automineSequencer = automineSequencer;
571
+ this.isUploadingSnapshot = (_initProto(this), false);
491
572
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
492
573
  this.tracer = telemetry.getTracer('AztecNodeService');
493
574
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
494
- this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
575
+ this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, pickL1ContractAddresses(config));
495
576
  // A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
496
577
  // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
497
578
  // memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
@@ -499,12 +580,249 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
499
580
  throw new Error('debugLogStore should never be enabled when realProofs are set');
500
581
  }
501
582
  }
583
+ /** @internal Exposed for testing — returns the RPC proof verifier. */ getProofVerifier() {
584
+ return this.rpcProofVerifier;
585
+ }
502
586
  async getWorldStateSyncStatus() {
503
587
  const status = await this.worldStateSynchronizer.status();
504
588
  return status.syncSummary;
505
589
  }
506
- getL2Tips() {
507
- return this.blockSource.getL2Tips();
590
+ async getChainTips() {
591
+ const { proposed, checkpointed, proven, finalized } = await this.blockSource.getL2Tips();
592
+ return {
593
+ proposed,
594
+ checkpointed,
595
+ proven,
596
+ finalized
597
+ };
598
+ }
599
+ getCheckpointsData(query) {
600
+ return this.blockSource.getCheckpointsData(query);
601
+ }
602
+ async getBlockNumber(tip) {
603
+ if (tip === undefined || tip === 'proposed') {
604
+ return this.blockSource.getBlockNumber();
605
+ }
606
+ return await this.blockSource.getBlockNumber({
607
+ tag: tip
608
+ }) ?? BlockNumber.ZERO;
609
+ }
610
+ async getCheckpointNumber(tip) {
611
+ const tips = await this.blockSource.getL2Tips();
612
+ switch(tip){
613
+ case undefined:
614
+ case 'checkpointed':
615
+ return tips.checkpointed.checkpoint.number;
616
+ case 'proposed':
617
+ return tips.proposedCheckpoint.checkpoint.number;
618
+ case 'proven':
619
+ return tips.proven.checkpoint.number;
620
+ case 'finalized':
621
+ return tips.finalized.checkpoint.number;
622
+ }
623
+ }
624
+ isChainTip(value) {
625
+ return value === 'proposed' || value === 'checkpointed' || value === 'proven' || value === 'finalized';
626
+ }
627
+ /**
628
+ * Normalizes a {@link BlockParameter} (which may be a bare value) into a
629
+ * {@link NormalizedBlockParameter} object form. Performs no chain-tip resolution — tag
630
+ * lookups are deferred to the underlying block source.
631
+ */ normalizeBlockParameter(param) {
632
+ if (BlockHash.isBlockHash(param)) {
633
+ return {
634
+ hash: param
635
+ };
636
+ }
637
+ if (typeof param === 'number') {
638
+ return {
639
+ number: param
640
+ };
641
+ }
642
+ if (typeof param === 'string') {
643
+ if (this.isBlockTag(param)) {
644
+ return {
645
+ tag: param === 'latest' ? 'proposed' : param
646
+ };
647
+ }
648
+ throw new BadRequestError(`Invalid BlockParameter tag: ${param}`);
649
+ }
650
+ if (typeof param === 'object' && param !== null) {
651
+ if ('number' in param) {
652
+ return {
653
+ number: param.number
654
+ };
655
+ }
656
+ if ('hash' in param) {
657
+ return {
658
+ hash: param.hash
659
+ };
660
+ }
661
+ if ('archive' in param) {
662
+ return {
663
+ archive: param.archive
664
+ };
665
+ }
666
+ if ('tag' in param) {
667
+ if (this.isBlockTag(param.tag)) {
668
+ return {
669
+ tag: param.tag
670
+ };
671
+ }
672
+ throw new BadRequestError(`Invalid BlockParameter tag: ${param.tag}`);
673
+ }
674
+ }
675
+ throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(param)}`);
676
+ }
677
+ isBlockTag(value) {
678
+ return BlockTag.includes(value);
679
+ }
680
+ /**
681
+ * Resolves a {@link CheckpointParameter} into a concrete `{ number }` or `{ slot }` query.
682
+ *
683
+ * Tag-based parameters (`'proposed'`, `'checkpointed'`, `'proven'`, `'finalized'`) are
684
+ * translated up-front to the corresponding tip's checkpoint number via {@link L2BlockSource.getL2Tips}.
685
+ * After resolution the unified {@link getCheckpoint} flow can perform a single
686
+ * confirmed→proposed lookup against either store.
687
+ */ async resolveCheckpointParameter(param) {
688
+ if (typeof param === 'number') {
689
+ return {
690
+ number: param
691
+ };
692
+ }
693
+ if (this.isChainTip(param)) {
694
+ const tips = await this.blockSource.getL2Tips();
695
+ switch(param){
696
+ case 'proposed':
697
+ return {
698
+ number: tips.proposedCheckpoint.checkpoint.number
699
+ };
700
+ case 'checkpointed':
701
+ return {
702
+ number: tips.checkpointed.checkpoint.number
703
+ };
704
+ case 'proven':
705
+ return {
706
+ number: tips.proven.checkpoint.number
707
+ };
708
+ case 'finalized':
709
+ return {
710
+ number: tips.finalized.checkpoint.number
711
+ };
712
+ }
713
+ }
714
+ if (typeof param === 'object' && param !== null) {
715
+ if ('number' in param) {
716
+ return {
717
+ number: param.number
718
+ };
719
+ }
720
+ if ('slot' in param) {
721
+ return {
722
+ slot: param.slot
723
+ };
724
+ }
725
+ }
726
+ throw new BadRequestError(`Invalid CheckpointParameter: ${JSON.stringify(param)}`);
727
+ }
728
+ /** Fetches checkpoint-level L1 and attestation data for use as block response context. */ async #getCheckpointContext(checkpointNumber) {
729
+ const checkpoint = await this.blockSource.getCheckpointData({
730
+ number: checkpointNumber
731
+ });
732
+ if (!checkpoint) {
733
+ return undefined;
734
+ }
735
+ return {
736
+ l1: checkpoint.l1,
737
+ attestations: checkpoint.attestations
738
+ };
739
+ }
740
+ async getBlock(param, options = {}) {
741
+ const query = this.normalizeBlockParameter(param);
742
+ const wantTxs = !!options.includeTransactions;
743
+ const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
744
+ if (wantTxs) {
745
+ const block = await this.blockSource.getBlock(query);
746
+ if (!block) {
747
+ return undefined;
748
+ }
749
+ const ctx = wantContext ? await this.#getCheckpointContext(block.checkpointNumber) : undefined;
750
+ return await blockResponseFromL2Block(block, options, ctx);
751
+ }
752
+ const data = await this.blockSource.getBlockData(query);
753
+ if (!data) {
754
+ return undefined;
755
+ }
756
+ const ctx = wantContext ? await this.#getCheckpointContext(data.checkpointNumber) : undefined;
757
+ return blockResponseFromBlockData(data, options, ctx);
758
+ }
759
+ getBlockData(param) {
760
+ const query = this.normalizeBlockParameter(param);
761
+ return this.blockSource.getBlockData(query);
762
+ }
763
+ async getBlocks(from, limit, options = {}) {
764
+ const wantTxs = !!options.includeTransactions;
765
+ const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
766
+ const onlyCheckpointed = !!options.onlyCheckpointed;
767
+ if (wantTxs) {
768
+ const blocks = await this.blockSource.getBlocks({
769
+ from,
770
+ limit,
771
+ onlyCheckpointed
772
+ });
773
+ const ctxByCheckpoint = await this.#getCheckpointContextsForBlocks(wantContext ? blocks : []);
774
+ return await Promise.all(blocks.map((block)=>blockResponseFromL2Block(block, options, ctxByCheckpoint.get(block.checkpointNumber))));
775
+ }
776
+ const dataItems = await this.blockSource.getBlocksData({
777
+ from,
778
+ limit,
779
+ onlyCheckpointed
780
+ });
781
+ const ctxByCheckpoint = await this.#getCheckpointContextsForBlocks(wantContext ? dataItems : []);
782
+ return await Promise.all(dataItems.map((data)=>blockResponseFromBlockData(data, options, ctxByCheckpoint.get(data.checkpointNumber))));
783
+ }
784
+ /** Fetches checkpoint context for a set of blocks, deduplicating shared checkpoints. */ async #getCheckpointContextsForBlocks(blocks) {
785
+ const unique = Array.from(new Set(blocks.map((b)=>b.checkpointNumber)));
786
+ const entries = await Promise.all(unique.map(async (n)=>[
787
+ n,
788
+ await this.#getCheckpointContext(n)
789
+ ]));
790
+ return new Map(entries);
791
+ }
792
+ async getCheckpoint(param, options = {}) {
793
+ const query = await this.resolveCheckpointParameter(param);
794
+ // Try the confirmed store first.
795
+ const confirmed = options.includeBlocks ? await this.blockSource.getCheckpoint(query) : await this.blockSource.getCheckpointData(query);
796
+ if (confirmed) {
797
+ return await (options.includeBlocks ? checkpointResponseFromPublishedCheckpoint(confirmed, options) : checkpointResponseFromCheckpointData(confirmed, options));
798
+ }
799
+ // Fall back to the proposed store.
800
+ const proposed = await this.blockSource.getProposedCheckpointData(query);
801
+ if (proposed) {
802
+ if (options.includeAttestations || options.includeL1PublishInfo) {
803
+ throw new BadRequestError(`Options includeL1PublishInfo or includeAttestations cannot be satisfied for a proposed checkpoint`);
804
+ }
805
+ const blocks = options.includeBlocks ? await this.blockSource.getBlocks({
806
+ from: proposed.startBlock,
807
+ limit: proposed.blockCount
808
+ }) : undefined;
809
+ return await projectProposedToCheckpointResponse(proposed, options, blocks);
810
+ }
811
+ return undefined;
812
+ }
813
+ async getCheckpoints(from, limit, options = {}) {
814
+ if (options.includeBlocks) {
815
+ const checkpoints = await this.blockSource.getCheckpoints({
816
+ from,
817
+ limit
818
+ });
819
+ return await Promise.all(checkpoints.map((cp)=>checkpointResponseFromPublishedCheckpoint(cp, options)));
820
+ }
821
+ const datas = await this.blockSource.getCheckpointsData({
822
+ from,
823
+ limit
824
+ });
825
+ return datas.map((d)=>checkpointResponseFromCheckpointData(d, options));
508
826
  }
509
827
  /**
510
828
  * initializes the Aztec Node, wait for component to sync.
@@ -515,7 +833,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
515
833
  ...inputConfig
516
834
  }; // Copy the config so we dont mutate the input object
517
835
  const log = deps.logger ?? createLogger('node');
518
- const packageVersion = getPackageVersion() ?? '';
836
+ const packageVersion = getPackageVersion();
519
837
  const telemetry = deps.telemetry ?? getTelemetryClient();
520
838
  const dateProvider = deps.dateProvider ?? new DateProvider();
521
839
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
@@ -559,18 +877,14 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
559
877
  }
560
878
  const publicClient = createPublicClient({
561
879
  chain: ethereumChain.chainInfo,
562
- transport: fallback(config.l1RpcUrls.map((url)=>http(url, {
563
- batch: false
564
- }))),
880
+ transport: makeL1HttpTransport(config.l1RpcUrls, {
881
+ timeout: config.l1HttpTimeoutMS
882
+ }),
565
883
  pollingInterval: config.viemPollingIntervalMS
566
884
  });
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());
885
+ const l1ContractsAddresses = await RegistryContract.collectAddresses(publicClient, config.registryAddress, config.rollupVersion ?? 'canonical');
886
+ Object.assign(config, l1ContractsAddresses);
887
+ const rollupContract = new RollupContract(publicClient, config.rollupAddress.toString());
574
888
  const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
575
889
  rollupContract.getL1GenesisTime(),
576
890
  rollupContract.getSlotDuration(),
@@ -584,203 +898,338 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
584
898
  const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
585
899
  // attempt snapshot sync if possible
586
900
  await trySnapshotSync(config, log);
587
- const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, {
901
+ const epochCache = await EpochCache.create(config.rollupAddress, config, {
588
902
  dateProvider
589
903
  });
590
- const archiver = await createArchiver(config, {
591
- blobClient,
592
- epochCache,
593
- telemetry,
594
- dateProvider
595
- }, {
596
- blockUntilSync: !config.skipArchiverInitialSync
597
- });
598
- // now create the merkle trees and the world state synchronizer
599
- const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.prefilledPublicData, telemetry);
600
- const circuitVerifier = config.realProofs || config.debugForceTxProofVerification ? await BBCircuitVerifier.new(config) : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
601
- let debugLogStore;
602
- if (!config.realProofs) {
603
- log.warn(`Aztec node is accepting fake proofs`);
604
- debugLogStore = new InMemoryDebugLogStore();
605
- log.info('Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served');
606
- } else {
607
- debugLogStore = new NullDebugLogStore();
608
- }
609
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
610
- const proverOnly = config.enableProverNode && config.disableValidator;
611
- if (proverOnly) {
612
- log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
613
- }
614
- // create the tx pool and the p2p client, which will need the l2 block source
615
- const p2pClient = await createP2PClient(config, archiver, proofVerifier, worldStateSynchronizer, epochCache, packageVersion, dateProvider, telemetry, deps.p2pClientDeps);
616
- // We'll accumulate sentinel watchers here
617
- const watchers = [];
618
- // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
619
- // Override maxTxsPerCheckpoint with the validator-specific limit if set.
620
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder({
621
- ...config,
622
- l1GenesisTime,
623
- slotDuration: Number(slotDuration),
624
- rollupManaLimit,
625
- maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint
626
- }, worldStateSynchronizer, archiver, dateProvider, telemetry);
627
- let validatorClient;
628
- if (!proverOnly) {
629
- // Create validator client if required
630
- validatorClient = await createValidatorClient(config, {
631
- checkpointsBuilder: validatorCheckpointsBuilder,
632
- worldState: worldStateSynchronizer,
633
- p2pClient,
634
- telemetry,
635
- dateProvider,
636
- epochCache,
637
- blockSource: archiver,
638
- l1ToL2MessageSource: archiver,
639
- keyStoreManager,
640
- blobClient
641
- });
642
- // If we have a validator client, register it as a source of offenses for the slasher,
643
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
644
- // like attestations or auths will fail.
645
- if (validatorClient) {
646
- watchers.push(validatorClient);
647
- if (!options.dontStartSequencer) {
648
- await validatorClient.registerHandlers();
649
- }
650
- }
651
- }
652
- // If there's no validator client, create a BlockProposalHandler to handle block proposals
653
- // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
654
- // while non-reexecution is used for validating the proposals and collecting their txs.
655
- if (!validatorClient) {
656
- const reexecute = !!config.alwaysReexecuteBlockProposals;
657
- log.info(`Setting up block proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
658
- createBlockProposalHandler(config, {
659
- checkpointsBuilder: validatorCheckpointsBuilder,
660
- worldState: worldStateSynchronizer,
904
+ // Track started resources so we can clean up on partial failure during node creation.
905
+ const started = [];
906
+ try {
907
+ // Default the orphan-prune grace window from the block build duration when unset, so the archiver
908
+ // waits roughly one build slot for a proposed checkpoint to arrive before pruning a block-only tip.
909
+ config.orphanProposedBlockPruneGraceSeconds ??= config.blockDurationMs !== undefined ? Math.ceil(config.blockDurationMs / 1000) : MIN_EXECUTION_TIME;
910
+ // Create world-state first so we can retrieve the initial header before constructing the archiver.
911
+ const nativeWs = await createWorldState(config, options.genesis);
912
+ const initialHeader = nativeWs.getInitialHeader();
913
+ const initialBlockHash = await initialHeader.hash();
914
+ const archiver = await createArchiver(config, {
915
+ blobClient,
661
916
  epochCache,
662
- blockSource: archiver,
663
- l1ToL2MessageSource: archiver,
664
- p2pClient,
665
- dateProvider,
666
- telemetry
667
- }).register(p2pClient, reexecute);
668
- }
669
- // Start world state and wait for it to sync to the archiver.
670
- await worldStateSynchronizer.start();
671
- // Start p2p. Note that it depends on world state to be running.
672
- await p2pClient.start();
673
- let validatorsSentinel;
674
- let epochPruneWatcher;
675
- let attestationsBlockWatcher;
676
- if (!proverOnly) {
677
- validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
678
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
679
- watchers.push(validatorsSentinel);
680
- }
681
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
682
- epochPruneWatcher = new EpochPruneWatcher(archiver, archiver, epochCache, p2pClient.getTxProvider(), validatorCheckpointsBuilder, config);
683
- watchers.push(epochPruneWatcher);
684
- }
685
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
686
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
687
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
688
- watchers.push(attestationsBlockWatcher);
689
- }
690
- }
691
- // Start p2p-related services once the archiver has completed sync
692
- void archiver.waitForInitialSync().then(async ()=>{
693
- await p2pClient.start();
694
- await validatorsSentinel?.start();
695
- await epochPruneWatcher?.start();
696
- await attestationsBlockWatcher?.start();
697
- log.info(`All p2p services started`);
698
- }).catch((err)=>log.error('Failed to start p2p services after archiver sync', err));
699
- // Validator enabled, create/start relevant service
700
- let sequencer;
701
- let slasherClient;
702
- if (!config.disableValidator && validatorClient) {
703
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
704
- // as they are executed when the node is selected as proposer.
705
- const validatorAddresses = keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses() : [];
706
- slasherClient = await createSlasher(config, config.l1Contracts, getPublicClient(config), watchers, dateProvider, epochCache, validatorAddresses, undefined);
707
- await slasherClient.start();
708
- const l1TxUtils = config.sequencerPublisherForwarderAddress ? await createForwarderL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), config.sequencerPublisherForwarderAddress, {
709
- ...config,
710
- scope: 'sequencer'
711
- }, {
712
917
  telemetry,
713
- logger: log.createChild('l1-tx-utils'),
714
- dateProvider,
715
- kzg: Blob.getViemKzgInstance()
716
- }) : await createL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
717
- ...config,
718
- scope: 'sequencer'
918
+ dateProvider
719
919
  }, {
720
- telemetry,
721
- logger: log.createChild('l1-tx-utils'),
722
- dateProvider,
723
- kzg: Blob.getViemKzgInstance()
724
- });
725
- // Create and start the sequencer client
726
- const checkpointsBuilder = new CheckpointsBuilder({
920
+ blockUntilSync: !config.skipArchiverInitialSync,
921
+ // The non-pipelined automine sequencer publishes each checkpoint in-slot, so it never
922
+ // leaves orphan proposed blocks; pruning would race its local push. See pruneOrphanProposedBlocks.
923
+ enableOrphanProposedBlockPruning: !config.useAutomineSequencer
924
+ }, initialHeader, initialBlockHash);
925
+ started.push(archiver);
926
+ // The synchronizer takes ownership of the native world-state from here
927
+ const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, nativeWs, telemetry);
928
+ started.push(worldStateSynchronizer);
929
+ const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
930
+ let peerProofVerifier;
931
+ let rpcProofVerifier;
932
+ if (useRealVerifiers) {
933
+ peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
934
+ const rpcVerifier = await BBCircuitVerifier.new(config);
935
+ rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
936
+ } else {
937
+ peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
938
+ rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
939
+ }
940
+ started.push(peerProofVerifier, rpcProofVerifier);
941
+ let debugLogStore;
942
+ if (!config.realProofs) {
943
+ log.warn(`Aztec node is accepting fake proofs`);
944
+ debugLogStore = new InMemoryDebugLogStore();
945
+ log.info('Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served');
946
+ } else {
947
+ debugLogStore = new NullDebugLogStore();
948
+ }
949
+ const globalVariableBuilderConfig = {
950
+ rollupAddress: config.rollupAddress,
951
+ ethereumSlotDuration: config.ethereumSlotDuration,
952
+ rollupVersion: BigInt(config.rollupVersion),
953
+ l1GenesisTime,
954
+ slotDuration: Number(slotDuration)
955
+ };
956
+ const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, globalVariableBuilderConfig);
957
+ const feeProvider = new FeeProviderImpl(dateProvider, publicClient, globalVariableBuilderConfig);
958
+ const proverOnly = config.enableProverNode && config.disableValidator;
959
+ if (proverOnly) {
960
+ log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
961
+ }
962
+ // create the tx pool and the p2p client, which will need the l2 block source
963
+ const p2pClient = await createP2PClient(config, archiver, peerProofVerifier, worldStateSynchronizer, epochCache, feeProvider, packageVersion, dateProvider, telemetry, deps.p2pClientDeps, initialBlockHash);
964
+ started.push(p2pClient);
965
+ // We'll accumulate sentinel watchers here
966
+ const watchers = [];
967
+ // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
968
+ // Override maxTxsPerCheckpoint with the validator-specific limit if set.
969
+ const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder({
727
970
  ...config,
728
971
  l1GenesisTime,
729
972
  slotDuration: Number(slotDuration),
730
- rollupManaLimit
731
- }, worldStateSynchronizer, archiver, dateProvider, telemetry, debugLogStore);
732
- sequencer = await SequencerClient.new(config, {
733
- ...deps,
734
- epochCache,
735
- l1TxUtils,
736
- validatorClient,
737
- p2pClient,
738
- worldStateSynchronizer,
739
- slasherClient,
740
- checkpointsBuilder,
741
- l2BlockSource: archiver,
742
- l1ToL2MessageSource: archiver,
743
- telemetry,
744
- dateProvider,
745
- blobClient,
746
- nodeKeyStore: keyStoreManager
747
- });
748
- }
749
- if (!options.dontStartSequencer && sequencer) {
750
- await sequencer.start();
751
- log.verbose(`Sequencer started`);
752
- } else if (sequencer) {
753
- log.warn(`Sequencer created but not started`);
754
- }
755
- // Create prover node subsystem if enabled
756
- let proverNode;
757
- if (config.enableProverNode) {
758
- proverNode = await createProverNode(config, {
759
- ...deps.proverNodeDeps,
760
- telemetry,
761
- dateProvider,
762
- archiver,
763
- worldStateSynchronizer,
764
- p2pClient,
765
- epochCache,
766
- blobClient,
767
- keyStoreManager
973
+ rollupManaLimit,
974
+ maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint
975
+ }, worldStateSynchronizer, archiver, dateProvider, telemetry);
976
+ let validatorClient;
977
+ // Tracks successful checkpoint re-execution by a checkpoint proposal handler.
978
+ const reexecutionTracker = new CheckpointReexecutionTracker();
979
+ if (!config.disableValidator) {
980
+ // Create validator client if required
981
+ validatorClient = await createValidatorClient(config, {
982
+ checkpointsBuilder: validatorCheckpointsBuilder,
983
+ worldState: worldStateSynchronizer,
984
+ p2pClient,
985
+ telemetry,
986
+ dateProvider,
987
+ epochCache,
988
+ blockSource: archiver,
989
+ l1ToL2MessageSource: archiver,
990
+ keyStoreManager,
991
+ blobClient,
992
+ reexecutionTracker,
993
+ slashingProtectionDb: deps.slashingProtectionDb
994
+ });
995
+ // If we have a validator client, register it as a source of offenses for the slasher,
996
+ // and have it register callbacks on the p2p client *before* we start it, otherwise messages
997
+ // like attestations or auths will fail.
998
+ if (validatorClient) {
999
+ watchers.push(validatorClient);
1000
+ const vc = validatorClient;
1001
+ const getValidatorAddresses = ()=>vc.getValidatorAddresses().map((a)=>a.toString());
1002
+ validatorClient.getProposalHandler().register(p2pClient, true, archiver, getValidatorAddresses);
1003
+ if (!options.dontStartSequencer) {
1004
+ await validatorClient.registerHandlers();
1005
+ }
1006
+ }
1007
+ }
1008
+ // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
1009
+ // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
1010
+ // while non-reexecution is used for validating the proposals and collecting their txs.
1011
+ // Checkpoint proposals rebuild blobs if the blob client can upload blobs.
1012
+ if (!validatorClient) {
1013
+ const reexecute = !!config.alwaysReexecuteBlockProposals;
1014
+ log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
1015
+ createProposalHandler(config, {
1016
+ checkpointsBuilder: validatorCheckpointsBuilder,
1017
+ worldState: worldStateSynchronizer,
1018
+ epochCache,
1019
+ blockSource: archiver,
1020
+ l1ToL2MessageSource: archiver,
1021
+ p2pClient,
1022
+ blobClient,
1023
+ dateProvider,
1024
+ telemetry,
1025
+ reexecutionTracker
1026
+ }).register(p2pClient, reexecute, archiver);
1027
+ }
1028
+ // Start world state and wait for it to sync to the archiver.
1029
+ await worldStateSynchronizer.start();
1030
+ // Start p2p. Note that it depends on world state to be running.
1031
+ await p2pClient.start();
1032
+ let validatorsSentinel;
1033
+ let dataWithholdingWatcher;
1034
+ let attestationsBlockWatcher;
1035
+ let attestedInvalidProposalWatcher;
1036
+ let broadcastedInvalidCheckpointProposalWatcher;
1037
+ let checkpointEquivocationWatcher;
1038
+ if (!proverOnly) {
1039
+ validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, reexecutionTracker, config);
1040
+ if (validatorsSentinel) {
1041
+ watchers.push(validatorsSentinel);
1042
+ }
1043
+ dataWithholdingWatcher = new DataWithholdingWatcher(epochCache, archiver, p2pClient.getTxProvider(), p2pClient, reexecutionTracker, {
1044
+ chainId: config.l1ChainId,
1045
+ rollupAddress: config.rollupAddress
1046
+ }, config);
1047
+ watchers.push(dataWithholdingWatcher);
1048
+ broadcastedInvalidCheckpointProposalWatcher = new BroadcastedInvalidCheckpointProposalWatcher(p2pClient, archiver, epochCache, config);
1049
+ watchers.push(broadcastedInvalidCheckpointProposalWatcher);
1050
+ if (validatorClient) {
1051
+ attestedInvalidProposalWatcher = new AttestedInvalidProposalWatcher(p2pClient, validatorClient, archiver, epochCache, config, {
1052
+ log: log.createChild('attested-invalid-proposal-watcher')
1053
+ });
1054
+ watchers.push(attestedInvalidProposalWatcher);
1055
+ }
1056
+ checkpointEquivocationWatcher = new CheckpointEquivocationWatcher(archiver, epochCache, config);
1057
+ watchers.push(checkpointEquivocationWatcher);
1058
+ attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config, log.getBindings());
1059
+ watchers.push(attestationsBlockWatcher);
1060
+ }
1061
+ const watchersToStart = compactArray([
1062
+ validatorsSentinel,
1063
+ dataWithholdingWatcher,
1064
+ attestationsBlockWatcher,
1065
+ broadcastedInvalidCheckpointProposalWatcher,
1066
+ attestedInvalidProposalWatcher,
1067
+ checkpointEquivocationWatcher
1068
+ ]);
1069
+ const startedWatchers = [];
1070
+ const stopStartedWatchers = async ()=>{
1071
+ for (const watcher of startedWatchers){
1072
+ await tryStop(watcher);
1073
+ }
1074
+ };
1075
+ // Start p2p-related services once the archiver has completed sync
1076
+ void archiver.waitForInitialSync().then(async ()=>{
1077
+ for (const watcher of watchersToStart){
1078
+ await watcher.start();
1079
+ startedWatchers.push(watcher);
1080
+ }
1081
+ log.info(`All p2p services started`);
1082
+ }).catch((err)=>log.error('Failed to start p2p services after archiver sync', err));
1083
+ started.push({
1084
+ stop: stopStartedWatchers
768
1085
  });
769
- if (!options.dontStartProverNode) {
770
- await proverNode.start();
771
- log.info(`Prover node subsystem started`);
772
- } else {
773
- log.info(`Prover node subsystem created but not started`);
1086
+ // Validator enabled, create/start relevant service
1087
+ let sequencer;
1088
+ let automineSequencer;
1089
+ let slasherClient;
1090
+ if (!config.disableValidator && validatorClient) {
1091
+ // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
1092
+ // as they are executed when the node is selected as proposer.
1093
+ const validatorAddresses = keyStoreManager ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses() : [];
1094
+ slasherClient = await createSlasher(config, pickL1ContractAddresses(config), getPublicClient(config), watchers, dateProvider, epochCache, validatorAddresses, undefined);
1095
+ await slasherClient.start();
1096
+ started.push(slasherClient);
1097
+ const l1TxUtils = config.sequencerPublisherForwarderAddress ? await createForwarderL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), config.sequencerPublisherForwarderAddress, {
1098
+ ...config,
1099
+ scope: 'sequencer'
1100
+ }, {
1101
+ telemetry,
1102
+ logger: log.createChild('l1-tx-utils'),
1103
+ dateProvider,
1104
+ kzg: Blob.getViemKzgInstance()
1105
+ }) : await createL1TxUtilsFromSigners(publicClient, keyStoreManager.createAllValidatorPublisherSigners(), {
1106
+ ...config,
1107
+ scope: 'sequencer'
1108
+ }, {
1109
+ telemetry,
1110
+ logger: log.createChild('l1-tx-utils'),
1111
+ dateProvider,
1112
+ kzg: Blob.getViemKzgInstance()
1113
+ });
1114
+ // Create a funder L1TxUtils from the keystore funding account (if configured)
1115
+ const fundingSigner = keyStoreManager?.createFundingSigner();
1116
+ let funderL1TxUtils;
1117
+ if (fundingSigner) {
1118
+ const [funder] = await createL1TxUtilsFromSigners(publicClient, [
1119
+ fundingSigner
1120
+ ], {
1121
+ ...config,
1122
+ scope: 'sequencer'
1123
+ }, {
1124
+ telemetry,
1125
+ logger: log.createChild('l1-tx-utils:funder'),
1126
+ dateProvider
1127
+ });
1128
+ funderL1TxUtils = funder;
1129
+ }
1130
+ // Create and start the sequencer client
1131
+ const checkpointsBuilder = new CheckpointsBuilder({
1132
+ ...config,
1133
+ l1GenesisTime,
1134
+ slotDuration: Number(slotDuration),
1135
+ rollupManaLimit
1136
+ }, worldStateSynchronizer, archiver, dateProvider, telemetry, debugLogStore);
1137
+ if (config.useAutomineSequencer) {
1138
+ // Test-only path: deterministic, queue-driven sequencer for non-block-building e2e tests.
1139
+ // See `AUTOMINE_E2E_OPTS` in `end-to-end/src/fixtures/fixtures.ts`.
1140
+ automineSequencer = await createAutomineSequencer({
1141
+ config,
1142
+ l1TxUtils,
1143
+ funderL1TxUtils,
1144
+ publicClient,
1145
+ rollupContract,
1146
+ epochCache,
1147
+ blobClient,
1148
+ telemetry,
1149
+ dateProvider,
1150
+ keyStoreManager: keyStoreManager,
1151
+ validatorClient,
1152
+ checkpointsBuilder,
1153
+ globalVariableBuilder,
1154
+ worldStateSynchronizer,
1155
+ archiver,
1156
+ p2pClient,
1157
+ l1Constants: {
1158
+ l1GenesisTime,
1159
+ slotDuration: Number(slotDuration),
1160
+ ethereumSlotDuration: config.ethereumSlotDuration,
1161
+ rollupManaLimit
1162
+ },
1163
+ log
1164
+ });
1165
+ } else {
1166
+ sequencer = await SequencerClient.new(config, {
1167
+ ...deps,
1168
+ epochCache,
1169
+ l1TxUtils,
1170
+ funderL1TxUtils,
1171
+ validatorClient,
1172
+ p2pClient,
1173
+ worldStateSynchronizer,
1174
+ slasherClient,
1175
+ checkpointsBuilder,
1176
+ l2BlockSource: archiver,
1177
+ l1ToL2MessageSource: archiver,
1178
+ telemetry,
1179
+ dateProvider,
1180
+ blobClient,
1181
+ nodeKeyStore: keyStoreManager,
1182
+ globalVariableBuilder
1183
+ });
1184
+ }
1185
+ }
1186
+ if (!options.dontStartSequencer && sequencer) {
1187
+ await sequencer.start();
1188
+ started.push(sequencer);
1189
+ log.verbose(`Sequencer started`);
1190
+ } else if (sequencer) {
1191
+ log.warn(`Sequencer created but not started`);
1192
+ }
1193
+ if (!options.dontStartSequencer && automineSequencer) {
1194
+ await automineSequencer.start();
1195
+ started.push({
1196
+ stop: ()=>automineSequencer.stop()
1197
+ });
1198
+ log.verbose(`AutomineSequencer started`);
1199
+ } else if (automineSequencer) {
1200
+ log.warn(`AutomineSequencer created but not started`);
1201
+ }
1202
+ // Create prover node subsystem if enabled
1203
+ let proverNode;
1204
+ if (config.enableProverNode) {
1205
+ proverNode = await createProverNode(config, {
1206
+ ...deps.proverNodeDeps,
1207
+ telemetry,
1208
+ dateProvider,
1209
+ archiver,
1210
+ worldStateSynchronizer,
1211
+ p2pClient,
1212
+ epochCache,
1213
+ blobClient,
1214
+ keyStoreManager
1215
+ });
1216
+ if (!options.dontStartProverNode) {
1217
+ await proverNode.start();
1218
+ started.push(proverNode);
1219
+ log.info(`Prover node subsystem started`);
1220
+ } else {
1221
+ log.info(`Prover node subsystem created but not started`);
1222
+ }
1223
+ }
1224
+ 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);
1225
+ return node;
1226
+ } catch (err) {
1227
+ log.error('Failed during node creation, stopping started resources', err);
1228
+ for (const resource of started.reverse()){
1229
+ await tryStop(resource);
774
1230
  }
1231
+ throw err;
775
1232
  }
776
- const globalVariableBuilder = new GlobalVariableBuilder({
777
- ...config,
778
- rollupVersion: BigInt(config.rollupVersion),
779
- l1GenesisTime,
780
- slotDuration: Number(slotDuration)
781
- });
782
- 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);
783
- return node;
784
1233
  }
785
1234
  /**
786
1235
  * Returns the sequencer client instance.
@@ -788,6 +1237,9 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
788
1237
  */ getSequencer() {
789
1238
  return this.sequencer;
790
1239
  }
1240
+ /** Test-only: returns the AutomineSequencer when wired via `useAutomineSequencer`. */ getAutomineSequencer() {
1241
+ return this.automineSequencer;
1242
+ }
791
1243
  /** Returns the prover node subsystem, if enabled. */ getProverNode() {
792
1244
  return this.proverNode;
793
1245
  }
@@ -804,7 +1256,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
804
1256
  * Method to return the currently deployed L1 contract addresses.
805
1257
  * @returns - The currently deployed L1 contract addresses.
806
1258
  */ getL1ContractAddresses() {
807
- return Promise.resolve(this.config.l1Contracts);
1259
+ return Promise.resolve(pickL1ContractAddresses(this.config));
808
1260
  }
809
1261
  getEncodedEnr() {
810
1262
  return Promise.resolve(this.p2pClient.getEnr()?.encodeTxt());
@@ -841,64 +1293,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
841
1293
  };
842
1294
  return nodeInfo;
843
1295
  }
844
- /**
845
- * Get a block specified by its block number, block hash, or 'latest'.
846
- * @param block - The block parameter (block number, block hash, or 'latest').
847
- * @returns The requested block.
848
- */ async getBlock(block) {
849
- if (BlockHash.isBlockHash(block)) {
850
- return this.getBlockByHash(block);
851
- }
852
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
853
- if (blockNumber === BlockNumber.ZERO) {
854
- return this.buildInitialBlock();
855
- }
856
- return await this.blockSource.getL2Block(blockNumber);
857
- }
858
- /**
859
- * Get a block specified by its hash.
860
- * @param blockHash - The block hash being requested.
861
- * @returns The requested block.
862
- */ async getBlockByHash(blockHash) {
863
- const initialBlockHash = await this.#getInitialHeaderHash();
864
- if (blockHash.equals(initialBlockHash)) {
865
- return this.buildInitialBlock();
866
- }
867
- return await this.blockSource.getL2BlockByHash(blockHash);
868
- }
869
- buildInitialBlock() {
870
- const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
871
- return L2Block.empty(initialHeader);
872
- }
873
- /**
874
- * Get a block specified by its archive root.
875
- * @param archive - The archive root being requested.
876
- * @returns The requested block.
877
- */ async getBlockByArchive(archive) {
878
- return await this.blockSource.getL2BlockByArchive(archive);
879
- }
880
- /**
881
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
882
- * @param from - The start of the range of blocks to return.
883
- * @param limit - The maximum number of blocks to obtain.
884
- * @returns The blocks requested.
885
- */ async getBlocks(from, limit) {
886
- return await this.blockSource.getBlocks(from, BlockNumber(limit)) ?? [];
887
- }
888
- async getCheckpoints(from, limit) {
889
- return await this.blockSource.getCheckpoints(from, limit) ?? [];
890
- }
891
- async getCheckpointedBlocks(from, limit) {
892
- return await this.blockSource.getCheckpointedBlocks(from, limit) ?? [];
1296
+ async getCurrentMinFees() {
1297
+ return await this.feeProvider.getCurrentMinFees();
893
1298
  }
894
- getCheckpointsDataForEpoch(epochNumber) {
895
- return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
896
- }
897
- /**
898
- * Method to fetch the current min L2 fees.
899
- * @returns The current min L2 fees.
900
- */ async getCurrentMinFees() {
901
- return await this.globalVariableBuilder.getCurrentMinFees();
1299
+ /** Returns predicted min fees for the current slot and next N slots. */ async getPredictedMinFees(manaUsage) {
1300
+ return await this.feeProvider.getPredictedMinFees(manaUsage);
902
1301
  }
903
1302
  async getMaxPriorityFees() {
904
1303
  for await (const tx of this.p2pClient.iteratePendingTxs()){
@@ -910,21 +1309,6 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
910
1309
  });
911
1310
  }
912
1311
  /**
913
- * Method to fetch the latest block number synchronized by the node.
914
- * @returns The block number.
915
- */ async getBlockNumber() {
916
- return await this.blockSource.getBlockNumber();
917
- }
918
- async getProvenBlockNumber() {
919
- return await this.blockSource.getProvenBlockNumber();
920
- }
921
- async getCheckpointedBlockNumber() {
922
- return await this.blockSource.getCheckpointedL2BlockNumber();
923
- }
924
- getCheckpointNumber() {
925
- return this.blockSource.getCheckpointNumber();
926
- }
927
- /**
928
1312
  * Method to fetch the version of the package.
929
1313
  * @returns The node package version
930
1314
  */ getNodeVersion() {
@@ -948,43 +1332,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
948
1332
  getContract(address) {
949
1333
  return this.contractDataSource.getContract(address);
950
1334
  }
951
- async getPrivateLogsByTags(tags, page, referenceBlock) {
952
- if (referenceBlock) {
953
- const initialBlockHash = await this.#getInitialHeaderHash();
954
- if (!referenceBlock.equals(initialBlockHash)) {
955
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
956
- if (!header) {
957
- throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
958
- }
959
- }
960
- }
961
- return this.logsSource.getPrivateLogsByTags(tags, page);
962
- }
963
- async getPublicLogsByTagsFromContract(contractAddress, tags, page, referenceBlock) {
964
- if (referenceBlock) {
965
- const initialBlockHash = await this.#getInitialHeaderHash();
966
- if (!referenceBlock.equals(initialBlockHash)) {
967
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
968
- if (!header) {
969
- throw new Error(`Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`);
970
- }
971
- }
972
- }
973
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
974
- }
975
- /**
976
- * Gets public logs based on the provided filter.
977
- * @param filter - The filter to apply to the logs.
978
- * @returns The requested logs.
979
- */ getPublicLogs(filter) {
980
- return this.logsSource.getPublicLogs(filter);
1335
+ getPrivateLogsByTags(query) {
1336
+ return this.logsSource.getPrivateLogsByTags(query);
981
1337
  }
982
- /**
983
- * Gets contract class logs based on the provided filter.
984
- * @param filter - The filter to apply to the logs.
985
- * @returns The requested logs.
986
- */ getContractClassLogs(filter) {
987
- return this.logsSource.getContractClassLogs(filter);
1338
+ getPublicLogsByTags(query) {
1339
+ return this.logsSource.getPublicLogsByTags(query);
988
1340
  }
989
1341
  /**
990
1342
  * Method to submit a transaction to the p2p pool.
@@ -1004,35 +1356,74 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1004
1356
  });
1005
1357
  throw new Error(`Invalid tx: ${reason}`);
1006
1358
  }
1007
- await this.p2pClient.sendTx(tx);
1359
+ try {
1360
+ await this.p2pClient.sendTx(tx);
1361
+ } catch (err) {
1362
+ this.metrics.receivedTx(timer.ms(), false);
1363
+ this.log.warn(`Mempool rejected tx ${txHash}: ${err.message}`, {
1364
+ txHash
1365
+ });
1366
+ throw err;
1367
+ }
1008
1368
  const duration = timer.ms();
1009
1369
  this.metrics.receivedTx(duration, true);
1010
1370
  this.log.info(`Received tx ${txHash} in ${duration}ms`, {
1011
1371
  txHash
1012
1372
  });
1013
1373
  }
1014
- async getTxReceipt(txHash) {
1374
+ async getTxReceipt(txHash, options) {
1015
1375
  // Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
1016
- // as a fallback if we don't find a settled receipt in the archiver.
1376
+ // as a fallback if we don't find a mined tx effect in the archiver.
1017
1377
  const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
1018
1378
  const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
1019
- // Then get the actual tx from the archiver, which tracks every tx in a mined block.
1020
- const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
1379
+ // Then get the raw tx effect from the archiver, which tracks every tx in a mined block.
1380
+ const indexed = await this.blockSource.getTxEffect(txHash);
1021
1381
  let receipt;
1022
- if (settledTxReceipt) {
1023
- receipt = settledTxReceipt;
1382
+ if (indexed) {
1383
+ receipt = await this.#assembleMinedReceipt(indexed, options);
1024
1384
  } else if (isKnownToPool) {
1025
1385
  // If the tx is in the pool but not in the archiver, it's pending.
1026
1386
  // This handles race conditions between archiver and p2p, where the archiver
1027
1387
  // has pruned the block in which a tx was mined, but p2p has not caught up yet.
1028
- receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
1388
+ let tx;
1389
+ if (options?.includePendingTx) {
1390
+ // The tx may have left the pool since we checked its status (mined or dropped); in that case we
1391
+ // leave `tx` unset and still return a pending receipt.
1392
+ const pendingTx = await this.p2pClient.getTxByHashFromPool(txHash);
1393
+ tx = pendingTx && !options.includeProof ? pendingTx.withoutProof() : pendingTx;
1394
+ }
1395
+ receipt = new PendingTxReceipt(txHash, tx);
1029
1396
  } else {
1030
1397
  // Otherwise, if we don't know the tx, we consider it dropped.
1031
- receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
1398
+ receipt = new DroppedTxReceipt(txHash, 'Tx dropped by P2P node');
1032
1399
  }
1033
1400
  this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
1034
1401
  return receipt;
1035
1402
  }
1403
+ /**
1404
+ * Assembles a {@link MinedTxReceipt} from a raw {@link IndexedTxEffect}, deriving the finalization status from the
1405
+ * cached L2 tips and the epoch from the block's slot number.
1406
+ */ async #assembleMinedReceipt(indexed, options) {
1407
+ const blockNumber = indexed.l2BlockNumber;
1408
+ const [tips, l1Constants] = await Promise.all([
1409
+ this.blockSource.getL2Tips(),
1410
+ this.blockSource.getL1Constants()
1411
+ ]);
1412
+ const status = this.#deriveMinedStatus(blockNumber, tips);
1413
+ const epochNumber = getEpochAtSlot(indexed.slotNumber, l1Constants);
1414
+ return new MinedTxReceipt(indexed.data.txHash, status, MinedTxReceipt.executionResultFromRevertCode(indexed.data.revertCode), indexed.data.transactionFee.toBigInt(), indexed.l2BlockHash, blockNumber, indexed.slotNumber, indexed.txIndexInBlock, epochNumber, options?.includeTxEffect ? indexed.data : undefined, /*debugLogs=*/ undefined);
1415
+ }
1416
+ #deriveMinedStatus(blockNumber, tips) {
1417
+ if (blockNumber <= tips.finalized.block.number) {
1418
+ return TxStatus.FINALIZED;
1419
+ } else if (blockNumber <= tips.proven.block.number) {
1420
+ return TxStatus.PROVEN;
1421
+ } else if (blockNumber <= tips.checkpointed.block.number) {
1422
+ return TxStatus.CHECKPOINTED;
1423
+ } else {
1424
+ return TxStatus.PROPOSED;
1425
+ }
1426
+ }
1036
1427
  getTxEffect(txHash) {
1037
1428
  return this.blockSource.getTxEffect(txHash);
1038
1429
  }
@@ -1040,11 +1431,14 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1040
1431
  * Method to stop the aztec node.
1041
1432
  */ async stop() {
1042
1433
  this.log.info(`Stopping Aztec Node`);
1043
- await tryStop(this.validatorsSentinel);
1044
- await tryStop(this.epochPruneWatcher);
1434
+ await this.stopStartedWatchers();
1045
1435
  await tryStop(this.slasherClient);
1046
- await tryStop(this.proofVerifier);
1436
+ await Promise.all([
1437
+ tryStop(this.peerProofVerifier),
1438
+ tryStop(this.rpcProofVerifier)
1439
+ ]);
1047
1440
  await tryStop(this.sequencer);
1441
+ await tryStop(this.automineSequencer);
1048
1442
  await tryStop(this.proverNode);
1049
1443
  await tryStop(this.p2pClient);
1050
1444
  await tryStop(this.worldStateSynchronizer);
@@ -1085,7 +1479,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1085
1479
  return compactArray(await Promise.all(txHashes.map((txHash)=>this.getTxByHash(txHash))));
1086
1480
  }
1087
1481
  async findLeavesIndexes(referenceBlock, treeId, leafValues) {
1088
- const committedDb = await this.#getWorldState(referenceBlock);
1482
+ const committedDb = await this.getWorldState(referenceBlock);
1089
1483
  const maybeIndices = await committedDb.findLeafIndices(treeId, leafValues.map((x)=>x.toBuffer()));
1090
1484
  // Filter out undefined values to query block numbers only for found leaves
1091
1485
  const definedIndices = maybeIndices.filter((x)=>x !== undefined);
@@ -1126,33 +1520,41 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1126
1520
  if (blockNumber === undefined) {
1127
1521
  throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1128
1522
  }
1129
- const blockHash = blockNumberToHash.get(blockNumber);
1130
- if (blockHash === undefined) {
1523
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
1524
+ if (l2BlockHash === undefined) {
1131
1525
  throw new Error(`Block hash not found for block number ${blockNumber}`);
1132
1526
  }
1133
1527
  return {
1134
1528
  l2BlockNumber: blockNumber,
1135
- l2BlockHash: new BlockHash(blockHash),
1529
+ l2BlockHash,
1136
1530
  data: index
1137
1531
  };
1138
1532
  });
1139
1533
  }
1140
1534
  async getBlockHashMembershipWitness(referenceBlock, blockHash) {
1141
- const committedDb = await this.#getWorldState(referenceBlock);
1535
+ // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
1536
+ // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1537
+ // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1538
+ const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1539
+ if (referenceBlockNumber === BlockNumber.ZERO) {
1540
+ // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
1541
+ return undefined;
1542
+ }
1543
+ const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
1142
1544
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.ARCHIVE, [
1143
1545
  blockHash
1144
1546
  ]);
1145
1547
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1146
1548
  }
1147
1549
  async getNoteHashMembershipWitness(referenceBlock, noteHash) {
1148
- const committedDb = await this.#getWorldState(referenceBlock);
1550
+ const committedDb = await this.getWorldState(referenceBlock);
1149
1551
  const [pathAndIndex] = await committedDb.findSiblingPaths(MerkleTreeId.NOTE_HASH_TREE, [
1150
1552
  noteHash
1151
1553
  ]);
1152
1554
  return pathAndIndex === undefined ? undefined : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
1153
1555
  }
1154
1556
  async getL1ToL2MessageMembershipWitness(referenceBlock, l1ToL2Message) {
1155
- const db = await this.#getWorldState(referenceBlock);
1557
+ const db = await this.getWorldState(referenceBlock);
1156
1558
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [
1157
1559
  l1ToL2Message
1158
1560
  ]);
@@ -1167,40 +1569,31 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1167
1569
  }
1168
1570
  async getL1ToL2MessageCheckpoint(l1ToL2Message) {
1169
1571
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1170
- return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1171
- }
1172
- /**
1173
- * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
1174
- * @param l1ToL2Message - The L1 to L2 message to check.
1175
- * @returns Whether the message is synced and ready to be included in a block.
1176
- */ async isL1ToL2MessageSynced(l1ToL2Message) {
1177
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1178
- return messageIndex !== undefined;
1572
+ return messageIndex !== undefined ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1179
1573
  }
1180
1574
  /**
1181
1575
  * Returns all the L2 to L1 messages in an epoch.
1576
+ *
1577
+ * @deprecated Use {@link getL2ToL1MembershipWitness} to get an L2-to-L1 message witness directly.
1578
+ *
1182
1579
  * @param epoch - The epoch at which to get the data.
1183
1580
  * @returns The L2 to L1 messages (empty array if the epoch is not found).
1184
1581
  */ async getL2ToL1Messages(epoch) {
1185
- // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1186
- const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1187
- const blocksInCheckpoints = [];
1188
- let previousSlotNumber = SlotNumber.ZERO;
1189
- let checkpointIndex = -1;
1190
- for (const checkpointedBlock of checkpointedBlocks){
1191
- const block = checkpointedBlock.block;
1192
- const slotNumber = block.header.globalVariables.slotNumber;
1193
- if (slotNumber !== previousSlotNumber) {
1194
- checkpointIndex++;
1195
- blocksInCheckpoints.push([]);
1196
- previousSlotNumber = slotNumber;
1197
- }
1198
- blocksInCheckpoints[checkpointIndex].push(block);
1199
- }
1200
- return blocksInCheckpoints.map((blocks)=>blocks.map((block)=>block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs)));
1582
+ const blocks = await this.blockSource.getBlocks({
1583
+ epoch,
1584
+ onlyCheckpointed: true
1585
+ });
1586
+ const blocksInCheckpoints = chunkBy(blocks, (block)=>block.header.globalVariables.slotNumber);
1587
+ return blocksInCheckpoints.map((slotBlocks)=>slotBlocks.map((block)=>block.body.txEffects.map((txEffect)=>txEffect.l2ToL1Msgs)));
1588
+ }
1589
+ /**
1590
+ * Returns the L2-to-L1 membership witness for a message in `txHash`. Passthrough to the
1591
+ * archiver's locally-cached resolver — see {@link Archiver.getL2ToL1MembershipWitness}.
1592
+ */ getL2ToL1MembershipWitness(txHash, message, messageIndexInTx) {
1593
+ return this.blockSource.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
1201
1594
  }
1202
1595
  async getNullifierMembershipWitness(referenceBlock, nullifier) {
1203
- const db = await this.#getWorldState(referenceBlock);
1596
+ const db = await this.getWorldState(referenceBlock);
1204
1597
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [
1205
1598
  nullifier.toBuffer()
1206
1599
  ]);
@@ -1214,36 +1607,22 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1214
1607
  }
1215
1608
  return new NullifierMembershipWitness(index, leafPreimage, path);
1216
1609
  }
1217
- /**
1218
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1219
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1220
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1221
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1222
- * @returns The low nullifier membership witness (if found).
1223
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1224
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1225
- * we are trying to prove non-inclusion for.
1226
- *
1227
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1228
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1229
- * index of the nullifier itself when it already exists in the tree.
1230
- * TODO: This is a confusing behavior and we should eventually address that.
1231
- */ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1232
- const committedDb = await this.#getWorldState(referenceBlock);
1610
+ async getLowNullifierMembershipWitness(referenceBlock, nullifier) {
1611
+ const committedDb = await this.getWorldState(referenceBlock);
1233
1612
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1234
1613
  if (!findResult) {
1235
1614
  return undefined;
1236
1615
  }
1237
1616
  const { index, alreadyPresent } = findResult;
1238
1617
  if (alreadyPresent) {
1239
- this.log.warn(`Nullifier ${nullifier.toBigInt()} already exists in the tree`);
1618
+ throw new Error(`Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`);
1240
1619
  }
1241
1620
  const preimageData = await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
1242
1621
  const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
1243
1622
  return new NullifierMembershipWitness(BigInt(index), preimageData, siblingPath);
1244
1623
  }
1245
1624
  async getPublicDataWitness(referenceBlock, leafSlot) {
1246
- const committedDb = await this.#getWorldState(referenceBlock);
1625
+ const committedDb = await this.getWorldState(referenceBlock);
1247
1626
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1248
1627
  if (!lowLeafResult) {
1249
1628
  return undefined;
@@ -1254,7 +1633,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1254
1633
  }
1255
1634
  }
1256
1635
  async getPublicStorageAt(referenceBlock, contract, slot) {
1257
- const committedDb = await this.#getWorldState(referenceBlock);
1636
+ const committedDb = await this.getWorldState(referenceBlock);
1258
1637
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1259
1638
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1260
1639
  if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
@@ -1263,64 +1642,62 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1263
1642
  const preimage = await committedDb.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
1264
1643
  return preimage.leaf.value;
1265
1644
  }
1266
- async getBlockHeader(block = 'latest') {
1267
- if (BlockHash.isBlockHash(block)) {
1268
- const initialBlockHash = await this.#getInitialHeaderHash();
1269
- if (block.equals(initialBlockHash)) {
1270
- // Block source doesn't handle initial header so we need to handle the case separately.
1271
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1272
- }
1273
- return this.blockSource.getBlockHeaderByHash(block);
1274
- } else {
1275
- // Block source doesn't handle initial header so we need to handle the case separately.
1276
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : block;
1277
- if (blockNumber === BlockNumber.ZERO) {
1278
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1279
- }
1280
- return this.blockSource.getBlockHeader(block);
1281
- }
1282
- }
1283
- /**
1284
- * Get a block header specified by its archive root.
1285
- * @param archive - The archive root being requested.
1286
- * @returns The requested block header.
1287
- */ async getBlockHeaderByArchive(archive) {
1288
- return await this.blockSource.getBlockHeaderByArchive(archive);
1289
- }
1290
- getBlockData(number) {
1291
- return this.blockSource.getBlockData(number);
1292
- }
1293
- getBlockDataByArchive(archive) {
1294
- return this.blockSource.getBlockDataByArchive(archive);
1295
- }
1296
1645
  /**
1297
1646
  * Simulates the public part of a transaction with the current state.
1298
1647
  * @param tx - The transaction to simulate.
1299
- **/ async simulatePublicCalls(tx, skipFeeEnforcement = false) {
1300
- // Check total gas limit for simulation
1301
- const gasSettings = tx.data.constants.txContext.gasSettings;
1302
- const txGasLimit = gasSettings.gasLimits.l2Gas;
1303
- const teardownGasLimit = gasSettings.teardownGasLimits.l2Gas;
1304
- if (txGasLimit + teardownGasLimit > this.config.rpcSimulatePublicMaxGasLimit) {
1305
- throw new BadRequestError(`Transaction total gas limit ${txGasLimit + teardownGasLimit} (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${this.config.rpcSimulatePublicMaxGasLimit} for simulation`);
1306
- }
1307
- const txHash = tx.getTxHash();
1308
- const latestBlockNumber = await this.blockSource.getBlockNumber();
1309
- const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1310
- // If sequencer is not initialized, we just set these values to zero for simulation.
1311
- const coinbase = EthAddress.ZERO;
1312
- const feeRecipient = AztecAddress.ZERO;
1313
- const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(blockNumber, coinbase, feeRecipient);
1314
- const publicProcessorFactory = new PublicProcessorFactory(this.contractDataSource, new DateProvider(), this.telemetry, this.log.getBindings());
1315
- this.log.verbose(`Simulating public calls for tx ${txHash}`, {
1316
- globalVariables: newGlobalVariables.toInspect(),
1317
- txHash,
1318
- blockNumber
1319
- });
1320
- // Ensure world-state has caught up with the latest block we loaded from the archiver
1321
- await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1322
- const merkleTreeFork = await this.worldStateSynchronizer.fork();
1648
+ * @param skipFeeEnforcement - If true, fee enforcement is skipped.
1649
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
1650
+ **/ async simulatePublicCalls(tx, skipFeeEnforcement = false, overrides) {
1651
+ const env = {
1652
+ stack: [],
1653
+ error: void 0,
1654
+ hasError: false
1655
+ };
1323
1656
  try {
1657
+ // Check total gas limit for simulation
1658
+ const gasSettings = tx.data.constants.txContext.gasSettings;
1659
+ const txGasLimit = gasSettings.gasLimits.l2Gas;
1660
+ const teardownGasLimit = gasSettings.teardownGasLimits.l2Gas;
1661
+ if (txGasLimit + teardownGasLimit > this.config.rpcSimulatePublicMaxGasLimit) {
1662
+ throw new BadRequestError(`Transaction total gas limit ${txGasLimit + teardownGasLimit} (${txGasLimit} + ${teardownGasLimit}) exceeds maximum gas limit ${this.config.rpcSimulatePublicMaxGasLimit} for simulation`);
1663
+ }
1664
+ const txHash = tx.getTxHash();
1665
+ const l2Tips = await this.blockSource.getL2Tips();
1666
+ const latestBlockNumber = l2Tips.proposed.number;
1667
+ const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1668
+ // If sequencer is not initialized, we just set these values to zero for simulation.
1669
+ const coinbase = EthAddress.ZERO;
1670
+ const feeRecipient = AztecAddress.ZERO;
1671
+ const newGlobalVariables = await this.globalVariableBuilder.buildGlobalVariables(blockNumber, coinbase, feeRecipient);
1672
+ const publicProcessorFactory = new PublicProcessorFactory(this.contractDataSource, new DateProvider(), this.telemetry, this.log.getBindings());
1673
+ this.log.verbose(`Simulating public calls for tx ${txHash}`, {
1674
+ globalVariables: newGlobalVariables.toInspect(),
1675
+ txHash,
1676
+ blockNumber
1677
+ });
1678
+ // Ensure world-state has caught up with the latest block we loaded from the archiver
1679
+ await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1680
+ // If we detect the next block would start a new checkpoint, then insert L1-to-L2 messages into
1681
+ // the world state tree so simulation can take them into account. We detect if the next block would
1682
+ // start a new checkpoint by checking if the proposed checkpoint's block number matches the latest block number,
1683
+ // which means the next block would be the first block of the next checkpoint.
1684
+ const targetCheckpoint = CheckpointNumber((l2Tips.proposedCheckpoint.checkpoint.number ?? CheckpointNumber.ZERO) + 1);
1685
+ const nextCheckpointMessages = l2Tips.proposedCheckpoint.block.number === l2Tips.proposed.number ? await this.l1ToL2MessageSource.getL1ToL2Messages(targetCheckpoint).catch((err)=>{
1686
+ if (isErrorClass(err, L1ToL2MessagesNotReadyError)) {
1687
+ this.log.warn(`L1-to-L2 messages for checkpoint ${targetCheckpoint} are not ready yet (simulating without them)`);
1688
+ } else {
1689
+ this.log.error(`Failed to get L1-to-L2 messages for checkpoint ${targetCheckpoint} (simulating without them)`, err);
1690
+ }
1691
+ return undefined;
1692
+ }) : undefined;
1693
+ const merkleTreeFork = _ts_add_disposable_resource(env, await this.worldStateSynchronizer.fork(latestBlockNumber), true);
1694
+ if (nextCheckpointMessages !== undefined) {
1695
+ this.log.debug(`Appending ${nextCheckpointMessages.length} L1-to-L2 messages to the world state tree for the next checkpoint`, {
1696
+ checkpointNumber: l2Tips.proposedCheckpoint.checkpoint.number + 1
1697
+ });
1698
+ await appendL1ToL2MessagesToTree(merkleTreeFork, nextCheckpointMessages);
1699
+ }
1700
+ await applyPublicDataOverrides(merkleTreeFork, overrides?.publicStorage);
1324
1701
  const config = PublicSimulatorConfig.from({
1325
1702
  skipFeeEnforcement,
1326
1703
  collectDebugLogs: true,
@@ -1331,7 +1708,11 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1331
1708
  maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads
1332
1709
  })
1333
1710
  });
1334
- const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1711
+ const contractsDB = new PublicContractsDB(this.contractDataSource, this.log.getBindings());
1712
+ if (overrides?.contracts) {
1713
+ contractsDB.addContracts(Object.values(overrides.contracts).map(({ instance })=>instance));
1714
+ }
1715
+ const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config, contractsDB);
1335
1716
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1336
1717
  const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([
1337
1718
  tx
@@ -1345,13 +1726,17 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1345
1726
  }
1346
1727
  const [processedTx] = processedTxs;
1347
1728
  return new PublicSimulationOutput(processedTx.revertReason, processedTx.globalVariables, processedTx.txEffect, returns, processedTx.gasUsed, debugLogs);
1729
+ } catch (e) {
1730
+ env.error = e;
1731
+ env.hasError = true;
1348
1732
  } finally{
1349
- await merkleTreeFork.close();
1733
+ const result = _ts_dispose_resources(env);
1734
+ if (result) await result;
1350
1735
  }
1351
1736
  }
1352
1737
  async isValidTx(tx, { isSimulation, skipFeeEnforcement } = {}) {
1353
1738
  const db = this.worldStateSynchronizer.getCommitted();
1354
- const verifier = isSimulation ? undefined : this.proofVerifier;
1739
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1355
1740
  // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1356
1741
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1357
1742
  const blockNumber = BlockNumber(await this.blockSource.getBlockNumber() + 1);
@@ -1384,7 +1769,20 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1384
1769
  ...this.config,
1385
1770
  ...config
1386
1771
  };
1387
- this.sequencer?.updateConfig(config);
1772
+ // If the sequencer is currently paused via pauseSequencer(), record the caller's desired
1773
+ // minTxsPerBlock as the restore value (so resumeSequencer applies it) and keep the freeze
1774
+ // (MAX_SAFE_INTEGER) applied to the underlying sequencer. Without this guard, forwarding
1775
+ // the new minTxsPerBlock to the sequencer would silently unpause block production while
1776
+ // pauseSequencer() still considers it paused.
1777
+ const sequencerUpdate = {
1778
+ ...config
1779
+ };
1780
+ if (this.sequencerPausedMinTxsPerBlock !== undefined && sequencerUpdate.minTxsPerBlock !== undefined) {
1781
+ this.sequencerPausedMinTxsPerBlock = sequencerUpdate.minTxsPerBlock;
1782
+ delete sequencerUpdate.minTxsPerBlock;
1783
+ }
1784
+ this.sequencer?.updateConfig(sequencerUpdate);
1785
+ this.automineSequencer?.updateConfig(sequencerUpdate);
1388
1786
  this.slasherClient?.updateConfig(config);
1389
1787
  this.validatorsSentinel?.updateConfig(config);
1390
1788
  await this.p2pClient.updateP2PConfig(config);
@@ -1393,7 +1791,18 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1393
1791
  archiver.updateConfig(config);
1394
1792
  }
1395
1793
  if (newConfig.realProofs !== this.config.realProofs) {
1396
- this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
1794
+ await Promise.all([
1795
+ tryStop(this.peerProofVerifier),
1796
+ tryStop(this.rpcProofVerifier)
1797
+ ]);
1798
+ if (newConfig.realProofs) {
1799
+ this.peerProofVerifier = await BatchChonkVerifier.new(newConfig, newConfig.bbChonkVerifyMaxBatch, 'peer');
1800
+ const rpcVerifier = await BBCircuitVerifier.new(newConfig);
1801
+ this.rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, newConfig.numConcurrentIVCVerifiers);
1802
+ } else {
1803
+ this.peerProofVerifier = new TestCircuitVerifier();
1804
+ this.rpcProofVerifier = new TestCircuitVerifier();
1805
+ }
1397
1806
  }
1398
1807
  this.config = newConfig;
1399
1808
  }
@@ -1402,7 +1811,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1402
1811
  classRegistry: ProtocolContractAddress.ContractClassRegistry,
1403
1812
  feeJuice: ProtocolContractAddress.FeeJuice,
1404
1813
  instanceRegistry: ProtocolContractAddress.ContractInstanceRegistry,
1405
- multiCallEntrypoint: ProtocolContractAddress.MultiCallEntrypoint
1814
+ multiCallEntrypoint: STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS
1406
1815
  });
1407
1816
  }
1408
1817
  registerContractFunctionSignatures(signatures) {
@@ -1453,7 +1862,7 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1453
1862
  });
1454
1863
  return Promise.resolve();
1455
1864
  }
1456
- async rollbackTo(targetBlock, force) {
1865
+ async rollbackTo(targetBlock, force, resumeSync = true) {
1457
1866
  const archiver = this.blockSource;
1458
1867
  if (!('rollbackTo' in archiver)) {
1459
1868
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1481,9 +1890,13 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1481
1890
  this.log.error(`Error during rollback`, err);
1482
1891
  throw err;
1483
1892
  } finally{
1484
- this.log.info(`Resuming world state and archiver sync.`);
1485
- this.worldStateSynchronizer.resumeSync();
1486
- archiver.resume();
1893
+ if (resumeSync) {
1894
+ this.log.info(`Resuming world state and archiver sync.`);
1895
+ this.worldStateSynchronizer.resumeSync();
1896
+ archiver.resume();
1897
+ } else {
1898
+ this.log.info(`Sync left paused after rollback (resumeSync=false).`);
1899
+ }
1487
1900
  }
1488
1901
  }
1489
1902
  async pauseSync() {
@@ -1497,18 +1910,51 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1497
1910
  this.blockSource.resume();
1498
1911
  return Promise.resolve();
1499
1912
  }
1500
- getSlashPayloads() {
1501
- if (!this.slasherClient) {
1502
- throw new Error(`Slasher client not enabled`);
1913
+ pauseSequencer() {
1914
+ if (this.automineSequencer) {
1915
+ this.automineSequencer.pause();
1916
+ return Promise.resolve();
1917
+ }
1918
+ if (this.sequencer) {
1919
+ if (this.sequencerPausedMinTxsPerBlock === undefined) {
1920
+ this.sequencerPausedMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock ?? 0;
1921
+ this.sequencer.updateConfig({
1922
+ minTxsPerBlock: Number.MAX_SAFE_INTEGER
1923
+ });
1924
+ this.log.info(`Sequencer paused (minTxsPerBlock set to MAX_SAFE_INTEGER)`, {
1925
+ previousMinTxsPerBlock: this.sequencerPausedMinTxsPerBlock
1926
+ });
1927
+ }
1928
+ return Promise.resolve();
1929
+ }
1930
+ throw new BadRequestError('Cannot pause sequencer: no sequencer is running');
1931
+ }
1932
+ resumeSequencer() {
1933
+ if (this.automineSequencer) {
1934
+ this.automineSequencer.resume();
1935
+ return Promise.resolve();
1936
+ }
1937
+ if (this.sequencer) {
1938
+ if (this.sequencerPausedMinTxsPerBlock !== undefined) {
1939
+ const restored = this.sequencerPausedMinTxsPerBlock;
1940
+ this.sequencerPausedMinTxsPerBlock = undefined;
1941
+ this.sequencer.updateConfig({
1942
+ minTxsPerBlock: restored
1943
+ });
1944
+ this.log.info(`Sequencer resumed (minTxsPerBlock restored)`, {
1945
+ minTxsPerBlock: restored
1946
+ });
1947
+ }
1948
+ return Promise.resolve();
1503
1949
  }
1504
- return this.slasherClient.getSlashPayloads();
1950
+ throw new BadRequestError('Cannot resume sequencer: no sequencer is running');
1505
1951
  }
1506
1952
  getSlashOffenses(round) {
1507
1953
  if (!this.slasherClient) {
1508
1954
  throw new Error(`Slasher client not enabled`);
1509
1955
  }
1510
1956
  if (round === 'all') {
1511
- return this.slasherClient.getPendingOffenses();
1957
+ return this.slasherClient.getOffenses();
1512
1958
  } else {
1513
1959
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1514
1960
  }
@@ -1580,57 +2026,104 @@ _dec = trackSpan('AztecNodeService.simulatePublicCalls', (tx)=>({
1580
2026
  this.keyStoreManager = newManager;
1581
2027
  this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1582
2028
  }
1583
- #getInitialHeaderHash() {
1584
- if (!this.initialHeaderHashPromise) {
1585
- this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
2029
+ async mineBlock() {
2030
+ if (this.automineSequencer) {
2031
+ await this.automineSequencer.buildEmptyBlock();
2032
+ return;
2033
+ }
2034
+ if (!this.sequencer) {
2035
+ throw new BadRequestError('Cannot mine block: no sequencer is running');
2036
+ }
2037
+ const currentBlockNumber = await this.getBlockNumber();
2038
+ // Use slot duration + 50% buffer as the timeout so this works on running networks too
2039
+ const { slotDuration } = await this.blockSource.getL1Constants();
2040
+ const timeoutSeconds = Math.ceil(slotDuration * 1.5);
2041
+ // Temporarily set minTxsPerBlock to 0 so the sequencer produces a block even with no txs
2042
+ const originalMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock;
2043
+ this.sequencer.updateConfig({
2044
+ minTxsPerBlock: 0
2045
+ });
2046
+ try {
2047
+ // Trigger the sequencer to produce a block immediately
2048
+ void this.sequencer.trigger();
2049
+ // Wait for the new L2 block to appear
2050
+ await retryUntil(async ()=>{
2051
+ const newBlockNumber = await this.getBlockNumber();
2052
+ return newBlockNumber > currentBlockNumber ? true : undefined;
2053
+ }, 'mineBlock', timeoutSeconds, 0.1);
2054
+ } finally{
2055
+ this.sequencer.updateConfig({
2056
+ minTxsPerBlock: originalMinTxsPerBlock
2057
+ });
1586
2058
  }
1587
- return this.initialHeaderHashPromise;
1588
2059
  }
1589
2060
  /**
1590
2061
  * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1591
2062
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1592
2063
  * @returns An instance of a committed MerkleTreeOperations
1593
- */ async #getWorldState(block) {
2064
+ */ async getWorldState(block) {
2065
+ const query = this.normalizeBlockParameter(block);
2066
+ // When the request anchors on a specific block hash, resolve it against the archiver up front and
2067
+ // drive the world-state sync to that exact block number and hash. Resolving against the archiver
2068
+ // first fails fast with a clear reorg error if the hash is unknown, and passing the hash to the
2069
+ // synchronizer makes the sync reorg-aware: it barriers until the archive-tree commit for that block
2070
+ // has landed and verifies it matches the requested fork, instead of syncing to bare latest height
2071
+ // and then racing the snapshot read below against an in-flight archive-tree write.
2072
+ const requestedHash = 'hash' in query ? query.hash : undefined;
2073
+ const anchorBlockNumber = requestedHash !== undefined ? await this.resolveBlockNumber(query) : undefined;
1594
2074
  let blockSyncedTo = BlockNumber.ZERO;
1595
2075
  try {
1596
2076
  // Attempt to sync the world state if necessary
1597
- blockSyncedTo = await this.#syncWorldState();
2077
+ blockSyncedTo = await this.#syncWorldState(anchorBlockNumber, requestedHash);
1598
2078
  } catch (err) {
1599
2079
  this.log.error(`Error getting world state: ${err}`);
1600
2080
  }
1601
- if (block === 'latest') {
1602
- this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
2081
+ if ('tag' in query && query.tag === 'proposed') {
2082
+ this.log.debug(`Using committed db for latest block, world state synced upto ${blockSyncedTo}`);
1603
2083
  return this.worldStateSynchronizer.getCommitted();
1604
2084
  }
1605
- if (BlockHash.isBlockHash(block)) {
1606
- const initialBlockHash = await this.#getInitialHeaderHash();
1607
- if (block.equals(initialBlockHash)) {
1608
- // Block source doesn't handle initial header so we need to handle the case separately.
1609
- return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1610
- }
1611
- const header = await this.blockSource.getBlockHeaderByHash(block);
1612
- if (!header) {
1613
- 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.`);
2085
+ const blockNumber = anchorBlockNumber ?? await this.resolveBlockNumber(query);
2086
+ // Check it's within world state sync range
2087
+ if (blockNumber > blockSyncedTo) {
2088
+ throw new Error(`Queried block ${inspectBlockParameter(block)} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
2089
+ }
2090
+ this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
2091
+ const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
2092
+ // Double-check world-state synced to the same block hash as was requested.
2093
+ // Block 0 is skipped: the snapshot returned by `getSnapshot(0)` is the *pre*-genesis archive
2094
+ // (size 0), so leaf 0 is not yet inserted from that snapshot's view even though block 0's hash
2095
+ // does live at archive index 0 in the committed tree. The genesis hash is already validated by
2096
+ // the archiver when it resolves the hash query to block number 0.
2097
+ if (requestedHash !== undefined && blockNumber !== BlockNumber.ZERO) {
2098
+ const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
2099
+ if (!blockHash || !requestedHash.equals(blockHash)) {
2100
+ 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.`);
1614
2101
  }
1615
- const blockNumber = header.getBlockNumber();
1616
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1617
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1618
2102
  }
1619
- // Block number provided
1620
- {
1621
- const blockNumber = block;
1622
- if (blockNumber > blockSyncedTo) {
1623
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
2103
+ return snapshot;
2104
+ }
2105
+ /** Resolves any {@link BlockParameter} variant to a concrete block number. */ async resolveBlockNumber(block) {
2106
+ const query = this.normalizeBlockParameter(block);
2107
+ const blockNumber = await this.blockSource.getBlockNumber(query);
2108
+ if (blockNumber === undefined) {
2109
+ if ('hash' in query) {
2110
+ 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.`);
2111
+ }
2112
+ if ('archive' in query) {
2113
+ throw new Error(`Block with archive ${query.archive.toString()} not found.`);
1624
2114
  }
1625
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1626
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
2115
+ throw new Error(`Block not found for ${inspectBlockParameter(block)}.`);
1627
2116
  }
2117
+ return blockNumber;
1628
2118
  }
1629
2119
  /**
1630
- * Ensure we fully sync the world state
2120
+ * Ensure the world state is synced.
2121
+ * @param targetBlockNumber - Block to sync up to. Defaults to the latest block known to the archiver.
2122
+ * @param blockHash - If provided, the synchronizer verifies the block at `targetBlockNumber` matches this
2123
+ * hash, resyncing (and so detecting reorgs) if it does not yet match or has been reorged away.
1631
2124
  * @returns A promise that fulfils once the world state is synced
1632
- */ async #syncWorldState() {
1633
- const blockSourceHeight = await this.blockSource.getBlockNumber();
1634
- return await this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
2125
+ */ async #syncWorldState(targetBlockNumber, blockHash) {
2126
+ const target = targetBlockNumber ?? await this.blockSource.getBlockNumber();
2127
+ return await this.worldStateSynchronizer.syncImmediate(target, blockHash);
1635
2128
  }
1636
2129
  }