@aztec/aztec-node 0.0.1-commit.c0b82b2 → 0.0.1-commit.c2eed6949

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.
@@ -1,15 +1,17 @@
1
1
  import { Archiver, createArchiver } from '@aztec/archiver';
2
- import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
2
+ import { BBCircuitVerifier, BatchChonkVerifier, QueuedIVCVerifier } from '@aztec/bb-prover';
3
+ import { TestCircuitVerifier } from '@aztec/bb-prover/test';
3
4
  import { type BlobClientInterface, createBlobClientWithFileStores } from '@aztec/blob-client/client';
4
5
  import { Blob } from '@aztec/blob-lib';
5
6
  import { ARCHIVE_HEIGHT, type L1_TO_L2_MSG_TREE_HEIGHT, type NOTE_HASH_TREE_HEIGHT } from '@aztec/constants';
6
7
  import { EpochCache, type EpochCacheInterface } from '@aztec/epoch-cache';
7
8
  import { createEthereumChain } from '@aztec/ethereum/chain';
8
- import { getPublicClient } from '@aztec/ethereum/client';
9
+ import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
9
10
  import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
10
11
  import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
12
+ import type { L1TxUtils } from '@aztec/ethereum/l1-tx-utils';
11
13
  import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
12
- import { compactArray, pick, unique } from '@aztec/foundation/collection';
14
+ import { chunkBy, compactArray, pick, unique } from '@aztec/foundation/collection';
13
15
  import { Fr } from '@aztec/foundation/curves/bn254';
14
16
  import { EthAddress } from '@aztec/foundation/eth-address';
15
17
  import { BadRequestError } from '@aztec/foundation/json-rpc';
@@ -111,9 +113,10 @@ import {
111
113
  createBlockProposalHandler,
112
114
  createValidatorClient,
113
115
  } from '@aztec/validator-client';
116
+ import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
114
117
  import { createWorldStateSynchronizer } from '@aztec/world-state';
115
118
 
116
- import { createPublicClient, fallback, http } from 'viem';
119
+ import { createPublicClient } from 'viem';
117
120
 
118
121
  import { createSentinel } from '../sentinel/factory.js';
119
122
  import { Sentinel } from '../sentinel/sentinel.js';
@@ -150,7 +153,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
150
153
  protected readonly globalVariableBuilder: GlobalVariableBuilderInterface,
151
154
  protected readonly epochCache: EpochCacheInterface,
152
155
  protected readonly packageVersion: string,
153
- private proofVerifier: ClientProtocolCircuitVerifier,
156
+ private peerProofVerifier: ClientProtocolCircuitVerifier,
157
+ private rpcProofVerifier: ClientProtocolCircuitVerifier,
154
158
  private telemetry: TelemetryClient = getTelemetryClient(),
155
159
  private log = createLogger('node'),
156
160
  private blobClient?: BlobClientInterface,
@@ -172,6 +176,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
172
176
  }
173
177
  }
174
178
 
179
+ /** @internal Exposed for testing — returns the RPC proof verifier. */
180
+ public getProofVerifier(): ClientProtocolCircuitVerifier {
181
+ return this.rpcProofVerifier;
182
+ }
183
+
175
184
  public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
176
185
  const status = await this.worldStateSynchronizer.status();
177
186
  return status.syncSummary;
@@ -195,6 +204,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
195
204
  dateProvider?: DateProvider;
196
205
  p2pClientDeps?: P2PClientDeps;
197
206
  proverNodeDeps?: Partial<ProverNodeDeps>;
207
+ slashingProtectionDb?: SlashingProtectionDatabase;
198
208
  } = {},
199
209
  options: {
200
210
  prefilledPublicData?: PublicDataTreeLeaf[];
@@ -257,7 +267,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
257
267
 
258
268
  const publicClient = createPublicClient({
259
269
  chain: ethereumChain.chainInfo,
260
- transport: fallback(config.l1RpcUrls.map((url: string) => http(url, { batch: false }))),
270
+ transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
261
271
  pollingInterval: config.viemPollingIntervalMS,
262
272
  });
263
273
 
@@ -271,10 +281,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
271
281
  config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
272
282
 
273
283
  const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
274
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
284
+ const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
275
285
  rollupContract.getL1GenesisTime(),
276
286
  rollupContract.getSlotDuration(),
277
287
  rollupContract.getVersion(),
288
+ rollupContract.getManaLimit().then(Number),
278
289
  ] as const);
