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

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';
@@ -108,12 +110,13 @@ import {
108
110
  FullNodeCheckpointsBuilder,
109
111
  NodeKeystoreAdapter,
110
112
  ValidatorClient,
111
- createBlockProposalHandler,
113
+ createProposalHandler,
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,
@@ -345,9 +361,16 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
345
361
  // We'll accumulate sentinel watchers here
346
362
  const watchers: Watcher[] = [];
347
363
 
348
- // 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.
349
366
  const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
350
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
367
+ {
368
+ ...config,
369
+ l1GenesisTime,
370
+ slotDuration: Number(slotDuration),
371
+ rollupManaLimit,
372
+ maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint,
373
+ },
351
374
  worldStateSynchronizer,
352
375
  archiver,
353
376
  dateProvider,
@@ -369,6 +392,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
369
392
  l1ToL2MessageSource: archiver,
370
393
  keyStoreManager,
371
394
  blobClient,
395
+ slashingProtectionDb: deps.slashingProtectionDb,
372
396
  });
373
397
 
374
398
  // If we have a validator client, register it as a source of offenses for the slasher,
@@ -376,26 +400,35 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
376
400
  // like attestations or auths will fail.
377
401
  if (validatorClient) {
378
402
  watchers.push(validatorClient);
403
+
404
+ const vc = validatorClient;
405
+ const getValidatorAddresses = () => vc.getValidatorAddresses().map(a => a.toString());
406
+ validatorClient.getProposalHandler().register(p2pClient, true, archiver, getValidatorAddresses);
407
+
379
408
  if (!options.dontStartSequencer) {
380
409
  await validatorClient.registerHandlers();
381
410
  }
382
411
  }
412
+ }
383
413
 
384
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
385
- // create a BlockProposalHandler to reexecute block proposals for monitoring
386
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
387
- log.info('Setting up block proposal reexecution for monitoring');
388
- createBlockProposalHandler(config, {
389
- checkpointsBuilder: validatorCheckpointsBuilder,
390
- worldState: worldStateSynchronizer,
391
- epochCache,
392
- blockSource: archiver,
393
- l1ToL2MessageSource: archiver,
394
- p2pClient,
395
- dateProvider,
396
- telemetry,
397
- }).registerForReexecution(p2pClient);
398
- }
414
+ // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
415
+ // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
416
+ // while non-reexecution is used for validating the proposals and collecting their txs.
417
+ // Checkpoint proposals rebuild blobs if the blob client can upload blobs.
418
+ if (!validatorClient) {
419
+ const reexecute = !!config.alwaysReexecuteBlockProposals;
420
+ log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
421
+ createProposalHandler(config, {
422
+ checkpointsBuilder: validatorCheckpointsBuilder,
423
+ worldState: worldStateSynchronizer,
424
+ epochCache,
425
+ blockSource: archiver,
426
+ l1ToL2MessageSource: archiver,
427
+ p2pClient,
428
+ blobClient,
429
+ dateProvider,
430
+ telemetry,
431
+ }).register(p2pClient, reexecute, archiver);
399
432
  }
400
433
 
401
434
  // Start world state and wait for it to sync to the archiver.
@@ -445,6 +478,14 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
445
478
  })
446
479
  .catch(err => log.error('Failed to start p2p services after archiver sync', err));
447
480
 
481
+ const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, {
482
+ l1Contracts: config.l1Contracts,
483
+ ethereumSlotDuration: config.ethereumSlotDuration,
484
+ rollupVersion: BigInt(config.rollupVersion),
485
+ l1GenesisTime,
486
+ slotDuration: Number(slotDuration),
487
+ });
488
+
448
489
  // Validator enabled, create/start relevant service
449
490
  let sequencer: SequencerClient | undefined;
450
491
  let slasherClient: SlasherClientInterface | undefined;
@@ -482,9 +523,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
482
523
  { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
483
524
  );
484
525
 
