@aztec/aztec-node 0.0.1-commit.b655e406 → 0.0.1-commit.d1f2d6c

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,43 +1,36 @@
1
1
  import { Archiver, createArchiver } from '@aztec/archiver';
2
2
  import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
3
- import { type BlobSinkClientInterface, createBlobSinkClient } from '@aztec/blob-sink/client';
3
+ import { type BlobClientInterface, createBlobClientWithFileStores } from '@aztec/blob-client/client';
4
4
  import {
5
5
  ARCHIVE_HEIGHT,
6
- INITIAL_L2_BLOCK_NUM,
7
6
  type L1_TO_L2_MSG_TREE_HEIGHT,
8
7
  type NOTE_HASH_TREE_HEIGHT,
9
8
  type NULLIFIER_TREE_HEIGHT,
10
9
  type PUBLIC_DATA_TREE_HEIGHT,
11
10
  } from '@aztec/constants';
12
11
  import { EpochCache, type EpochCacheInterface } from '@aztec/epoch-cache';
13
- import {
14
- type L1ContractAddresses,
15
- RegistryContract,
16
- RollupContract,
17
- createEthereumChain,
18
- getPublicClient,
19
- } from '@aztec/ethereum';
12
+ import { createEthereumChain } from '@aztec/ethereum/chain';
13
+ import { getPublicClient } from '@aztec/ethereum/client';
14
+ import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
15
+ import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
16
+ import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
20
17
  import { compactArray, pick } from '@aztec/foundation/collection';
18
+ import { Fr } from '@aztec/foundation/curves/bn254';
21
19
  import { EthAddress } from '@aztec/foundation/eth-address';
22
- import { Fr } from '@aztec/foundation/fields';
23
20
  import { BadRequestError } from '@aztec/foundation/json-rpc';
24
21
  import { type Logger, createLogger } from '@aztec/foundation/log';
25
- import { SerialQueue } from '@aztec/foundation/queue';
26
22
  import { count } from '@aztec/foundation/string';
27
23
  import { DateProvider, Timer } from '@aztec/foundation/timer';
28
24
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
29
25
  import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
30
26
  import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