279
290
 
280
291
  config.rollupVersion ??= Number(rollupVersionFromRollup);
@@ -305,10 +316,17 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
305
316
  options.prefilledPublicData,
306
317
  telemetry,
307
318
  );
308
- const circuitVerifier =
309
- config.realProofs || config.debugForceTxProofVerification
310
- ? await BBCircuitVerifier.new(config)
311
- : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
319
+ const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
320
+ let peerProofVerifier: ClientProtocolCircuitVerifier;
321
+ let rpcProofVerifier: ClientProtocolCircuitVerifier;
322
+ if (useRealVerifiers) {
323
+ peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
324
+ const rpcVerifier = await BBCircuitVerifier.new(config);
325
+ rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
326
+ } else {
327
+ peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
328
+ rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
329
+ }
312
330
 
313
331
  let debugLogStore: DebugLogStore;
314
332
  if (!config.realProofs) {
@@ -322,8 +340,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
322
340
  debugLogStore = new NullDebugLogStore();
323
341
  }
324
342
 
325
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
326
-
327
343
  const proverOnly = config.enableProverNode && config.disableValidator;
328
344
  if (proverOnly) {
329
345
  log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
@@ -333,7 +349,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
333
349
  const p2pClient = await createP2PClient(
334
350
  config,
335
351
  archiver,
336
- proofVerifier,
352
+ peerProofVerifier,
337
353
  worldStateSynchronizer,
338
354
  epochCache,
339
355
  packageVersion,
@@ -342,15 +358,19 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
342
358
  deps.p2pClientDeps,
343
359
  );
344
360
 
345
- // We should really not be modifying the config object
346
- config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
347
-
348
361
  // We'll accumulate sentinel watchers here
349
362
  const watchers: Watcher[] = [];
350
363
 
351
- // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation
364
+ // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
365
+ // Override maxTxsPerCheckpoint with the validator-specific limit if set.
352
366
  const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
353
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
367
+ {
368
+ ...config,
369
+ l1GenesisTime,
370
+ slotDuration: Number(slotDuration),
371
+ rollupManaLimit,
372
+ maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint,
373
+ },
354
374
  worldStateSynchronizer,
355
375
  archiver,
356
376
  dateProvider,
@@ -372,6 +392,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
372
392
  l1ToL2MessageSource: archiver,
373
393
  keyStoreManager,
374
394
  blobClient,
395
+ slashingProtectionDb: deps.slashingProtectionDb,
375
396
  });
376
397
 
377
398
  // If we have a validator client, register it as a source of offenses for the slasher,
@@ -383,22 +404,24 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
383
404
  await validatorClient.registerHandlers();
384
405
  }
385
406
  }
407
+ }
386
408
 