526
+ // Create a funder L1TxUtils from the keystore funding account (if configured)
527
+ const fundingSigner = keyStoreManager?.createFundingSigner();
528
+ let funderL1TxUtils: L1TxUtils | undefined;
529
+ if (fundingSigner) {
530
+ const [funder] = await createL1TxUtilsFromSigners(
531
+ publicClient,
532
+ [fundingSigner],
533
+ { ...config, scope: 'sequencer' },
534
+ { telemetry, logger: log.createChild('l1-tx-utils:funder'), dateProvider },
535
+ );
536
+ funderL1TxUtils = funder;
537
+ }
538
+
485
539
  // Create and start the sequencer client
486
540
  const checkpointsBuilder = new CheckpointsBuilder(
487
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
541
+ { ...config, l1GenesisTime, slotDuration: Number(slotDuration), rollupManaLimit },
488
542
  worldStateSynchronizer,
489
543
  archiver,
490
544
  dateProvider,
@@ -496,6 +550,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
496
550
  ...deps,
497
551
  epochCache,
498
552
  l1TxUtils,
553
+ funderL1TxUtils,
499
554
  validatorClient,
500
555
  p2pClient,
501
556
  worldStateSynchronizer,
@@ -507,6 +562,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
507
562
  dateProvider,
508
563
  blobClient,
509
564
  nodeKeyStore: keyStoreManager!,
565
+ globalVariableBuilder,
510
566
  });
511
567
  }
512
568
 
@@ -540,13 +596,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
540
596
  }
541
597
  }
542
598
 
543
- const globalVariableBuilder = new GlobalVariableBuilder({
544
- ...config,
545
- rollupVersion: BigInt(config.rollupVersion),
546
- l1GenesisTime,
547
- slotDuration: Number(slotDuration),
548
- });
549
-
550
599
  const node = new AztecNodeService(
551
600
  config,
552
601
  p2pClient,
@@ -565,7 +614,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
565
614
  globalVariableBuilder,
566
615
  epochCache,
567
616
  packageVersion,
568
- proofVerifier,
617
+ peerProofVerifier,
618
+ rpcProofVerifier,
569
619
  telemetry,
570
620
  log,
571
621
  blobClient,
@@ -710,6 +760,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
710
760
  return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
711
761
  }
712
762
 