31
- import { createL1TxUtilsWithBlobsFromEthSigner } from '@aztec/node-lib/factories';
27
+ import {
28
+ createForwarderL1TxUtilsFromEthSigner,
29
+ createL1TxUtilsWithBlobsFromEthSigner,
30
+ } from '@aztec/node-lib/factories';
32
31
  import { type P2P, type P2PClientDeps, createP2PClient, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
33
32
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
34
- import {
35
- BlockBuilder,
36
- GlobalVariableBuilder,
37
- SequencerClient,
38
- type SequencerPublisher,
39
- createValidatorForAcceptingTxs,
40
- } from '@aztec/sequencer-client';
33
+ import { GlobalVariableBuilder, SequencerClient, type SequencerPublisher } from '@aztec/sequencer-client';
41
34
  import { PublicProcessorFactory } from '@aztec/simulator/server';
42
35
  import {
43
36
  AttestationsBlockWatcher,
@@ -46,15 +39,10 @@ import {
46
39
  type Watcher,
47
40
  createSlasher,
48
41
  } from '@aztec/slasher';
42
+ import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
49
43
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
50
- import {
51
- type InBlock,
52
- type L2Block,
53
- L2BlockHash,
54
- type L2BlockNumber,
55
- type L2BlockSource,
56
- type PublishedL2Block,
57
- } from '@aztec/stdlib/block';
44
+ import { type BlockParameter, type DataInBlock, L2Block, L2BlockHash, type L2BlockSource } from '@aztec/stdlib/block';
45
+ import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
58
46
  import type {
59
47
  ContractClassPublic,
60
48
  ContractDataSource,
@@ -62,7 +50,7 @@ import type {
62
50
  NodeInfo,
63
51
  ProtocolContractAddresses,
64
52
  } from '@aztec/stdlib/contract';
65
- import type { GasFees } from '@aztec/stdlib/gas';
53
+ import { GasFees } from '@aztec/stdlib/gas';
66
54
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
67
55
  import {
68
56
  type AztecNode,
@@ -81,7 +69,7 @@ import {
81
69
  type WorldStateSynchronizer,
82
70
  tryStop,
83
71
  } from '@aztec/stdlib/interfaces/server';
84
- import type { LogFilter, PrivateLog, TxScopedL2Log } from '@aztec/stdlib/logs';
72
+ import type { LogFilter, SiloedTag, Tag, TxScopedL2Log } from '@aztec/stdlib/logs';
85
73
  import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
86
74
  import { P2PClientType } from '@aztec/stdlib/p2p';
87
75
  import type { Offense, SlashPayloadRound } from '@aztec/stdlib/slashing';
@@ -109,10 +97,13 @@ import {
109
97
  trackSpan,
110
98
  } from '@aztec/telemetry-client';
111
99
  import {
100
+ FullNodeCheckpointsBuilder as CheckpointsBuilder,
101
+ FullNodeCheckpointsBuilder,
112
102
  NodeKeystoreAdapter,
113
103
  ValidatorClient,
114
104
  createBlockProposalHandler,
115
105
  createValidatorClient,
106
+ createValidatorForAcceptingTxs,
116
107
  } from '@aztec/validator-client';
117
108
  import { createWorldStateSynchronizer } from '@aztec/world-state';
118
109
 
@@ -128,13 +119,11 @@ import { NodeMetrics } from './node_metrics.js';
128
119
  */
129
120
  export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
130
121
  private metrics: NodeMetrics;
122
+ private initialHeaderHashPromise: Promise<L2BlockHash> | undefined = undefined;
131
123
 
132
124
  // Prevent two snapshot operations to happen simultaneously
133
125
  private isUploadingSnapshot = false;
134
126
 
135
- // Serial queue to ensure that we only send one tx at a time
136
- private txQueue: SerialQueue = new SerialQueue();
137
-
138
127
  public readonly tracer: Tracer;
139
128
 
140
129
  constructor(
@@ -157,10 +146,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
157
146
  private proofVerifier: ClientProtocolCircuitVerifier,
158
147
  private telemetry: TelemetryClient = getTelemetryClient(),
159
148
  private log = createLogger('node'),
149
+ private blobClient?: BlobClientInterface,
160
150
  ) {
161
151
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
162
152
  this.tracer = telemetry.getTracer('AztecNodeService');
163
- this.txQueue.start();
164
153
 
165
154
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
166
155
  this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
@@ -187,7 +176,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
187
176
  logger?: Logger;
188
177
  publisher?: SequencerPublisher;
189
178
  dateProvider?: DateProvider;
190
- blobSinkClient?: BlobSinkClientInterface;
191
179
  p2pClientDeps?: P2PClientDeps<P2PClientType.Full>;
192
180
  } = {},
193
181
  options: {
@@ -200,8 +188,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
200
188
  const packageVersion = getPackageVersion() ?? '';
201
189
  const telemetry = deps.telemetry ?? getTelemetryClient();
202
190
  const dateProvider = deps.dateProvider ?? new DateProvider();
203
- const blobSinkClient =
204
- deps.blobSinkClient ?? createBlobSinkClient(config, { logger: createLogger('node:blob-sink:client') });
205
191
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
206
192
 
207
193
  // Build a key store from file if given or from environment otherwise
@@ -241,7 +227,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
241
227
 
242
228
  const publicClient = createPublicClient({
243
229
  chain: ethereumChain.chainInfo,
244
- transport: fallback(config.l1RpcUrls.map((url: string) => http(url))),
230
+ transport: fallback(config.l1RpcUrls.map((url: string) => http(url, { batch: false }))),
245
231
  pollingInterval: config.viemPollingIntervalMS,
246
232
  });
247
233
 
@@ -269,6 +255,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
269
255
  );
270
256
  }
271
257
 
258
+ const blobClient = await createBlobClientWithFileStores(config, createLogger('node:blob-client:client'));
259
+
272
260
  // attempt snapshot sync if possible
273
261
  await trySnapshotSync(config, log);
274
262
 
@@ -276,7 +264,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
276
264
 
277
265
  const archiver = await createArchiver(
278
266
  config,
279
- { blobSinkClient, epochCache, telemetry, dateProvider },
267
+ { blobClient, epochCache, telemetry, dateProvider },
280
268
  { blockUntilSync: !config.skipArchiverInitialSync },
281
269
  );
282
270
 
@@ -287,7 +275,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
287
275
  options.prefilledPublicData,
288
276
  telemetry,
289
277
  );
290
- const circuitVerifier = config.realProofs ? await BBCircuitVerifier.new(config) : new TestCircuitVerifier();
278
+ const circuitVerifier =
279
+ config.realProofs || config.debugForceTxProofVerification
280
+ ? await BBCircuitVerifier.new(config)
281
+ : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
291
282
  if (!config.realProofs) {
292
283
  log.warn(`Aztec node is accepting fake proofs`);
293
284
  }
@@ -310,7 +301,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
310
301
  // We should really not be modifying the config object
311
302
  config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
312
303
 
313
- const blockBuilder = new BlockBuilder(
304
+ // Create FullNodeCheckpointsBuilder for validator and non-validator block proposal handling
305
+ const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
314
306
  { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
315
307
  worldStateSynchronizer,
316
308
  archiver,
@@ -322,15 +314,17 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
322
314
  const watchers: Watcher[] = [];
323
315
 
324
316
  // Create validator client if required
325
- const validatorClient = createValidatorClient(config, {
317
+ const validatorClient = await createValidatorClient(config, {
318
+ checkpointsBuilder: validatorCheckpointsBuilder,
319
+ worldState: worldStateSynchronizer,
326
320
  p2pClient,
327
321
  telemetry,
328
322
  dateProvider,
329
323
  epochCache,
330
- blockBuilder,
331
324
  blockSource: archiver,
332
325
  l1ToL2MessageSource: archiver,
333
326
  keyStoreManager,
327
+ blobClient,
334
328
  });
335
329
 
336
330
  // If we have a validator client, register it as a source of offenses for the slasher,
@@ -348,7 +342,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
348
342
  if (!validatorClient && config.alwaysReexecuteBlockProposals) {
349
343
  log.info('Setting up block proposal reexecution for monitoring');
350
344
  createBlockProposalHandler(config, {
351
- blockBuilder,
345
+ checkpointsBuilder: validatorCheckpointsBuilder,
346
+ worldState: worldStateSynchronizer,
352
347
  epochCache,
353
348
  blockSource: archiver,
354
349
  l1ToL2MessageSource: archiver,
@@ -376,7 +371,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
376
371
  archiver,
377
372
  epochCache,
378
373
  p2pClient.getTxProvider(),
379
- blockBuilder,
374
+ validatorCheckpointsBuilder,
380
375
  config,
381
376
  );
382
377
  watchers.push(epochPruneWatcher);
@@ -404,7 +399,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
404
399
  // Validator enabled, create/start relevant service
405
400
  let sequencer: SequencerClient | undefined;
406
401
  let slasherClient: SlasherClientInterface | undefined;
407
- if (!config.disableValidator) {
402
+ if (!config.disableValidator && validatorClient) {
408
403
  // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
409
404
  // as they are executed when the node is selected as proposer.
410
405
  const validatorAddresses = keyStoreManager
@@ -423,14 +418,30 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
423
418
  );
424
419
  await slasherClient.start();
425
420
 
426
- const l1TxUtils = await createL1TxUtilsWithBlobsFromEthSigner(
427
- publicClient,
428
- keyStoreManager!.createAllValidatorPublisherSigners(),
429
- { ...config, scope: 'sequencer' },
430
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider },
431
- );
421
+ const l1TxUtils = config.publisherForwarderAddress
422
+ ? await createForwarderL1TxUtilsFromEthSigner(
423
+ publicClient,
424
+ keyStoreManager!.createAllValidatorPublisherSigners(),
425
+ config.publisherForwarderAddress,
426
+ { ...config, scope: 'sequencer' },
427
+ { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider },
428
+ )
429
+ : await createL1TxUtilsWithBlobsFromEthSigner(
430
+ publicClient,
431
+ keyStoreManager!.createAllValidatorPublisherSigners(),
432
+ { ...config, scope: 'sequencer' },
433
+ { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider },
434
+ );
432
435
 
433
436
  // Create and start the sequencer client
437
+ const checkpointsBuilder = new CheckpointsBuilder(
438
+ { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
439
+ worldStateSynchronizer,
440
+ archiver,
441
+ dateProvider,
442
+ telemetry,
443
+ );
444
+
434
445
  sequencer = await SequencerClient.new(config, {
435
446
  ...deps,
436
447
  epochCache,
@@ -439,12 +450,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
439
450
  p2pClient,
440
451
  worldStateSynchronizer,
441
452
  slasherClient,
442
- blockBuilder,
453
+ checkpointsBuilder,
443
454
  l2BlockSource: archiver,
444
455
  l1ToL2MessageSource: archiver,
445
456
  telemetry,
446
457
  dateProvider,
447
- blobSinkClient,
458
+ blobClient,
448
459
  nodeKeyStore: keyStoreManager!,
449
460
  });
450
461
  }
@@ -456,6 +467,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
456
467
  log.warn(`Sequencer created but not started`);
457
468
  }
458
469
 
470
+ const globalVariableBuilder = new GlobalVariableBuilder({
471
+ ...config,
472
+ rollupVersion: BigInt(config.rollupVersion),
473
+ l1GenesisTime,
474
+ slotDuration: Number(slotDuration),
475
+ });
476
+
459
477
  return new AztecNodeService(
460
478
  config,
461
479
  p2pClient,
@@ -470,12 +488,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
470
488
  epochPruneWatcher,
471
489
  ethereumChain.chainInfo.id,
472
490
  config.rollupVersion,
473
- new GlobalVariableBuilder(config),
491
+ globalVariableBuilder,
474
492
  epochCache,
475
493
  packageVersion,
476
494
  proofVerifier,
477
495
  telemetry,
478
496
  log,
497
+ blobClient,
479
498
  );
480
499
  }
481
500
 
@@ -546,13 +565,19 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
546
565
  }
547
566
 
548
567
  /**
549
- * Get a block specified by its number.
550
- * @param number - The block number being requested.
568
+ * Get a block specified by its block number, block hash, or 'latest'.
569
+ * @param block - The block parameter (block number, block hash, or 'latest').
551
570
  * @returns The requested block.
552
571
  */
553
- public async getBlock(number: L2BlockNumber): Promise<L2Block | undefined> {
554
- const blockNumber = number === 'latest' ? await this.getBlockNumber() : number;
555
- return await this.blockSource.getBlock(blockNumber);
572
+ public async getBlock(block: BlockParameter): Promise<L2Block | undefined> {
573
+ if (L2BlockHash.isL2BlockHash(block)) {
574
+ return this.getBlockByHash(Fr.fromBuffer(block.toBuffer()));
575
+ }
576
+ const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
577
+ if (blockNumber === BlockNumber.ZERO) {
578
+ return this.buildInitialBlock();
579
+ }
580
+ return await this.blockSource.getL2Block(blockNumber);
556
581
  }
557
582
 
558
583
  /**
@@ -561,8 +586,16 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
561
586
  * @returns The requested block.
562
587
  */
563
588
  public async getBlockByHash(blockHash: Fr): Promise<L2Block | undefined> {
564
- const publishedBlock = await this.blockSource.getPublishedBlockByHash(blockHash);
565
- return publishedBlock?.block;
589
+ const initialBlockHash = await this.#getInitialHeaderHash();
590
+ if (blockHash.equals(Fr.fromBuffer(initialBlockHash.toBuffer()))) {
591
+ return this.buildInitialBlock();
592
+ }
593
+ return await this.blockSource.getL2BlockByHash(blockHash);
594
+ }
595
+
596
+ private buildInitialBlock(): L2Block {
597
+ const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
598
+ return L2Block.empty(initialHeader);
566
599
  }
567
600
 
568
601
  /**
@@ -571,8 +604,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
571
604
  * @returns The requested block.
572
605
  */
573
606
  public async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
574
- const publishedBlock = await this.blockSource.getPublishedBlockByArchive(archive);
575
- return publishedBlock?.block;
607
+ return await this.blockSource.getL2BlockByArchive(archive);
576
608
  }
577
609
 
578
610
  /**
@@ -581,34 +613,50 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
581
613
  * @param limit - The maximum number of blocks to obtain.
582
614
  * @returns The blocks requested.
583
615
  */
584
- public async getBlocks(from: number, limit: number): Promise<L2Block[]> {
585
- return (await this.blockSource.getBlocks(from, limit)) ?? [];
616
+ public async getBlocks(from: BlockNumber, limit: number): Promise<L2Block[]> {
617
+ return (await this.blockSource.getBlocks(from, BlockNumber(limit))) ?? [];
586
618
  }
587
619
 
588
- public async getPublishedBlocks(from: number, limit: number): Promise<PublishedL2Block[]> {
589
- return (await this.blockSource.getPublishedBlocks(from, limit)) ?? [];
620
+ public async getCheckpoints(from: CheckpointNumber, limit: number): Promise<PublishedCheckpoint[]> {
621
+ return (await this.blockSource.getCheckpoints(from, limit)) ?? [];
622
+ }
623
+
624
+ public async getCheckpointedBlocks(from: BlockNumber, limit: number) {
625
+ return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
590
626
  }
591
627
 
592
628
  /**
593
- * Method to fetch the current base fees.
594
- * @returns The current base fees.
629
+ * Method to fetch the current min L2 fees.
630
+ * @returns The current min L2 fees.
595
631
  */
596
- public async getCurrentBaseFees(): Promise<GasFees> {
597
- return await this.globalVariableBuilder.getCurrentBaseFees();
632
+ public async getCurrentMinFees(): Promise<GasFees> {
633
+ return await this.globalVariableBuilder.getCurrentMinFees();
634
+ }
635
+
636
+ public async getMaxPriorityFees(): Promise<GasFees> {
637
+ for await (const tx of this.p2pClient.iteratePendingTxs()) {
638
+ return tx.getGasSettings().maxPriorityFeesPerGas;
639
+ }
640
+
641
+ return GasFees.from({ feePerDaGas: 0n, feePerL2Gas: 0n });
598
642
  }
599
643
 
600
644
  /**
601
645
  * Method to fetch the latest block number synchronized by the node.
602
646
  * @returns The block number.
603
647
  */
604
- public async getBlockNumber(): Promise<number> {
648
+ public async getBlockNumber(): Promise<BlockNumber> {
605
649
  return await this.blockSource.getBlockNumber();
606
650
  }
607
651
 
608
- public async getProvenBlockNumber(): Promise<number> {
652
+ public async getProvenBlockNumber(): Promise<BlockNumber> {
609
653
  return await this.blockSource.getProvenBlockNumber();
610
654
  }
611
655
 
656
+ public async getCheckpointedBlockNumber(): Promise<BlockNumber> {
657
+ return await this.blockSource.getCheckpointedL2BlockNumber();
658
+ }
659
+
612
660
  /**
613
661
  * Method to fetch the version of the package.
614
662
  * @returns The node package version
@@ -641,25 +689,45 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
641
689
  return this.contractDataSource.getContract(address);
642
690
  }
643
691
 
644
- /**
645
- * Retrieves all private logs from up to `limit` blocks, starting from the block number `from`.
646
- * @param from - The block number from which to begin retrieving logs.
647
- * @param limit - The maximum number of blocks to retrieve logs from.
648
- * @returns An array of private logs from the specified range of blocks.
649
- */
650
- public getPrivateLogs(from: number, limit: number): Promise<PrivateLog[]> {
651
- return this.logsSource.getPrivateLogs(from, limit);
652
- }
653
-
654
- /**
655
- * Gets all logs that match any of the received tags (i.e. logs with their first field equal to a tag).
656
- * @param tags - The tags to filter the logs by.
657
- * @param logsPerTag - The maximum number of logs to return for each tag. By default no limit is set
658
- * @returns For each received tag, an array of matching logs is returned. An empty array implies no logs match
659
- * that tag.
660
- */
661
- public getLogsByTags(tags: Fr[], logsPerTag?: number): Promise<TxScopedL2Log[][]> {
662
- return this.logsSource.getLogsByTags(tags, logsPerTag);
692
+ public async getPrivateLogsByTags(
693
+ tags: SiloedTag[],
694
+ page?: number,
695
+ referenceBlock?: L2BlockHash,
696
+ ): Promise<TxScopedL2Log[][]> {
697
+ if (referenceBlock) {
698
+ const initialBlockHash = await this.#getInitialHeaderHash();
699
+ if (!referenceBlock.equals(initialBlockHash)) {
700
+ const blockHashFr = Fr.fromBuffer(referenceBlock.toBuffer());
701
+ const header = await this.blockSource.getBlockHeaderByHash(blockHashFr);
702
+ if (!header) {
703
+ throw new Error(
704
+ `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
705
+ );
706
+ }
707
+ }
708
+ }
709
+ return this.logsSource.getPrivateLogsByTags(tags, page);
710
+ }
711
+
712
+ public async getPublicLogsByTagsFromContract(
713
+ contractAddress: AztecAddress,
714
+ tags: Tag[],
715
+ page?: number,
716
+ referenceBlock?: L2BlockHash,
717
+ ): Promise<TxScopedL2Log[][]> {
718
+ if (referenceBlock) {
719
+ const initialBlockHash = await this.#getInitialHeaderHash();
720
+ if (!referenceBlock.equals(initialBlockHash)) {
721
+ const blockHashFr = Fr.fromBuffer(referenceBlock.toBuffer());
722
+ const header = await this.blockSource.getBlockHeaderByHash(blockHashFr);
723
+ if (!header) {
724
+ throw new Error(
725
+ `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
726
+ );
727
+ }
728
+ }
729
+ }
730
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
663
731
  }
664
732
 
665
733
  /**
@@ -685,7 +753,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
685
753
  * @param tx - The transaction to be submitted.
686
754
  */
687
755
  public async sendTx(tx: Tx) {
688
- await this.txQueue.put(() => this.#sendTx(tx));
756
+ await this.#sendTx(tx);
689
757
  }
690
758
 
691
759
  async #sendTx(tx: Tx) {
@@ -706,21 +774,26 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
706
774
  }
707
775
 
708
776
  public async getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
709
- let txReceipt = new TxReceipt(txHash, TxStatus.DROPPED, 'Tx dropped by P2P node.');
710
-
711
- // We first check if the tx is in pending (instead of first checking if it is mined) because if we first check
712
- // for mined and then for pending there could be a race condition where the tx is mined between the two checks
713
- // and we would incorrectly return a TxReceipt with status DROPPED
714
- if ((await this.p2pClient.getTxStatus(txHash)) === 'pending') {
715
- txReceipt = new TxReceipt(txHash, TxStatus.PENDING, '');
716
- }
777
+ // Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
778
+ // as a fallback if we don't find a settled receipt in the archiver.
779
+ const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
780
+ const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
717
781
 
782
+ // Then get the actual tx from the archiver, which tracks every tx in a mined block.
718
783
  const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
784
+
719
785
  if (settledTxReceipt) {
720
- txReceipt = settledTxReceipt;
786
+ // If the archiver has the receipt then return it.
787
+ return settledTxReceipt;
788
+ } else if (isKnownToPool) {
789
+ // If the tx is in the pool but not in the archiver, it's pending.
790
+ // This handles race conditions between archiver and p2p, where the archiver
791
+ // has pruned the block in which a tx was mined, but p2p has not caught up yet.
792
+ return new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
793
+ } else {
794
+ // Otherwise, if we don't know the tx, we consider it dropped.
795
+ return new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
721
796
  }
722
-
723
- return txReceipt;
724
797
  }
725
798
 
726
799
  public getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined> {
@@ -732,7 +805,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
732
805
  */
733
806
  public async stop() {
734
807
  this.log.info(`Stopping Aztec Node`);
735
- await this.txQueue.end();
736
808
  await tryStop(this.validatorsSentinel);
737
809
  await tryStop(this.epochPruneWatcher);
738
810
  await tryStop(this.slasherClient);
@@ -741,10 +813,19 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
741
813
  await tryStop(this.p2pClient);
742
814
  await tryStop(this.worldStateSynchronizer);
743
815
  await tryStop(this.blockSource);
816
+ await tryStop(this.blobClient);
744
817
  await tryStop(this.telemetry);
745
818
  this.log.info(`Stopped Aztec Node`);
746
819
  }
747
820
 
821
+ /**
822
+ * Returns the blob client used by this node.
823
+ * @internal - Exposed for testing purposes only.
824
+ */
825
+ public getBlobClient(): BlobClientInterface | undefined {
826
+ return this.blobClient;
827
+ }
828
+
748
829
  /**
749
830
  * Method to retrieve pending txs.
750
831
  * @param limit - The number of items to returns
@@ -777,20 +858,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
777
858
  return compactArray(await Promise.all(txHashes.map(txHash => this.getTxByHash(txHash))));
778
859
  }
779
860
 
780
- /**
781
- * Find the indexes of the given leaves in the given tree along with a block metadata pointing to the block in which
782
- * the leaves were inserted.
783
- * @param blockNumber - The block number at which to get the data or 'latest' for latest data.
784
- * @param treeId - The tree to search in.
785
- * @param leafValues - The values to search for.
786
- * @returns The indices of leaves and the block metadata of a block in which the leaves were inserted.
787
- */
788
861
  public async findLeavesIndexes(
789
- blockNumber: L2BlockNumber,
862
+ block: BlockParameter,
790
863
  treeId: MerkleTreeId,
791
864
  leafValues: Fr[],
792
- ): Promise<(InBlock<bigint> | undefined)[]> {
793
- const committedDb = await this.#getWorldState(blockNumber);
865
+ ): Promise<(DataInBlock<bigint> | undefined)[]> {
866
+ const committedDb = await this.#getWorldState(block);
794
867
  const maybeIndices = await committedDb.findLeafIndices(
795
868
  treeId,
796
869
  leafValues.map(x => x.toBuffer()),
@@ -815,7 +888,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
815
888
  // (note that block number corresponds to the leaf index in the archive tree).
816
889
  const blockHashes = await Promise.all(
817
890
  uniqueBlockNumbers.map(blockNumber => {
818
- return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, blockNumber!);
891
+ return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
819
892
  }),
820
893
  );
821
894
 
@@ -826,7 +899,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
826
899
  }
827
900
  }
828
901
 
829
- // Create InBlock objects by combining indices, blockNumbers and blockHashes and return them.
902
+ // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
830
903
  return maybeIndices.map((index, i) => {
831
904
  if (index === undefined) {
832
905
  return undefined;
@@ -841,46 +914,34 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
841
914
  return undefined;
842
915
  }
843
916
  return {
844
- l2BlockNumber: Number(blockNumber),
917
+ l2BlockNumber: BlockNumber(Number(blockNumber)),
845
918
  l2BlockHash: L2BlockHash.fromField(blockHash),
846
919
  data: index,
847
920
  };
848
921
  });
849
922
  }
850
923
 
851
- /**
852
- * Returns a sibling path for the given index in the nullifier tree.
853
- * @param blockNumber - The block number at which to get the data.
854
- * @param leafIndex - The index of the leaf for which the sibling path is required.
855
- * @returns The sibling path for the leaf index.
856
- */
857
924
  public async getNullifierSiblingPath(
858
- blockNumber: L2BlockNumber,
925
+ block: BlockParameter,
859
926
  leafIndex: bigint,
860
927
  ): Promise<SiblingPath<typeof NULLIFIER_TREE_HEIGHT>> {
861
- const committedDb = await this.#getWorldState(blockNumber);
928
+ const committedDb = await this.#getWorldState(block);
862
929
  return committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, leafIndex);
863
930
  }
864
931
 
865
- /**
866
- * Returns a sibling path for the given index in the data tree.
867
- * @param blockNumber - The block number at which to get the data.
868
- * @param leafIndex - The index of the leaf for which the sibling path is required.
869
- * @returns The sibling path for the leaf index.
870
- */
871
932
  public async getNoteHashSiblingPath(
872
- blockNumber: L2BlockNumber,
933
+ block: BlockParameter,
873
934
  leafIndex: bigint,
874
935
  ): Promise<SiblingPath<typeof NOTE_HASH_TREE_HEIGHT>> {
875
- const committedDb = await this.#getWorldState(blockNumber);
936
+ const committedDb = await this.#getWorldState(block);
876
937
  return committedDb.getSiblingPath(MerkleTreeId.NOTE_HASH_TREE, leafIndex);
877
938
  }
878
939
 
879
940
  public async getArchiveMembershipWitness(
880
- blockNumber: L2BlockNumber,
941
+ block: BlockParameter,
881
942
  archive: Fr,
882
943
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
883
- const committedDb = await this.#getWorldState(blockNumber);
944
+ const committedDb = await this.#getWorldState(block);
884
945
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [archive]);
885
946
  return pathAndIndex === undefined
886
947
  ? undefined
@@ -888,10 +949,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
888
949
  }
889
950
 
890
951
  public async getNoteHashMembershipWitness(
891
- blockNumber: L2BlockNumber,
952
+ block: BlockParameter,
892
953
  noteHash: Fr,
893
954
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
894
- const committedDb = await this.#getWorldState(blockNumber);
955
+ const committedDb = await this.#getWorldState(block);
895
956
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
896
957
  MerkleTreeId.NOTE_HASH_TREE,
897
958
  [noteHash],
@@ -901,17 +962,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
901
962
  : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
902
963
  }
903
964
 
904
- /**
905
- * Returns the index and a sibling path for a leaf in the committed l1 to l2 data tree.
906
- * @param blockNumber - The block number at which to get the data.
907
- * @param l1ToL2Message - The l1ToL2Message to get the index / sibling path for.
908
- * @returns A tuple of the index and the sibling path of the L1ToL2Message (undefined if not found).
909
- */
910
965
  public async getL1ToL2MessageMembershipWitness(
911
- blockNumber: L2BlockNumber,
966
+ block: BlockParameter,
912
967
  l1ToL2Message: Fr,
913
968
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
914
- const db = await this.#getWorldState(blockNumber);
969
+ const db = await this.#getWorldState(block);
915
970
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
916
971
  if (!witness) {
917
972
  return undefined;
@@ -921,9 +976,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
921
976
  return [witness.index, witness.path];
922
977
  }
923
978
 
924
- public async getL1ToL2MessageBlock(l1ToL2Message: Fr): Promise<number | undefined> {
979
+ public async getL1ToL2MessageBlock(l1ToL2Message: Fr): Promise<BlockNumber | undefined> {
925
980
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
926
- return messageIndex ? InboxLeaf.l2BlockFromIndex(messageIndex) : undefined;
981
+ return messageIndex
982
+ ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex))
983
+ : undefined;
927
984
  }
928
985
 
929
986
  /**
@@ -937,54 +994,52 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
937
994
  }
938
995
 
939
996
  /**
940
- * Returns all the L2 to L1 messages in a block.
941
- * @param blockNumber - The block number at which to get the data.
942
- * @returns The L2 to L1 messages (undefined if the block number is not found).
997
+ * Returns all the L2 to L1 messages in an epoch.
998
+ * @param epoch - The epoch at which to get the data.
999
+ * @returns The L2 to L1 messages (empty array if the epoch is not found).
943
1000
  */
944
- public async getL2ToL1Messages(blockNumber: L2BlockNumber): Promise<Fr[][] | undefined> {
945
- const block = await this.blockSource.getBlock(blockNumber === 'latest' ? await this.getBlockNumber() : blockNumber);
946
- return block?.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs);
1001
+ public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
1002
+ // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1003
+ const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1004
+ const blocksInCheckpoints: L2Block[][] = [];
1005
+ let previousSlotNumber = SlotNumber.ZERO;
1006
+ let checkpointIndex = -1;
1007
+ for (const checkpointedBlock of checkpointedBlocks) {
1008
+ const block = checkpointedBlock.block;
1009
+ const slotNumber = block.header.globalVariables.slotNumber;
1010
+ if (slotNumber !== previousSlotNumber) {
1011
+ checkpointIndex++;
1012
+ blocksInCheckpoints.push([]);
1013
+ previousSlotNumber = slotNumber;
1014
+ }
1015
+ blocksInCheckpoints[checkpointIndex].push(block);
1016
+ }
1017
+ return blocksInCheckpoints.map(blocks =>
1018
+ blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1019
+ );
947
1020
  }
948
1021
 
949
- /**
950
- * Returns a sibling path for a leaf in the committed blocks tree.
951
- * @param blockNumber - The block number at which to get the data.
952
- * @param leafIndex - Index of the leaf in the tree.
953
- * @returns The sibling path.
954
- */
955
1022
  public async getArchiveSiblingPath(
956
- blockNumber: L2BlockNumber,
1023
+ block: BlockParameter,
957
1024
  leafIndex: bigint,
958
1025
  ): Promise<SiblingPath<typeof ARCHIVE_HEIGHT>> {
959
- const committedDb = await this.#getWorldState(blockNumber);
1026
+ const committedDb = await this.#getWorldState(block);
960
1027
  return committedDb.getSiblingPath(MerkleTreeId.ARCHIVE, leafIndex);
961
1028
  }
962
1029
 
963
- /**
964
- * Returns a sibling path for a leaf in the committed public data tree.
965
- * @param blockNumber - The block number at which to get the data.
966
- * @param leafIndex - Index of the leaf in the tree.
967
- * @returns The sibling path.
968
- */
969
1030
  public async getPublicDataSiblingPath(
970
- blockNumber: L2BlockNumber,
1031
+ block: BlockParameter,
971
1032
  leafIndex: bigint,
972
1033
  ): Promise<SiblingPath<typeof PUBLIC_DATA_TREE_HEIGHT>> {
973
- const committedDb = await this.#getWorldState(blockNumber);
1034
+ const committedDb = await this.#getWorldState(block);
974
1035
  return committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, leafIndex);
975
1036
  }
976
1037
 
977
- /**
978
- * Returns a nullifier membership witness for a given nullifier at a given block.
979
- * @param blockNumber - The block number at which to get the index.
980
- * @param nullifier - Nullifier we try to find witness for.
981
- * @returns The nullifier membership witness (if found).
982
- */
983
1038
  public async getNullifierMembershipWitness(
984
- blockNumber: L2BlockNumber,
1039
+ block: BlockParameter,
985
1040
  nullifier: Fr,
986
1041
  ): Promise<NullifierMembershipWitness | undefined> {
987
- const db = await this.#getWorldState(blockNumber);
1042
+ const db = await this.#getWorldState(block);
988
1043
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
989
1044
  if (!witness) {
990
1045
  return undefined;
@@ -1001,7 +1056,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1001
1056
 
1002
1057
  /**
1003
1058
  * Returns a low nullifier membership witness for a given nullifier at a given block.
1004
- * @param blockNumber - The block number at which to get the index.
1059
+ * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1005
1060
  * @param nullifier - Nullifier we try to find the low nullifier witness for.
1006
1061
  * @returns The low nullifier membership witness (if found).
1007
1062
  * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
@@ -1014,10 +1069,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1014
1069
  * TODO: This is a confusing behavior and we should eventually address that.
1015
1070
  */
1016
1071
  public async getLowNullifierMembershipWitness(
1017
- blockNumber: L2BlockNumber,
1072
+ block: BlockParameter,
1018
1073
  nullifier: Fr,
1019
1074
  ): Promise<NullifierMembershipWitness | undefined> {
1020
- const committedDb = await this.#getWorldState(blockNumber);
1075
+ const committedDb = await this.#getWorldState(block);
1021
1076
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1022
1077
  if (!findResult) {
1023
1078
  return undefined;
@@ -1032,8 +1087,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1032
1087
  return new NullifierMembershipWitness(BigInt(index), preimageData as NullifierLeafPreimage, siblingPath);
1033
1088
  }
1034
1089
 
1035
- async getPublicDataWitness(blockNumber: L2BlockNumber, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1036
- const committedDb = await this.#getWorldState(blockNumber);
1090
+ async getPublicDataWitness(block: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1091
+ const committedDb = await this.#getWorldState(block);
1037
1092
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1038
1093
  if (!lowLeafResult) {
1039
1094
  return undefined;
@@ -1047,19 +1102,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1047
1102
  }
1048
1103
  }
1049
1104
 
1050
- /**
1051
- * Gets the storage value at the given contract storage slot.
1052
- *
1053
- * @remarks The storage slot here refers to the slot as it is defined in Noir not the index in the merkle tree.
1054
- * Aztec's version of `eth_getStorageAt`.
1055
- *
1056
- * @param contract - Address of the contract to query.
1057
- * @param slot - Slot to query.
1058
- * @param blockNumber - The block number at which to get the data or 'latest'.
1059
- * @returns Storage value at the given contract slot.
1060
- */
1061
- public async getPublicStorageAt(blockNumber: L2BlockNumber, contract: AztecAddress, slot: Fr): Promise<Fr> {
1062
- const committedDb = await this.#getWorldState(blockNumber);
1105
+ public async getPublicStorageAt(block: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1106
+ const committedDb = await this.#getWorldState(block);
1063
1107
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1064
1108
 
1065
1109
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
@@ -1073,23 +1117,23 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1073
1117
  return preimage.leaf.value;
1074
1118
  }
1075
1119
 
1076
- /**
1077
- * Returns the currently committed block header, or the initial header if no blocks have been produced.
1078
- * @returns The current committed block header.
1079
- */
1080
- public async getBlockHeader(blockNumber: L2BlockNumber = 'latest'): Promise<BlockHeader | undefined> {
1081
- return blockNumber === 0 || (blockNumber === 'latest' && (await this.blockSource.getBlockNumber()) === 0)
1082
- ? this.worldStateSynchronizer.getCommitted().getInitialHeader()
1083
- : this.blockSource.getBlockHeader(blockNumber);
1084
- }
1085
-
1086
- /**
1087
- * Get a block header specified by its hash.
1088
- * @param blockHash - The block hash being requested.
1089
- * @returns The requested block header.
1090
- */
1091
- public async getBlockHeaderByHash(blockHash: Fr): Promise<BlockHeader | undefined> {
1092
- return await this.blockSource.getBlockHeaderByHash(blockHash);
1120
+ public async getBlockHeader(block: BlockParameter = 'latest'): Promise<BlockHeader | undefined> {
1121
+ if (L2BlockHash.isL2BlockHash(block)) {
1122
+ const initialBlockHash = await this.#getInitialHeaderHash();
1123
+ if (block.equals(initialBlockHash)) {
1124
+ // Block source doesn't handle initial header so we need to handle the case separately.
1125
+ return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1126
+ }
1127
+ const blockHashFr = Fr.fromBuffer(block.toBuffer());
1128
+ return this.blockSource.getBlockHeaderByHash(blockHashFr);
1129
+ } else {
1130
+ // Block source doesn't handle initial header so we need to handle the case separately.
1131
+ const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
1132
+ if (blockNumber === BlockNumber.ZERO) {
1133
+ return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1134
+ }
1135
+ return this.blockSource.getBlockHeader(block);
1136
+ }
1093
1137
  }
1094
1138
 
1095
1139
  /**
@@ -1124,7 +1168,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1124
1168
  }
1125
1169
 
1126
1170
  const txHash = tx.getTxHash();
1127
- const blockNumber = (await this.blockSource.getBlockNumber()) + 1;
1171
+ const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1128
1172
 
1129
1173
  // If sequencer is not initialized, we just set these values to zero for simulation.
1130
1174
  const coinbase = EthAddress.ZERO;
@@ -1149,11 +1193,17 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1149
1193
 
1150
1194
  const merkleTreeFork = await this.worldStateSynchronizer.fork();
1151
1195
  try {
1152
- const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, {
1196
+ const config = PublicSimulatorConfig.from({
1153
1197
  skipFeeEnforcement,
1154
- clientInitiatedSimulation: true,
1155
- maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads,
1198
+ collectDebugLogs: true,
1199
+ collectHints: false,
1200
+ collectCallMetadata: true,
1201
+ collectStatistics: false,
1202
+ collectionLimits: CollectionLimitsConfig.from({
1203
+ maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads,
1204
+ }),
1156
1205
  });
1206
+ const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1157
1207
 
1158
1208
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1159
1209
  const [processedTxs, failedTxs, _usedTxs, returns] = await processor.process([tx]);
@@ -1185,14 +1235,14 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1185
1235
 
1186
1236
  // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
1187
1237
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1188
- const blockNumber = (await this.blockSource.getBlockNumber()) + 1;
1238
+ const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1189
1239
  const validator = createValidatorForAcceptingTxs(db, this.contractDataSource, verifier, {
1190
1240
  timestamp: nextSlotTimestamp,
1191
1241
  blockNumber,
1192
1242
  l1ChainId: this.l1ChainId,
1193
1243
  rollupVersion: this.version,
1194
1244
  setupAllowList: this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions()),
1195
- gasFees: await this.getCurrentBaseFees(),
1245
+ gasFees: await this.getCurrentMinFees(),
1196
1246
  skipFeeEnforcement,
1197
1247
  txsPermitted: !this.config.disableTransactions,
1198
1248
  });
@@ -1242,8 +1292,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1242
1292
 
1243
1293
  public getValidatorStats(
1244
1294
  validatorAddress: EthAddress,
1245
- fromSlot?: bigint,
1246
- toSlot?: bigint,
1295
+ fromSlot?: SlotNumber,
1296
+ toSlot?: SlotNumber,
1247
1297
  ): Promise<SingleValidatorStats | undefined> {
1248
1298
  return this.validatorsSentinel?.getValidatorStats(validatorAddress, fromSlot, toSlot) ?? Promise.resolve(undefined);
1249
1299
  }
@@ -1264,7 +1314,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1264
1314
  }
1265
1315
 
1266
1316
  // And it has an L2 block hash
1267
- const l2BlockHash = await archiver.getL2Tips().then(tips => tips.latest.hash);
1317
+ const l2BlockHash = await archiver.getL2Tips().then(tips => tips.proposed.hash);
1268
1318
  if (!l2BlockHash) {
1269
1319
  this.metrics.recordSnapshotError();
1270
1320
  throw new Error(`Archiver has no latest L2 block hash downloaded. Cannot start snapshot.`);
@@ -1292,13 +1342,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1292
1342
  return Promise.resolve();
1293
1343
  }
1294
1344
 
1295
- public async rollbackTo(targetBlock: number, force?: boolean): Promise<void> {
1345
+ public async rollbackTo(targetBlock: BlockNumber, force?: boolean): Promise<void> {
1296
1346
  const archiver = this.blockSource as Archiver;
1297
1347
  if (!('rollbackTo' in archiver)) {
1298
1348
  throw new Error('Archiver implementation does not support rollbacks.');
1299
1349
  }
1300
1350
 
1301
- const finalizedBlock = await archiver.getL2Tips().then(tips => tips.finalized.number);
1351
+ const finalizedBlock = await archiver.getL2Tips().then(tips => tips.finalized.block.number);
1302
1352
  if (targetBlock < finalizedBlock) {
1303
1353
  if (force) {
1304
1354
  this.log.warn(`Clearing world state database to allow rolling back behind finalized block ${finalizedBlock}`);
@@ -1359,17 +1409,24 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1359
1409
  }
1360
1410
  }
1361
1411
 
1412
+ #getInitialHeaderHash(): Promise<L2BlockHash> {
1413
+ if (!this.initialHeaderHashPromise) {
1414
+ this.initialHeaderHashPromise = this.worldStateSynchronizer
1415
+ .getCommitted()
1416
+ .getInitialHeader()
1417
+ .hash()
1418
+ .then(hash => L2BlockHash.fromField(hash));
1419
+ }
1420
+ return this.initialHeaderHashPromise;
1421
+ }
1422
+
1362
1423
  /**
1363
1424
  * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1364
- * @param blockNumber - The block number at which to get the data.
1425
+ * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1365
1426
  * @returns An instance of a committed MerkleTreeOperations
1366
1427
  */
1367
- async #getWorldState(blockNumber: L2BlockNumber) {
1368
- if (typeof blockNumber === 'number' && blockNumber < INITIAL_L2_BLOCK_NUM - 1) {
1369
- throw new Error('Invalid block number to get world state for: ' + blockNumber);
1370
- }
1371
-
1372
- let blockSyncedTo: number = 0;
1428
+ async #getWorldState(block: BlockParameter) {
1429
+ let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1373
1430
  try {
1374
1431
  // Attempt to sync the world state if necessary
1375
1432
  blockSyncedTo = await this.#syncWorldState();
@@ -1377,15 +1434,40 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1377
1434
  this.log.error(`Error getting world state: ${err}`);
1378
1435
  }
1379
1436
 
1380
- // using a snapshot could be less efficient than using the committed db
1381
- if (blockNumber === 'latest' /*|| blockNumber === blockSyncedTo*/) {
1382
- this.log.debug(`Using committed db for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1437
+ if (block === 'latest') {
1438
+ this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
1383
1439
  return this.worldStateSynchronizer.getCommitted();
1384
- } else if (blockNumber <= blockSyncedTo) {
1440
+ }
1441
+
1442
+ if (L2BlockHash.isL2BlockHash(block)) {
1443
+ const initialBlockHash = await this.#getInitialHeaderHash();
1444
+ if (block.equals(initialBlockHash)) {
1445
+ // Block source doesn't handle initial header so we need to handle the case separately.
1446
+ return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1447
+ }
1448
+
1449
+ const blockHashFr = Fr.fromBuffer(block.toBuffer());
1450
+ const header = await this.blockSource.getBlockHeaderByHash(blockHashFr);
1451
+ if (!header) {
1452
+ throw new Error(
1453
+ `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.`,
1454
+ );
1455
+ }
1456
+ const blockNumber = header.getBlockNumber();
1457
+ this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1458
+ return this.worldStateSynchronizer.getSnapshot(blockNumber);
1459
+ }
1460
+
1461
+ // Block number provided
1462
+ {
1463
+ const blockNumber = block as BlockNumber;
1464
+
1465
+ if (blockNumber > blockSyncedTo) {
1466
+ throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1467
+ }
1468
+
1385
1469
  this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1386
1470
  return this.worldStateSynchronizer.getSnapshot(blockNumber);
1387
- } else {
1388
- throw new Error(`Block ${blockNumber} not yet synced`);
1389
1471
  }
1390
1472
  }
1391
1473
 
@@ -1393,8 +1475,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1393
1475
  * Ensure we fully sync the world state
1394
1476
  * @returns A promise that fulfils once the world state is synced
1395
1477
  */
1396
- async #syncWorldState(): Promise<number> {
1478
+ async #syncWorldState(): Promise<BlockNumber> {
1397
1479
  const blockSourceHeight = await this.blockSource.getBlockNumber();
1398
- return this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
1480
+ return await this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
1399
1481
  }
1400
1482
  }