387
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
388
- // create a BlockProposalHandler to reexecute block proposals for monitoring
389
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
390
- log.info('Setting up block proposal reexecution for monitoring');
391
- createBlockProposalHandler(config, {
392
- checkpointsBuilder: validatorCheckpointsBuilder,
393
- worldState: worldStateSynchronizer,
394
- epochCache,
395
- blockSource: archiver,
396
- l1ToL2MessageSource: archiver,
397
- p2pClient,
398
- dateProvider,
399
- telemetry,
400
- }).registerForReexecution(p2pClient);
401
- }
409
+ // If there's no validator client, create a BlockProposalHandler to handle block proposals
410
+ // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
411
+ // while non-reexecution is used for validating the proposals and collecting their txs.
412
+ if (!validatorClient) {
413
+ const reexecute = !!config.alwaysReexecuteBlockProposals;
414
+ log.info(`Setting up block proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
415
+ createBlockProposalHandler(config, {
416
+ checkpointsBuilder: validatorCheckpointsBuilder,
417
+ worldState: worldStateSynchronizer,
418
+ epochCache,
419
+ blockSource: archiver,
420
+ l1ToL2MessageSource: archiver,
421
+ p2pClient,
422
+ dateProvider,
423
+ telemetry,
424
+ }).register(p2pClient, reexecute);
402
425
  }
403
426
 
404
427
  // Start world state and wait for it to sync to the archiver.
@@ -448,6 +471,14 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
448
471
  })
449
472
  .catch(err => log.error('Failed to start p2p services after archiver sync', err));
450
473
 
474
+ const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, {
475
+ l1Contracts: config.l1Contracts,
476
+ ethereumSlotDuration: config.ethereumSlotDuration,
477
+ rollupVersion: BigInt(config.rollupVersion),
478
+ l1GenesisTime,
479
+ slotDuration: Number(slotDuration),
480
+ });
481
+
451
482
  // Validator enabled, create/start relevant service
452
483
  let sequencer: SequencerClient | undefined;
453
484
  let slasherClient: SlasherClientInterface | undefined;
@@ -485,9 +516,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
485
516
  { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
486
517
  );
487
518
 
519
+ // Create a funder L1TxUtils from the keystore funding account (if configured)
520
+ const fundingSigner = keyStoreManager?.createFundingSigner();
521
+ let funderL1TxUtils: L1TxUtils | undefined;
522
+ if (fundingSigner) {
523
+ const [funder] = await createL1TxUtilsFromSigners(
524
+ publicClient,
525
+ [fundingSigner],
526
+ { ...config, scope: 'sequencer' },
527
+ { telemetry, logger: log.createChild('l1-tx-utils:funder'), dateProvider },
528
+ );
529
+ funderL1TxUtils = funder;
530
+ }
531
+
488
532
  // Create and start the sequencer client
489
533
  const checkpointsBuilder = new CheckpointsBuilder(
490
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
534
+ { ...config, l1GenesisTime, slotDuration: Number(slotDuration), rollupManaLimit },
491
535
  worldStateSynchronizer,
492
536
  archiver,
493
537
  dateProvider,
@@ -499,6 +543,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
499
543
  ...deps,
500
544
  epochCache,
501
545
  l1TxUtils,
546
+ funderL1TxUtils,
502
547
  validatorClient,
503
548
  p2pClient,
504
549
  worldStateSynchronizer,
@@ -510,6 +555,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
510
555
  dateProvider,
511
556
  blobClient,
512
557
  nodeKeyStore: keyStoreManager!,
558
+ globalVariableBuilder,
513
559
  });
514
560
  }
515
561
 
@@ -543,13 +589,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
543
589
  }
544
590
  }
545
591
 
546
- const globalVariableBuilder = new GlobalVariableBuilder({
547
- ...config,
548
- rollupVersion: BigInt(config.rollupVersion),
549
- l1GenesisTime,
550
- slotDuration: Number(slotDuration),
551
- });
552
-
553
592
  const node = new AztecNodeService(
554
593
  config,
555
594
  p2pClient,
@@ -568,7 +607,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
568
607
  globalVariableBuilder,
569
608
  epochCache,
570
609
  packageVersion,
571
- proofVerifier,
610
+ peerProofVerifier,
611
+ rpcProofVerifier,
572
612
  telemetry,
573
613
  log,
574
614
  blobClient,
@@ -618,7 +658,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
618
658
  }
619
659
 
620
660
  public async getAllowedPublicSetup(): Promise<AllowedElement[]> {
621
- return this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
661
+ return [...(await getDefaultAllowedSetupFunctions()), ...(this.config.txPublicSetupAllowListExtend ?? [])];
622
662
  }
623
663
 
624
664
  /**
@@ -713,6 +753,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
713
753
  return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
714
754
  }
715
755
 
756
+ public getCheckpointsDataForEpoch(epochNumber: EpochNumber) {
757
+ return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
758
+ }
759
+
716
760
  /**
717
761
  * Method to fetch the current min L2 fees.
718
762
  * @returns The current min L2 fees.
@@ -745,6 +789,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
745
789
  return await this.blockSource.getCheckpointedL2BlockNumber();
746
790
  }
747
791
 
792
+ public getCheckpointNumber(): Promise<CheckpointNumber> {
793
+ return this.blockSource.getCheckpointNumber();
794
+ }
795
+
748
796
  /**
749
797
  * Method to fetch the version of the package.
750
798
  * @returns The node package version
@@ -782,18 +830,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
782
830
  page?: number,
783
831
  referenceBlock?: BlockHash,
784
832
  ): Promise<TxScopedL2Log[][]> {
833
+ let upToBlockNumber: BlockNumber | undefined;
785
834
  if (referenceBlock) {
786
835
  const initialBlockHash = await this.#getInitialHeaderHash();
787
- if (!referenceBlock.equals(initialBlockHash)) {
836
+ if (referenceBlock.equals(initialBlockHash)) {
837
+ upToBlockNumber = BlockNumber(0);
838
+ } else {
788
839
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
789
840
  if (!header) {
790
841
  throw new Error(
791
842
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
792
843
  );
793
844
  }
845
+ upToBlockNumber = header.globalVariables.blockNumber;
794
846
  }
795
847
  }
796
- return this.logsSource.getPrivateLogsByTags(tags, page);
848
+ return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
797
849
  }
798
850
 
799
851
  public async getPublicLogsByTagsFromContract(
@@ -802,18 +854,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
802
854
  page?: number,
803
855
  referenceBlock?: BlockHash,
804
856
  ): Promise<TxScopedL2Log[][]> {
857
+ let upToBlockNumber: BlockNumber | undefined;
805
858
  if (referenceBlock) {
806
859
  const initialBlockHash = await this.#getInitialHeaderHash();
807
- if (!referenceBlock.equals(initialBlockHash)) {
860
+ if (referenceBlock.equals(initialBlockHash)) {
861
+ upToBlockNumber = BlockNumber(0);
862
+ } else {
808
863
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
809
864
  if (!header) {
810
865
  throw new Error(
811
866
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
812
867
  );
813
868
  }
869
+ upToBlockNumber = header.globalVariables.blockNumber;
814
870
  }
815
871
  }
816
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
872
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
817
873
  }
818
874
 
819
875
  /**
@@ -899,7 +955,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
899
955
  await tryStop(this.validatorsSentinel);
900
956
  await tryStop(this.epochPruneWatcher);
901
957
  await tryStop(this.slasherClient);
902
- await tryStop(this.proofVerifier);
958
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
903
959
  await tryStop(this.sequencer);
904
960
  await tryStop(this.proverNode);
905
961
  await tryStop(this.p2pClient);
@@ -955,58 +1011,64 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
955
1011
  treeId: MerkleTreeId,
956
1012
  leafValues: Fr[],
957
1013
  ): Promise<(DataInBlock<bigint> | undefined)[]> {
958
- const committedDb = await this.#getWorldState(referenceBlock);
1014
+ const committedDb = await this.getWorldState(referenceBlock);
959
1015
  const maybeIndices = await committedDb.findLeafIndices(
960
1016
  treeId,
961
1017
  leafValues.map(x => x.toBuffer()),
962
1018
  );
963
- // We filter out undefined values
964
- const indices = maybeIndices.filter(x => x !== undefined) as bigint[];
1019
+ // Filter out undefined values to query block numbers only for found leaves
1020
+ const definedIndices = maybeIndices.filter(x => x !== undefined);
965
1021
 
966
- // Now we find the block numbers for the indices
967
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
1022
+ // Now we find the block numbers for the defined indices
1023
+ const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
968
1024
 
969
- // If any of the block numbers are undefined, we throw an error.
970
- for (let i = 0; i < indices.length; i++) {
971
- if (blockNumbers[i] === undefined) {
972
- throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
1025
+ // Build a map from leaf index to block number
1026
+ const indexToBlockNumber = new Map<bigint, BlockNumber>();
1027
+ for (let i = 0; i < definedIndices.length; i++) {
1028
+ const blockNumber = blockNumbers[i];
1029
+ if (blockNumber === undefined) {
1030
+ throw new Error(
1031
+ `Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`,
1032
+ );
973
1033
  }
1034
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
974
1035
  }
975
1036
 
976
1037
  // Get unique block numbers in order to optimize num calls to getLeafValue function.
977
- const uniqueBlockNumbers = [...new Set(blockNumbers.filter(x => x !== undefined))];
1038
+ const uniqueBlockNumbers = [...new Set(indexToBlockNumber.values())];
978
1039
 
979
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
980
- // (note that block number corresponds to the leaf index in the archive tree).
1040
+ // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
981
1041
  const blockHashes = await Promise.all(
982
1042
  uniqueBlockNumbers.map(blockNumber => {
983
1043
  return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
984
1044
  }),
985
1045
  );
986
1046
 
987
- // If any of the block hashes are undefined, we throw an error.
1047
+ // Build a map from block number to block hash
1048
+ const blockNumberToHash = new Map<BlockNumber, Fr>();
988
1049
  for (let i = 0; i < uniqueBlockNumbers.length; i++) {
989
- if (blockHashes[i] === undefined) {
1050
+ const blockHash = blockHashes[i];
1051
+ if (blockHash === undefined) {
990
1052
  throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
991
1053
  }
1054
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
992
1055
  }
993
1056
 
994
1057
  // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
995
- return maybeIndices.map((index, i) => {
1058
+ return maybeIndices.map(index => {
996
1059
  if (index === undefined) {
997
1060
  return undefined;
998
1061
  }
999
- const blockNumber = blockNumbers[i];
1062
+ const blockNumber = indexToBlockNumber.get(index);
1000
1063
  if (blockNumber === undefined) {
1001
- return undefined;
1064
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1002
1065
  }
1003
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
1004
- const blockHash = blockHashes[blockHashIndex];
1005
- if (!blockHash) {
1006
- return undefined;
1066
+ const blockHash = blockNumberToHash.get(blockNumber);
1067
+ if (blockHash === undefined) {
1068
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
1007
1069
  }
1008
1070
  return {
1009
- l2BlockNumber: BlockNumber(Number(blockNumber)),
1071
+ l2BlockNumber: blockNumber,
1010
1072
  l2BlockHash: new BlockHash(blockHash),
1011
1073
  data: index,
1012
1074
  };
@@ -1017,7 +1079,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1017
1079
  referenceBlock: BlockParameter,
1018
1080
  blockHash: BlockHash,
1019
1081
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
1020
- const committedDb = await this.#getWorldState(referenceBlock);
1082
+ // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
1083
+ // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1084
+ // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1085
+ const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1086
+ if (referenceBlockNumber === BlockNumber.ZERO) {
1087
+ // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
1088
+ return undefined;
1089
+ }
1090
+ const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
1021
1091
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
1022
1092
  return pathAndIndex === undefined
1023
1093
  ? undefined
@@ -1028,7 +1098,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1028
1098
  referenceBlock: BlockParameter,
1029
1099
  noteHash: Fr,
1030
1100
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
1031
- const committedDb = await this.#getWorldState(referenceBlock);
1101
+ const committedDb = await this.getWorldState(referenceBlock);
1032
1102
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
1033
1103
  MerkleTreeId.NOTE_HASH_TREE,
1034
1104
  [noteHash],
@@ -1042,7 +1112,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1042
1112
  referenceBlock: BlockParameter,
1043
1113
  l1ToL2Message: Fr,
1044
1114
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
1045
- const db = await this.#getWorldState(referenceBlock);
1115
+ const db = await this.getWorldState(referenceBlock);
1046
1116
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
1047
1117
  if (!witness) {
1048
1118
  return undefined;
@@ -1052,11 +1122,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1052
1122
  return [witness.index, witness.path];
1053
1123
  }
1054
1124
 
1055
- public async getL1ToL2MessageBlock(l1ToL2Message: Fr): Promise<BlockNumber | undefined> {
1125
+ public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
1056
1126
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1057
- return messageIndex
1058
- ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex))
1059
- : undefined;
1127
+ return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1060
1128
  }
1061
1129
 
1062
1130
  /**
@@ -1077,19 +1145,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1077
1145
  public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
1078
1146
  // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1079
1147
  const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1080
- const blocksInCheckpoints: L2Block[][] = [];
1081
- let previousSlotNumber = SlotNumber.ZERO;
1082
- let checkpointIndex = -1;
1083
- for (const checkpointedBlock of checkpointedBlocks) {
1084
- const block = checkpointedBlock.block;
1085
- const slotNumber = block.header.globalVariables.slotNumber;
1086
- if (slotNumber !== previousSlotNumber) {
1087
- checkpointIndex++;
1088
- blocksInCheckpoints.push([]);
1089
- previousSlotNumber = slotNumber;
1090
- }
1091
- blocksInCheckpoints[checkpointIndex].push(block);
1092
- }
1148
+ const blocksInCheckpoints = chunkBy(checkpointedBlocks, cb => cb.block.header.globalVariables.slotNumber).map(
1149
+ group => group.map(cb => cb.block),
1150
+ );
1093
1151
  return blocksInCheckpoints.map(blocks =>
1094
1152
  blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1095
1153
  );
@@ -1099,7 +1157,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1099
1157
  referenceBlock: BlockParameter,
1100
1158
  nullifier: Fr,
1101
1159
  ): Promise<NullifierMembershipWitness | undefined> {
1102
- const db = await this.#getWorldState(referenceBlock);
1160
+ const db = await this.getWorldState(referenceBlock);
1103
1161
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
1104
1162
  if (!witness) {
1105
1163
  return undefined;
@@ -1114,33 +1172,20 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1114
1172
  return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
1115
1173
  }
1116
1174
 
1117
- /**
1118
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1119
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1120
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1121
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1122
- * @returns The low nullifier membership witness (if found).
1123
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1124
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1125
- * we are trying to prove non-inclusion for.
1126
- *
1127
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1128
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1129
- * index of the nullifier itself when it already exists in the tree.
1130
- * TODO: This is a confusing behavior and we should eventually address that.
1131
- */
1132
1175
  public async getLowNullifierMembershipWitness(
1133
1176
  referenceBlock: BlockParameter,
1134
1177
  nullifier: Fr,
1135
1178
  ): Promise<NullifierMembershipWitness | undefined> {
1136
- const committedDb = await this.#getWorldState(referenceBlock);
1179
+ const committedDb = await this.getWorldState(referenceBlock);
1137
1180
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1138
1181
  if (!findResult) {
1139
1182
  return undefined;
1140
1183
  }
1141
1184
  const { index, alreadyPresent } = findResult;
1142
1185
  if (alreadyPresent) {
1143
- this.log.warn(`Nullifier ${nullifier.toBigInt()} already exists in the tree`);
1186
+ throw new Error(
1187
+ `Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`,
1188
+ );
1144
1189
  }
1145
1190
  const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
1146
1191
 
@@ -1149,7 +1194,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1149
1194
  }
1150
1195
 
1151
1196
  async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1152
- const committedDb = await this.#getWorldState(referenceBlock);
1197
+ const committedDb = await this.getWorldState(referenceBlock);
1153
1198
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1154
1199
  if (!lowLeafResult) {
1155
1200
  return undefined;
@@ -1164,7 +1209,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1164
1209
  }
1165
1210
 
1166
1211
  public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1167
- const committedDb = await this.#getWorldState(referenceBlock);
1212
+ const committedDb = await this.getWorldState(referenceBlock);
1168
1213
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1169
1214
 
1170
1215
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
@@ -1278,7 +1323,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1278
1323
  const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1279
1324
 
1280
1325
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1281
- const [processedTxs, failedTxs, _usedTxs, returns, _blobFields, debugLogs] = await processor.process([tx]);
1326
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1282
1327
  // REFACTOR: Consider returning the error rather than throwing
1283
1328
  if (failedTxs.length) {
1284
1329
  this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
@@ -1304,11 +1349,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1304
1349
  { isSimulation, skipFeeEnforcement }: { isSimulation?: boolean; skipFeeEnforcement?: boolean } = {},
1305
1350
  ): Promise<TxValidationResult> {
1306
1351
  const db = this.worldStateSynchronizer.getCommitted();
1307
- const verifier = isSimulation ? undefined : this.proofVerifier;
1352
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1308
1353
 
1309
1354
  // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1310
1355
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1311
1356
  const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1357
+ const l1Constants = await this.blockSource.getL1Constants();
1312
1358
  const validator = createTxValidatorForAcceptingTxsOverRPC(
1313
1359
  db,
1314
1360
  this.contractDataSource,
@@ -1318,10 +1364,16 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1318
1364
  blockNumber,
1319
1365
  l1ChainId: this.l1ChainId,
1320
1366
  rollupVersion: this.version,
1321
- setupAllowList: this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions()),
1367
+ setupAllowList: [
1368
+ ...(await getDefaultAllowedSetupFunctions()),
1369
+ ...(this.config.txPublicSetupAllowListExtend ?? []),
1370
+ ],
1322
1371
  gasFees: await this.getCurrentMinFees(),
1323
1372
  skipFeeEnforcement,
1324
1373
  txsPermitted: !this.config.disableTransactions,
1374
+ rollupManaLimit: l1Constants.rollupManaLimit,
1375
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1376
+ maxBlockDAGas: this.config.validateMaxDABlockGas,
1325
1377
  },
1326
1378
  this.log.getBindings(),
1327
1379
  );
@@ -1346,7 +1398,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1346
1398
  archiver.updateConfig(config);
1347
1399
  }
1348
1400
  if (newConfig.realProofs !== this.config.realProofs) {
1349
- this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
1401
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
1402
+ if (newConfig.realProofs) {
1403
+ this.peerProofVerifier = await BatchChonkVerifier.new(newConfig, newConfig.bbChonkVerifyMaxBatch, 'peer');
1404
+ const rpcVerifier = await BBCircuitVerifier.new(newConfig);
1405
+ this.rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, newConfig.numConcurrentIVCVerifiers);
1406
+ } else {
1407
+ this.peerProofVerifier = new TestCircuitVerifier();
1408
+ this.rpcProofVerifier = new TestCircuitVerifier();
1409
+ }
1350
1410
  }
1351
1411
 
1352
1412
  this.config = newConfig;
@@ -1588,7 +1648,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1588
1648
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1589
1649
  * @returns An instance of a committed MerkleTreeOperations
1590
1650
  */
1591
- async #getWorldState(block: BlockParameter) {
1651
+ protected async getWorldState(block: BlockParameter) {
1592
1652
  let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1593
1653
  try {
1594
1654
  // Attempt to sync the world state if necessary
@@ -1602,6 +1662,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1602
1662
  return this.worldStateSynchronizer.getCommitted();
1603
1663
  }
1604
1664
 
1665
+ // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1666
+ let blockNumber: BlockNumber;
1605
1667
  if (BlockHash.isBlockHash(block)) {
1606
1668
  const initialBlockHash = await this.#getInitialHeaderHash();
1607
1669
  if (block.equals(initialBlockHash)) {
@@ -1615,22 +1677,50 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1615
1677
  `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.`,
1616
1678
  );
1617
1679
  }
1618
- const blockNumber = header.getBlockNumber();
1619
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1620
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1680
+
1681
+ blockNumber = header.getBlockNumber();
1682
+ } else {
1683
+ blockNumber = block as BlockNumber;
1684
+ }
1685
+
1686
+ // Check it's within world state sync range
1687
+ if (blockNumber > blockSyncedTo) {
1688
+ throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1621
1689
  }
1690
+ this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1622
1691
 
1623
- // Block number provided
1624
- {
1625
- const blockNumber = block as BlockNumber;
1692
+ const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
1626
1693
 
1627
- if (blockNumber > blockSyncedTo) {
1628
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1694
+ // Double-check world-state synced to the same block hash as was requested
1695
+ if (BlockHash.isBlockHash(block)) {
1696
+ const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1697
+ if (!blockHash || !new BlockHash(blockHash).equals(block)) {
1698
+ throw new Error(
1699
+ `Block hash ${block.toString()} not found in world state at block number ${blockNumber}. If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
1700
+ );
1629
1701
  }
1702
+ }
1703
+
1704
+ return snapshot;
1705
+ }
1630
1706
 
1631
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1632
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1707
+ /** Resolves a block parameter to a block number. */
1708
+ protected async resolveBlockNumber(block: BlockParameter): Promise<BlockNumber> {
1709
+ if (block === 'latest') {
1710
+ return BlockNumber(await this.blockSource.getBlockNumber());
1711
+ }
1712
+ if (BlockHash.isBlockHash(block)) {
1713
+ const initialBlockHash = await this.#getInitialHeaderHash();
1714
+ if (block.equals(initialBlockHash)) {
1715
+ return BlockNumber.ZERO;
1716
+ }
1717
+ const header = await this.blockSource.getBlockHeaderByHash(block);
1718
+ if (!header) {
1719
+ throw new Error(`Block hash ${block.toString()} not found.`);
1720
+ }
1721
+ return header.getBlockNumber();
1633
1722
  }
1723
+ return block as BlockNumber;
1634
1724
  }
1635
1725
 
1636
1726
  /**