763
+ public getCheckpointsDataForEpoch(epochNumber: EpochNumber) {
764
+ return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
765
+ }
766
+
713
767
  /**
714
768
  * Method to fetch the current min L2 fees.
715
769
  * @returns The current min L2 fees.
@@ -742,6 +796,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
742
796
  return await this.blockSource.getCheckpointedL2BlockNumber();
743
797
  }
744
798
 
799
+ public getCheckpointNumber(): Promise<CheckpointNumber> {
800
+ return this.blockSource.getCheckpointNumber();
801
+ }
802
+
745
803
  /**
746
804
  * Method to fetch the version of the package.
747
805
  * @returns The node package version
@@ -779,18 +837,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
779
837
  page?: number,
780
838
  referenceBlock?: BlockHash,
781
839
  ): Promise<TxScopedL2Log[][]> {
840
+ let upToBlockNumber: BlockNumber | undefined;
782
841
  if (referenceBlock) {
783
842
  const initialBlockHash = await this.#getInitialHeaderHash();
784
- if (!referenceBlock.equals(initialBlockHash)) {
843
+ if (referenceBlock.equals(initialBlockHash)) {
844
+ upToBlockNumber = BlockNumber(0);
845
+ } else {
785
846
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
786
847
  if (!header) {
787
848
  throw new Error(
788
849
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
789
850
  );
790
851
  }
852
+ upToBlockNumber = header.globalVariables.blockNumber;
791
853
  }
792
854
  }
793
- return this.logsSource.getPrivateLogsByTags(tags, page);
855
+ return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
794
856
  }
795
857
 
796
858
  public async getPublicLogsByTagsFromContract(
@@ -799,18 +861,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
799
861
  page?: number,
800
862
  referenceBlock?: BlockHash,
801
863
  ): Promise<TxScopedL2Log[][]> {
864
+ let upToBlockNumber: BlockNumber | undefined;
802
865
  if (referenceBlock) {
803
866
  const initialBlockHash = await this.#getInitialHeaderHash();
804
- if (!referenceBlock.equals(initialBlockHash)) {
867
+ if (referenceBlock.equals(initialBlockHash)) {
868
+ upToBlockNumber = BlockNumber(0);
869
+ } else {
805
870
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
806
871
  if (!header) {
807
872
  throw new Error(
808
873
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
809
874
  );
810
875
  }
876
+ upToBlockNumber = header.globalVariables.blockNumber;
811
877
  }
812
878
  }
813
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
879
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
814
880
  }
815
881
 
816
882
  /**
@@ -896,7 +962,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
896
962
  await tryStop(this.validatorsSentinel);
897
963
  await tryStop(this.epochPruneWatcher);
898
964
  await tryStop(this.slasherClient);
899
- await tryStop(this.proofVerifier);
965
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
900
966
  await tryStop(this.sequencer);
901
967
  await tryStop(this.proverNode);
902
968
  await tryStop(this.p2pClient);
@@ -952,58 +1018,64 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
952
1018
  treeId: MerkleTreeId,
953
1019
  leafValues: Fr[],
954
1020
  ): Promise<(DataInBlock<bigint> | undefined)[]> {
955
- const committedDb = await this.#getWorldState(referenceBlock);
1021
+ const committedDb = await this.getWorldState(referenceBlock);
956
1022
  const maybeIndices = await committedDb.findLeafIndices(
957
1023
  treeId,
958
1024
  leafValues.map(x => x.toBuffer()),
959
1025
  );
960
- // We filter out undefined values
961
- const indices = maybeIndices.filter(x => x !== undefined) as bigint[];
1026
+ // Filter out undefined values to query block numbers only for found leaves
1027
+ const definedIndices = maybeIndices.filter(x => x !== undefined);
962
1028
 
963
- // Now we find the block numbers for the indices
964
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
1029
+ // Now we find the block numbers for the defined indices
1030
+ const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
965
1031
 
966
- // If any of the block numbers are undefined, we throw an error.
967
- for (let i = 0; i < indices.length; i++) {
968
- if (blockNumbers[i] === undefined) {
969
- throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
1032
+ // Build a map from leaf index to block number
1033
+ const indexToBlockNumber = new Map<bigint, BlockNumber>();
1034
+ for (let i = 0; i < definedIndices.length; i++) {
1035
+ const blockNumber = blockNumbers[i];
1036
+ if (blockNumber === undefined) {
1037
+ throw new Error(
1038
+ `Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`,
1039
+ );
970
1040
  }
1041
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
971
1042
  }
972
1043
 
973
1044
  // Get unique block numbers in order to optimize num calls to getLeafValue function.
974
- const uniqueBlockNumbers = [...new Set(blockNumbers.filter(x => x !== undefined))];
1045
+ const uniqueBlockNumbers = [...new Set(indexToBlockNumber.values())];
975
1046
 
976
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
977
- // (note that block number corresponds to the leaf index in the archive tree).
1047
+ // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
978
1048
  const blockHashes = await Promise.all(
979
1049
  uniqueBlockNumbers.map(blockNumber => {
980
1050
  return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
981
1051
  }),
982
1052
  );
983
1053
 
984
- // If any of the block hashes are undefined, we throw an error.
1054
+ // Build a map from block number to block hash
1055
+ const blockNumberToHash = new Map<BlockNumber, Fr>();
985
1056
  for (let i = 0; i < uniqueBlockNumbers.length; i++) {
986
- if (blockHashes[i] === undefined) {
1057
+ const blockHash = blockHashes[i];
1058
+ if (blockHash === undefined) {
987
1059
  throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
988
1060
  }
1061
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
989
1062
  }
990
1063
 
991
1064
  // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
992
- return maybeIndices.map((index, i) => {
1065
+ return maybeIndices.map(index => {
993
1066
  if (index === undefined) {
994
1067
  return undefined;
995
1068
  }
996
- const blockNumber = blockNumbers[i];
1069
+ const blockNumber = indexToBlockNumber.get(index);
997
1070
  if (blockNumber === undefined) {
998
- return undefined;
1071
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
999
1072
  }
1000
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
1001
- const blockHash = blockHashes[blockHashIndex];
1002
- if (!blockHash) {
1003
- return undefined;
1073
+ const blockHash = blockNumberToHash.get(blockNumber);
1074
+ if (blockHash === undefined) {
1075
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
1004
1076
  }
1005
1077
  return {
1006
- l2BlockNumber: BlockNumber(Number(blockNumber)),
1078
+ l2BlockNumber: blockNumber,
1007
1079
  l2BlockHash: new BlockHash(blockHash),
1008
1080
  data: index,
1009
1081
  };
@@ -1014,7 +1086,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1014
1086
  referenceBlock: BlockParameter,
1015
1087
  blockHash: BlockHash,
1016
1088
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
1017
- const committedDb = await this.#getWorldState(referenceBlock);
1089
+ // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
1090
+ // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1091
+ // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1092
+ const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1093
+ if (referenceBlockNumber === BlockNumber.ZERO) {
1094
+ // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
1095
+ return undefined;
1096
+ }
1097
+ const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
1018
1098
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
1019
1099
  return pathAndIndex === undefined
1020
1100
  ? undefined
@@ -1025,7 +1105,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1025
1105
  referenceBlock: BlockParameter,
1026
1106
  noteHash: Fr,
1027
1107
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
1028
- const committedDb = await this.#getWorldState(referenceBlock);
1108
+ const committedDb = await this.getWorldState(referenceBlock);
1029
1109
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
1030
1110
  MerkleTreeId.NOTE_HASH_TREE,
1031
1111
  [noteHash],
@@ -1039,7 +1119,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1039
1119
  referenceBlock: BlockParameter,
1040
1120
  l1ToL2Message: Fr,
1041
1121
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
1042
- const db = await this.#getWorldState(referenceBlock);
1122
+ const db = await this.getWorldState(referenceBlock);
1043
1123
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
1044
1124
  if (!witness) {
1045
1125
  return undefined;
@@ -1049,11 +1129,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1049
1129
  return [witness.index, witness.path];
1050
1130
  }
1051
1131
 
1052
- public async getL1ToL2MessageBlock(l1ToL2Message: Fr): Promise<BlockNumber | undefined> {
1132
+ public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
1053
1133
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1054
- return messageIndex
1055
- ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex))
1056
- : undefined;
1134
+ return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1057
1135
  }
1058
1136
 
1059
1137
  /**
@@ -1074,19 +1152,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1074
1152
  public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
1075
1153
  // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1076
1154
  const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1077
- const blocksInCheckpoints: L2Block[][] = [];
1078
- let previousSlotNumber = SlotNumber.ZERO;
1079
- let checkpointIndex = -1;
1080
- for (const checkpointedBlock of checkpointedBlocks) {
1081
- const block = checkpointedBlock.block;
1082
- const slotNumber = block.header.globalVariables.slotNumber;
1083
- if (slotNumber !== previousSlotNumber) {
1084
- checkpointIndex++;
1085
- blocksInCheckpoints.push([]);
1086
- previousSlotNumber = slotNumber;
1087
- }
1088
- blocksInCheckpoints[checkpointIndex].push(block);
1089
- }
1155
+ const blocksInCheckpoints = chunkBy(checkpointedBlocks, cb => cb.block.header.globalVariables.slotNumber).map(
1156
+ group => group.map(cb => cb.block),
1157
+ );
1090
1158
  return blocksInCheckpoints.map(blocks =>
1091
1159
  blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1092
1160
  );
@@ -1096,7 +1164,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1096
1164
  referenceBlock: BlockParameter,
1097
1165
  nullifier: Fr,
1098
1166
  ): Promise<NullifierMembershipWitness | undefined> {
1099
- const db = await this.#getWorldState(referenceBlock);
1167
+ const db = await this.getWorldState(referenceBlock);
1100
1168
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
1101
1169
  if (!witness) {
1102
1170
  return undefined;
@@ -1111,33 +1179,20 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1111
1179
  return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
1112
1180
  }
1113
1181
 
1114
- /**
1115
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1116
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1117
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1118
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1119
- * @returns The low nullifier membership witness (if found).
1120
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1121
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1122
- * we are trying to prove non-inclusion for.
1123
- *
1124
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1125
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1126
- * index of the nullifier itself when it already exists in the tree.
1127
- * TODO: This is a confusing behavior and we should eventually address that.
1128
- */
1129
1182
  public async getLowNullifierMembershipWitness(
1130
1183
  referenceBlock: BlockParameter,
1131
1184
  nullifier: Fr,
1132
1185
  ): Promise<NullifierMembershipWitness | undefined> {
1133
- const committedDb = await this.#getWorldState(referenceBlock);
1186
+ const committedDb = await this.getWorldState(referenceBlock);
1134
1187
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1135
1188
  if (!findResult) {
1136
1189
  return undefined;
1137
1190
  }
1138
1191
  const { index, alreadyPresent } = findResult;
1139
1192
  if (alreadyPresent) {
1140
- this.log.warn(`Nullifier ${nullifier.toBigInt()} already exists in the tree`);
1193
+ throw new Error(
1194
+ `Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`,
1195
+ );
1141
1196
  }
1142
1197
  const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
1143
1198
 
@@ -1146,7 +1201,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1146
1201
  }
1147
1202
 
1148
1203
  async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1149
- const committedDb = await this.#getWorldState(referenceBlock);
1204
+ const committedDb = await this.getWorldState(referenceBlock);
1150
1205
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1151
1206
  if (!lowLeafResult) {
1152
1207
  return undefined;
@@ -1161,7 +1216,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1161
1216
  }
1162
1217
 
1163
1218
  public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1164
- const committedDb = await this.#getWorldState(referenceBlock);
1219
+ const committedDb = await this.getWorldState(referenceBlock);
1165
1220
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1166
1221
 
1167
1222
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
@@ -1275,7 +1330,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1275
1330
  const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1276
1331
 
1277
1332
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1278
- const [processedTxs, failedTxs, _usedTxs, returns, _blobFields, debugLogs] = await processor.process([tx]);
1333
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1279
1334
  // REFACTOR: Consider returning the error rather than throwing
1280
1335
  if (failedTxs.length) {
1281
1336
  this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
@@ -1301,11 +1356,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1301
1356
  { isSimulation, skipFeeEnforcement }: { isSimulation?: boolean; skipFeeEnforcement?: boolean } = {},
1302
1357
  ): Promise<TxValidationResult> {
1303
1358
  const db = this.worldStateSynchronizer.getCommitted();
1304
- const verifier = isSimulation ? undefined : this.proofVerifier;
1359
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1305
1360
 
1306
1361
  // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1307
1362
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1308
1363
  const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1364
+ const l1Constants = await this.blockSource.getL1Constants();
1309
1365
  const validator = createTxValidatorForAcceptingTxsOverRPC(
1310
1366
  db,
1311
1367
  this.contractDataSource,
@@ -1322,6 +1378,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1322
1378
  gasFees: await this.getCurrentMinFees(),
1323
1379
  skipFeeEnforcement,
1324
1380
  txsPermitted: !this.config.disableTransactions,
1381
+ rollupManaLimit: l1Constants.rollupManaLimit,
1382
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1383
+ maxBlockDAGas: this.config.validateMaxDABlockGas,
1325
1384
  },
1326
1385
  this.log.getBindings(),
1327
1386
  );
@@ -1346,7 +1405,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1346
1405
  archiver.updateConfig(config);
1347
1406
  }
1348
1407
  if (newConfig.realProofs !== this.config.realProofs) {
1349
- this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
1408
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
1409
+ if (newConfig.realProofs) {
1410
+ this.peerProofVerifier = await BatchChonkVerifier.new(newConfig, newConfig.bbChonkVerifyMaxBatch, 'peer');
1411
+ const rpcVerifier = await BBCircuitVerifier.new(newConfig);
1412
+ this.rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, newConfig.numConcurrentIVCVerifiers);
1413
+ } else {
1414
+ this.peerProofVerifier = new TestCircuitVerifier();
1415
+ this.rpcProofVerifier = new TestCircuitVerifier();
1416
+ }
1350
1417
  }
1351
1418
 
1352
1419
  this.config = newConfig;
@@ -1588,7 +1655,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1588
1655
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1589
1656
  * @returns An instance of a committed MerkleTreeOperations
1590
1657
  */
1591
- async #getWorldState(block: BlockParameter) {
1658
+ protected async getWorldState(block: BlockParameter) {
1592
1659
  let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1593
1660
  try {
1594
1661
  // Attempt to sync the world state if necessary
@@ -1602,6 +1669,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1602
1669
  return this.worldStateSynchronizer.getCommitted();
1603
1670
  }
1604
1671
 
1672
+ // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1673
+ let blockNumber: BlockNumber;
1605
1674
  if (BlockHash.isBlockHash(block)) {
1606
1675
  const initialBlockHash = await this.#getInitialHeaderHash();
1607
1676
  if (block.equals(initialBlockHash)) {
@@ -1615,22 +1684,50 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1615
1684
  `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
1685
  );
1617
1686
  }
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);
1687
+
1688
+ blockNumber = header.getBlockNumber();
1689
+ } else {
1690
+ blockNumber = block as BlockNumber;
1621
1691
  }
1622
1692
 
1623
- // Block number provided
1624
- {
1625
- const blockNumber = block as BlockNumber;
1693
+ // Check it's within world state sync range
1694
+ if (blockNumber > blockSyncedTo) {
1695
+ throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1696
+ }
1697
+ this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1626
1698
 
1627
- if (blockNumber > blockSyncedTo) {
1628
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1699
+ const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
1700
+
1701
+ // Double-check world-state synced to the same block hash as was requested
1702
+ if (BlockHash.isBlockHash(block)) {
1703
+ const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1704
+ if (!blockHash || !new BlockHash(blockHash).equals(block)) {
1705
+ throw new Error(
1706
+ `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.`,
1707
+ );
1629
1708
  }
1709
+ }
1710
+
1711
+ return snapshot;
1712
+ }
1630
1713
 
1631
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1632
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1714
+ /** Resolves a block parameter to a block number. */
1715
+ protected async resolveBlockNumber(block: BlockParameter): Promise<BlockNumber> {
1716
+ if (block === 'latest') {
1717
+ return BlockNumber(await this.blockSource.getBlockNumber());
1718
+ }
1719
+ if (BlockHash.isBlockHash(block)) {
1720
+ const initialBlockHash = await this.#getInitialHeaderHash();
1721
+ if (block.equals(initialBlockHash)) {
1722
+ return BlockNumber.ZERO;
1723
+ }
1724
+ const header = await this.blockSource.getBlockHeaderByHash(block);
1725
+ if (!header) {
1726
+ throw new Error(`Block hash ${block.toString()} not found.`);
1727
+ }
1728
+ return header.getBlockNumber();
1633
1729
  }
1730
+ return block as BlockNumber;
1634
1731
  }
1635
1732
 
1636
1733
  /**