@aztec/aztec-node 0.0.1-commit.934299a21 → 0.0.1-commit.949a33fd8

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,19 +1,22 @@
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';
16
18
  import { type Logger, createLogger } from '@aztec/foundation/log';
19
+ import { retryUntil } from '@aztec/foundation/retry';
17
20
  import { count } from '@aztec/foundation/string';
18
21
  import { DateProvider, Timer } from '@aztec/foundation/timer';
19
22
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
@@ -30,7 +33,12 @@ import {
30
33
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
31
34
  import { type ProverNode, type ProverNodeDeps, createProverNode } from '@aztec/prover-node';
32
35
  import { createKeyStoreForProver } from '@aztec/prover-node/config';
33
- import { GlobalVariableBuilder, SequencerClient, type SequencerPublisher } from '@aztec/sequencer-client';
36
+ import {
37
+ FeeProviderImpl,
38
+ GlobalVariableBuilder,
39
+ SequencerClient,
40
+ type SequencerPublisher,
41
+ } from '@aztec/sequencer-client';
34
42
  import { PublicProcessorFactory } from '@aztec/simulator/server';
35
43
  import {
36
44
  AttestationsBlockWatcher,
@@ -42,14 +50,13 @@ import {
42
50
  import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
43
51
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
44
52
  import {
45
- type BlockData,
46
53
  BlockHash,
47
54
  type BlockParameter,
48
55
  type DataInBlock,
49
56
  L2Block,
50
57
  type L2BlockSource,
58
+ inspectBlockParameter,
51
59
  } from '@aztec/stdlib/block';
52
- import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
53
60
  import type {
54
61
  ContractClassPublic,
55
62
  ContractDataSource,
@@ -57,16 +64,24 @@ import type {
57
64
  NodeInfo,
58
65
  ProtocolContractAddresses,
59
66
  } from '@aztec/stdlib/contract';
60
- import { GasFees } from '@aztec/stdlib/gas';
67
+ import { GasFees, type ManaUsageEstimate } from '@aztec/stdlib/gas';
61
68
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
62
- import {
63
- type AztecNode,
64
- type AztecNodeAdmin,
65
- type AztecNodeAdminConfig,
66
- AztecNodeAdminConfigSchema,
67
- type GetContractClassLogsResponse,
68
- type GetPublicLogsResponse,
69
+ import type {
70
+ AztecNode,
71
+ AztecNodeAdmin,
72
+ AztecNodeAdminConfig,
73
+ AztecNodeDebug,
74
+ BlockIncludeOptions,
75
+ BlockResponse,
76
+ ChainTip,
77
+ ChainTips,
78
+ CheckpointIncludeOptions,
79
+ CheckpointParameter,
80
+ CheckpointResponse,
81
+ GetContractClassLogsResponse,
82
+ GetPublicLogsResponse,
69
83
  } from '@aztec/stdlib/interfaces/client';
84
+ import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
70
85
  import {
71
86
  type AllowedElement,
72
87
  type ClientProtocolCircuitVerifier,
@@ -79,12 +94,12 @@ import {
79
94
  import type { DebugLogStore, LogFilter, SiloedTag, Tag, TxScopedL2Log } from '@aztec/stdlib/logs';
80
95
  import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
81
96
  import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
82
- import { P2PClientType } from '@aztec/stdlib/p2p';
83
- import type { Offense, SlashPayloadRound } from '@aztec/stdlib/slashing';
84
- import type { NullifierLeafPreimage, PublicDataTreeLeaf, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
97
+ import type { Offense } from '@aztec/stdlib/slashing';
98
+ import type { NullifierLeafPreimage, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
85
99
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
86
100
  import {
87
101
  type BlockHeader,
102
+ type FeeProvider,
88
103
  type GlobalVariableBuilder as GlobalVariableBuilderInterface,
89
104
  type IndexedTxEffect,
90
105
  PublicSimulationOutput,
@@ -96,6 +111,7 @@ import {
96
111
  } from '@aztec/stdlib/tx';
97
112
  import { getPackageVersion } from '@aztec/stdlib/update-checker';
98
113
  import type { SingleValidatorStats, ValidatorsStats } from '@aztec/stdlib/validators';
114
+ import type { GenesisData } from '@aztec/stdlib/world-state';
99
115
  import {
100
116
  Attributes,
101
117
  type TelemetryClient,
@@ -109,22 +125,29 @@ import {
109
125
  FullNodeCheckpointsBuilder,
110
126
  NodeKeystoreAdapter,
111
127
  ValidatorClient,
112
- createBlockProposalHandler,
128
+ createProposalHandler,
113
129
  createValidatorClient,
114
130
  } from '@aztec/validator-client';
131
+ import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
115
132
  import { createWorldStateSynchronizer } from '@aztec/world-state';
116
133
 
117
- import { createPublicClient, fallback, http } from 'viem';
134
+ import { createPublicClient } from 'viem';
118
135
 
119
136
  import { createSentinel } from '../sentinel/factory.js';
120
137
  import { Sentinel } from '../sentinel/sentinel.js';
138
+ import {
139
+ blockResponseFromBlockData,
140
+ blockResponseFromL2Block,
141
+ checkpointResponseFromCheckpointData,
142
+ checkpointResponseFromPublishedCheckpoint,
143
+ } from './block_response_helpers.js';
121
144
  import { type AztecNodeConfig, createKeyStoreForValidator } from './config.js';
122
145
  import { NodeMetrics } from './node_metrics.js';
123
146
 
124
147
  /**
125
148
  * The aztec node.
126
149
  */
127
- export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
150
+ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDebug, Traceable {
128
151
  private metrics: NodeMetrics;
129
152
  private initialHeaderHashPromise: Promise<BlockHash> | undefined = undefined;
130
153
 
@@ -146,12 +169,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
146
169
  protected readonly slasherClient: SlasherClientInterface | undefined,
147
170
  protected readonly validatorsSentinel: Sentinel | undefined,
148
171
  protected readonly epochPruneWatcher: EpochPruneWatcher | undefined,
172
+ protected readonly attestationsBlockWatcher: AttestationsBlockWatcher | undefined,
149
173
  protected readonly l1ChainId: number,
150
174
  protected readonly version: number,
151
175
  protected readonly globalVariableBuilder: GlobalVariableBuilderInterface,
176
+ protected readonly feeProvider: FeeProvider,
152
177
  protected readonly epochCache: EpochCacheInterface,
153
178
  protected readonly packageVersion: string,
154
- private proofVerifier: ClientProtocolCircuitVerifier,
179
+ private peerProofVerifier: ClientProtocolCircuitVerifier,
180
+ private rpcProofVerifier: ClientProtocolCircuitVerifier,
155
181
  private telemetry: TelemetryClient = getTelemetryClient(),
156
182
  private log = createLogger('node'),
157
183
  private blobClient?: BlobClientInterface,
@@ -173,15 +199,291 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
173
199
  }
174
200
  }
175
201
 
202
+ /** @internal Exposed for testing — returns the RPC proof verifier. */
203
+ public getProofVerifier(): ClientProtocolCircuitVerifier {
204
+ return this.rpcProofVerifier;
205
+ }
206
+
176
207
  public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
177
208
  const status = await this.worldStateSynchronizer.status();
178
209
  return status.syncSummary;
179
210
  }
180
211
 
212
+ public async getChainTips(): Promise<ChainTips> {
213
+ const { proposed, checkpointed, proven, finalized } = await this.blockSource.getL2Tips();
214
+ return { proposed, checkpointed, proven, finalized };
215
+ }
216
+
181
217
  public getL2Tips() {
182
218
  return this.blockSource.getL2Tips();
183
219
  }
184
220
 
221
+ public async getBlockHeader(number: BlockNumber | 'latest'): Promise<BlockHeader | undefined> {
222
+ const resolvedNumber = number === 'latest' ? await this.blockSource.getBlockNumber() : number;
223
+ if (resolvedNumber === BlockNumber.ZERO) {
224
+ return this.worldStateSynchronizer.getCommitted().getInitialHeader();
225
+ }
226
+ return this.blockSource.getBlockHeader(resolvedNumber);
227
+ }
228
+
229
+ public async getCheckpointedBlocks(from: BlockNumber, limit: number) {
230
+ return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
231
+ }
232
+
233
+ public getCheckpointsDataForEpoch(epoch: EpochNumber) {
234
+ return this.blockSource.getCheckpointsDataForEpoch(epoch);
235
+ }
236
+
237
+ public getBlockNumber(tip?: ChainTip): Promise<BlockNumber> {
238
+ switch (tip) {
239
+ case undefined:
240
+ case 'proposed':
241
+ return this.blockSource.getBlockNumber();
242
+ case 'checkpointed':
243
+ return this.blockSource.getCheckpointedL2BlockNumber();
244
+ case 'proven':
245
+ return this.blockSource.getProvenBlockNumber();
246
+ case 'finalized':
247
+ return this.blockSource.getFinalizedL2BlockNumber();
248
+ }
249
+ }
250
+
251
+ public async getCheckpointNumber(tip?: ChainTip): Promise<CheckpointNumber> {
252
+ switch (tip) {
253
+ case undefined:
254
+ case 'proposed':
255
+ case 'checkpointed':
256
+ return await this.blockSource.getCheckpointNumber();
257
+ case 'proven':
258
+ case 'finalized': {
259
+ const tips = await this.blockSource.getL2Tips();
260
+ return tip === 'proven' ? tips.proven.checkpoint.number : tips.finalized.checkpoint.number;
261
+ }
262
+ }
263
+ }
264
+
265
+ private isChainTip(value: unknown): value is ChainTip {
266
+ return value === 'proposed' || value === 'checkpointed' || value === 'proven' || value === 'finalized';
267
+ }
268
+
269
+ private async resolveBlockParameter(
270
+ param: BlockParameter,
271
+ ): Promise<{ number?: BlockNumber; hash?: BlockHash; archive?: Fr }> {
272
+ if (BlockHash.isBlockHash(param)) {
273
+ return { hash: param };
274
+ }
275
+ if (typeof param === 'number') {
276
+ return { number: param as BlockNumber };
277
+ }
278
+ if (param === 'latest') {
279
+ return { number: await this.blockSource.getBlockNumber() };
280
+ }
281
+ if (this.isChainTip(param)) {
282
+ return { number: await this.getBlockNumber(param) };
283
+ }
284
+ if (typeof param === 'object' && param !== null) {
285
+ if ('number' in param) {
286
+ return { number: param.number };
287
+ }
288
+ if ('hash' in param) {
289
+ return { hash: param.hash };
290
+ }
291
+ if ('archive' in param) {
292
+ return { archive: param.archive };
293
+ }
294
+ }
295
+ throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(param)}`);
296
+ }
297
+
298
+ private async resolveCheckpointParameter(
299
+ param: CheckpointParameter,
300
+ ): Promise<{ number?: CheckpointNumber; slot?: SlotNumber }> {
301
+ if (typeof param === 'number') {
302
+ return { number: param as CheckpointNumber };
303
+ }
304
+ if (param === 'latest') {
305
+ return { number: await this.blockSource.getCheckpointNumber() };
306
+ }
307
+ if (this.isChainTip(param)) {
308
+ return { number: await this.getCheckpointNumber(param) };
309
+ }
310
+ if (typeof param === 'object' && param !== null) {
311
+ if ('number' in param) {
312
+ return { number: param.number };
313
+ }
314
+ if ('slot' in param) {
315
+ return { slot: param.slot };
316
+ }
317
+ }
318
+ throw new BadRequestError(`Invalid CheckpointParameter: ${JSON.stringify(param)}`);
319
+ }
320
+
321
+ public async getBlock<Opts extends BlockIncludeOptions = {}>(
322
+ param: BlockParameter,
323
+ options: Opts = {} as Opts,
324
+ ): Promise<BlockResponse<Opts> | undefined> {
325
+ const resolved = await this.resolveBlockParameter(param);
326
+ const wantTxs = !!options.includeTransactions;
327
+ const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
328
+
329
+ if (resolved.hash !== undefined) {
330
+ const initial = await this.#getInitialHeaderHash();
331
+ if (resolved.hash.equals(initial)) {
332
+ return (await this.buildGenesisBlockResponse(options)) as BlockResponse<Opts>;
333
+ }
334
+ if (wantTxs) {
335
+ const block = await this.blockSource.getL2BlockByHash(resolved.hash);
336
+ if (!block) {
337
+ return undefined;
338
+ }
339
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(block.number) : undefined;
340
+ return (await blockResponseFromL2Block(block, options, ctx)) as BlockResponse<Opts>;
341
+ }
342
+ const data = await this.blockSource.getBlockHeaderByHash(resolved.hash);
343
+ if (!data) {
344
+ return undefined;
345
+ }
346
+ const blockNumber = data.globalVariables.blockNumber;
347
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(blockNumber) : undefined;
348
+ if (ctx) {
349
+ return blockResponseFromBlockData(ctx.data, blockNumber, options, ctx) as BlockResponse<Opts>;
350
+ }
351
+ const blockData = await this.blockSource.getBlockData(blockNumber);
352
+ if (!blockData) {
353
+ return undefined;
354
+ }
355
+ return blockResponseFromBlockData(blockData, blockNumber, options) as BlockResponse<Opts>;
356
+ }
357
+
358
+ if (resolved.archive !== undefined) {
359
+ if (wantTxs) {
360
+ const block = await this.blockSource.getL2BlockByArchive(resolved.archive);
361
+ if (!block) {
362
+ return undefined;
363
+ }
364
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(block.number) : undefined;
365
+ return (await blockResponseFromL2Block(block, options, ctx)) as BlockResponse<Opts>;
366
+ }
367
+ const data = await this.blockSource.getBlockDataByArchive(resolved.archive);
368
+ if (!data) {
369
+ return undefined;
370
+ }
371
+ const blockNumber = data.header.globalVariables.blockNumber;
372
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(blockNumber) : undefined;
373
+ return blockResponseFromBlockData(data, blockNumber, options, ctx) as BlockResponse<Opts>;
374
+ }
375
+
376
+ const blockNumber = resolved.number!;
377
+ if (blockNumber === BlockNumber.ZERO) {
378
+ return (await this.buildGenesisBlockResponse(options)) as BlockResponse<Opts>;
379
+ }
380
+ if (wantTxs) {
381
+ const block = await this.blockSource.getL2Block(blockNumber);
382
+ if (!block) {
383
+ return undefined;
384
+ }
385
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(blockNumber) : undefined;
386
+ return (await blockResponseFromL2Block(block, options, ctx)) as BlockResponse<Opts>;
387
+ }
388
+ const ctx = await this.blockSource.getBlockDataWithCheckpointContext(blockNumber);
389
+ if (!ctx) {
390
+ return undefined;
391
+ }
392
+ return blockResponseFromBlockData(ctx.data, blockNumber, options, ctx) as BlockResponse<Opts>;
393
+ }
394
+
395
+ public async getBlocks<Opts extends BlockIncludeOptions = {}>(
396
+ from: BlockNumber,
397
+ limit: number,
398
+ options: Opts = {} as Opts,
399
+ ): Promise<BlockResponse<Opts>[]> {
400
+ const wantTxs = !!options.includeTransactions;
401
+ const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
402
+ if (wantTxs) {
403
+ const blocks = await this.blockSource.getBlocks(from, limit);
404
+ return (await Promise.all(
405
+ blocks.map(async block => {
406
+ const ctx = wantContext ? await this.blockSource.getBlockDataWithCheckpointContext(block.number) : undefined;
407
+ return blockResponseFromL2Block(block, options, ctx);
408
+ }),
409
+ )) as BlockResponse<Opts>[];
410
+ }
411
+ const results: BlockResponse<Opts>[] = [];
412
+ for (let i = 0; i < limit; i++) {
413
+ const blockNumber = BlockNumber(from + i);
414
+ const ctx = await this.blockSource.getBlockDataWithCheckpointContext(blockNumber);
415
+ if (!ctx) {
416
+ break;
417
+ }
418
+ results.push(blockResponseFromBlockData(ctx.data, blockNumber, options, ctx) as BlockResponse<Opts>);
419
+ }
420
+ return results;
421
+ }
422
+
423
+ public async getCheckpoint<Opts extends CheckpointIncludeOptions = {}>(
424
+ param: CheckpointParameter,
425
+ options: Opts = {} as Opts,
426
+ ): Promise<CheckpointResponse<Opts> | undefined> {
427
+ const resolved = await this.resolveCheckpointParameter(param);
428
+ let checkpointNumber = resolved.number;
429
+ if (checkpointNumber === undefined && resolved.slot !== undefined) {
430
+ checkpointNumber = await this.blockSource.getCheckpointNumberBySlot(resolved.slot);
431
+ }
432
+ if (checkpointNumber === undefined) {
433
+ return undefined;
434
+ }
435
+ if (options.includeBlocks) {
436
+ const [checkpoint] = await this.blockSource.getCheckpoints(checkpointNumber, 1);
437
+ if (!checkpoint) {
438
+ return undefined;
439
+ }
440
+ return (await checkpointResponseFromPublishedCheckpoint(checkpoint, options)) as CheckpointResponse<Opts>;
441
+ }
442
+ const data = await this.blockSource.getCheckpointData(checkpointNumber);
443
+ if (!data) {
444
+ return undefined;
445
+ }
446
+ return checkpointResponseFromCheckpointData(data, options) as CheckpointResponse<Opts>;
447
+ }
448
+
449
+ public async getCheckpoints<Opts extends CheckpointIncludeOptions = {}>(
450
+ from: CheckpointNumber,
451
+ limit: number,
452
+ options: Opts = {} as Opts,
453
+ ): Promise<CheckpointResponse<Opts>[]> {
454
+ if (options.includeBlocks) {
455
+ const checkpoints = await this.blockSource.getCheckpoints(from, limit);
456
+ return (await Promise.all(
457
+ checkpoints.map(cp => checkpointResponseFromPublishedCheckpoint(cp, options)),
458
+ )) as CheckpointResponse<Opts>[];
459
+ }
460
+ const datas = await this.blockSource.getCheckpointDataRange(from, limit);
461
+ return datas.map(d => checkpointResponseFromCheckpointData(d, options)) as CheckpointResponse<Opts>[];
462
+ }
463
+
464
+ private async buildGenesisBlockResponse(options: BlockIncludeOptions): Promise<BlockResponse> {
465
+ const initial = this.worldStateSynchronizer.getCommitted().getInitialHeader();
466
+ const empty = L2Block.empty(initial);
467
+ const response: BlockResponse = {
468
+ header: empty.header,
469
+ archive: empty.archive,
470
+ hash: await this.#getInitialHeaderHash(),
471
+ checkpointNumber: empty.checkpointNumber,
472
+ indexWithinCheckpoint: empty.indexWithinCheckpoint,
473
+ number: empty.number,
474
+ };
475
+ if (options.includeTransactions) {
476
+ (response as BlockResponse).body = empty.body;
477
+ }
478
+ if (options.includeL1PublishInfo) {
479
+ (response as BlockResponse).l1 = { published: false };
480
+ }
481
+ if (options.includeAttestations) {
482
+ (response as BlockResponse).attestations = [];
483
+ }
484
+ return response;
485
+ }
486
+
185
487
  /**
186
488
  * initializes the Aztec Node, wait for component to sync.
187
489
  * @param config - The configuration to be used by the aztec node.
@@ -194,11 +496,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
194
496
  logger?: Logger;
195
497
  publisher?: SequencerPublisher;
196
498
  dateProvider?: DateProvider;
197
- p2pClientDeps?: P2PClientDeps<P2PClientType.Full>;
499
+ p2pClientDeps?: P2PClientDeps;
198
500
  proverNodeDeps?: Partial<ProverNodeDeps>;
501
+ slashingProtectionDb?: SlashingProtectionDatabase;
199
502
  } = {},
200
503
  options: {
201
- prefilledPublicData?: PublicDataTreeLeaf[];
504
+ genesis?: GenesisData;
202
505
  dontStartSequencer?: boolean;
203
506
  dontStartProverNode?: boolean;
204
507
  } = {},
@@ -258,7 +561,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
258
561
 
259
562
  const publicClient = createPublicClient({
260
563
  chain: ethereumChain.chainInfo,
261
- transport: fallback(config.l1RpcUrls.map((url: string) => http(url, { batch: false }))),
564
+ transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
262
565
  pollingInterval: config.viemPollingIntervalMS,
263
566
  });
264
567
 
@@ -272,10 +575,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
272
575
  config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
273
576
 
274
577
  const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
275
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
578
+ const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
276
579
  rollupContract.getL1GenesisTime(),
277
580
  rollupContract.getSlotDuration(),
278
581
  rollupContract.getVersion(),
582
+ rollupContract.getManaLimit().then(Number),
279
583
  ] as const);
280
584
 
281
585
  config.rollupVersion ??= Number(rollupVersionFromRollup);
@@ -293,280 +597,354 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
293
597
 
294
598
  const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, { dateProvider });
295
599
 
296
- const archiver = await createArchiver(
297
- config,
298
- { blobClient, epochCache, telemetry, dateProvider },
299
- { blockUntilSync: !config.skipArchiverInitialSync },
300
- );
301
-
302
- // now create the merkle trees and the world state synchronizer
303
- const worldStateSynchronizer = await createWorldStateSynchronizer(
304
- config,
305
- archiver,
306
- options.prefilledPublicData,
307
- telemetry,
308
- );
309
- const circuitVerifier =
310
- config.realProofs || config.debugForceTxProofVerification
311
- ? await BBCircuitVerifier.new(config)
312
- : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
313
-
314
- let debugLogStore: DebugLogStore;
315
- if (!config.realProofs) {
316
- log.warn(`Aztec node is accepting fake proofs`);
317
-
318
- debugLogStore = new InMemoryDebugLogStore();
319
- log.info(
320
- 'Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served',
600
+ // Track started resources so we can clean up on partial failure during node creation.
601
+ const started: { stop?(): Promise<void> | void }[] = [];
602
+ try {
603
+ const archiver = await createArchiver(
604
+ config,
605
+ { blobClient, epochCache, telemetry, dateProvider },
606
+ { blockUntilSync: !config.skipArchiverInitialSync },
321
607
  );
322
- } else {
323
- debugLogStore = new NullDebugLogStore();
324
- }
325
-
326
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
327
-
328
- // create the tx pool and the p2p client, which will need the l2 block source
329
- const p2pClient = await createP2PClient(
330
- P2PClientType.Full,
331
- config,
332
- archiver,
333
- proofVerifier,
334
- worldStateSynchronizer,
335
- epochCache,
336
- packageVersion,
337
- dateProvider,
338
- telemetry,
339
- deps.p2pClientDeps,
340
- );
608
+ started.push(archiver);
609
+
610
+ // now create the merkle trees and the world state synchronizer
611
+ const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.genesis, telemetry);
612
+ started.push(worldStateSynchronizer);
613
+ const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
614
+ let peerProofVerifier: ClientProtocolCircuitVerifier;
615
+ let rpcProofVerifier: ClientProtocolCircuitVerifier;
616
+ if (useRealVerifiers) {
617
+ peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
618
+ const rpcVerifier = await BBCircuitVerifier.new(config);
619
+ rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
620
+ } else {
621
+ peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
622
+ rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
623
+ }
624
+ started.push(peerProofVerifier, rpcProofVerifier);
341
625
 
342
- // We should really not be modifying the config object
343
- config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
626
+ let debugLogStore: DebugLogStore;
627
+ if (!config.realProofs) {
628
+ log.warn(`Aztec node is accepting fake proofs`);
344
629
 
345
- // Create FullNodeCheckpointsBuilder for validator and non-validator block proposal handling
346
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
347
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
348
- worldStateSynchronizer,
349
- archiver,
350
- dateProvider,
351
- telemetry,
352
- );
630
+ debugLogStore = new InMemoryDebugLogStore();
631
+ log.info(
632
+ 'Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served',
633
+ );
634
+ } else {
635
+ debugLogStore = new NullDebugLogStore();
636
+ }
353
637
 
354
- // We'll accumulate sentinel watchers here
355
- const watchers: Watcher[] = [];
356
-
357
- // Create validator client if required
358
- const validatorClient = await createValidatorClient(config, {
359
- checkpointsBuilder: validatorCheckpointsBuilder,
360
- worldState: worldStateSynchronizer,
361
- p2pClient,
362
- telemetry,
363
- dateProvider,
364
- epochCache,
365
- blockSource: archiver,
366
- l1ToL2MessageSource: archiver,
367
- keyStoreManager,
368
- blobClient,
369
- });
638
+ const globalVariableBuilderConfig = {
639
+ l1Contracts: config.l1Contracts,
640
+ ethereumSlotDuration: config.ethereumSlotDuration,
641
+ rollupVersion: BigInt(config.rollupVersion),
642
+ l1GenesisTime,
643
+ slotDuration: Number(slotDuration),
644
+ };
370
645
 
371
- // If we have a validator client, register it as a source of offenses for the slasher,
372
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
373
- // like attestations or auths will fail.
374
- if (validatorClient) {
375
- watchers.push(validatorClient);
376
- if (!options.dontStartSequencer) {
377
- await validatorClient.registerHandlers();
646
+ const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, globalVariableBuilderConfig);
647
+ const feeProvider = new FeeProviderImpl(dateProvider, publicClient, globalVariableBuilderConfig);
648
+
649
+ const proverOnly = config.enableProverNode && config.disableValidator;
650
+ if (proverOnly) {
651
+ log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
378
652
  }
379
- }
380
653
 
381
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
382
- // create a BlockProposalHandler to reexecute block proposals for monitoring
383
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
384
- log.info('Setting up block proposal reexecution for monitoring');
385
- createBlockProposalHandler(config, {
386
- checkpointsBuilder: validatorCheckpointsBuilder,
387
- worldState: worldStateSynchronizer,
654
+ // create the tx pool and the p2p client, which will need the l2 block source
655
+ const p2pClient = await createP2PClient(
656
+ config,
657
+ archiver,
658
+ peerProofVerifier,
659
+ worldStateSynchronizer,
388
660
  epochCache,
389
- blockSource: archiver,
390
- l1ToL2MessageSource: archiver,
391
- p2pClient,
661
+ feeProvider,
662
+ packageVersion,
392
663
  dateProvider,
393
664
  telemetry,
394
- }).registerForReexecution(p2pClient);
395
- }
665
+ deps.p2pClientDeps,
666
+ );
667
+ started.push(p2pClient);
668
+
669
+ // We'll accumulate sentinel watchers here
670
+ const watchers: Watcher[] = [];
671
+
672
+ // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
673
+ // Override maxTxsPerCheckpoint with the validator-specific limit if set.
674
+ const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
675
+ {
676
+ ...config,
677
+ l1GenesisTime,
678
+ slotDuration: Number(slotDuration),
679
+ rollupManaLimit,
680
+ maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint,
681
+ },
682
+ worldStateSynchronizer,
683
+ archiver,
684
+ dateProvider,
685
+ telemetry,
686
+ );
687
+
688
+ let validatorClient: ValidatorClient | undefined;
689
+
690
+ if (!config.disableValidator) {
691
+ // Create validator client if required
692
+ validatorClient = await createValidatorClient(config, {
693
+ checkpointsBuilder: validatorCheckpointsBuilder,
694
+ worldState: worldStateSynchronizer,
695
+ p2pClient,
696
+ telemetry,
697
+ dateProvider,
698
+ epochCache,
699
+ blockSource: archiver,
700
+ l1ToL2MessageSource: archiver,
701
+ keyStoreManager,
702
+ blobClient,
703
+ slashingProtectionDb: deps.slashingProtectionDb,
704
+ });
705
+
706
+ // If we have a validator client, register it as a source of offenses for the slasher,
707
+ // and have it register callbacks on the p2p client *before* we start it, otherwise messages
708
+ // like attestations or auths will fail.
709
+ if (validatorClient) {
710
+ watchers.push(validatorClient);
711
+
712
+ const vc = validatorClient;
713
+ const getValidatorAddresses = () => vc.getValidatorAddresses().map(a => a.toString());
714
+ validatorClient.getProposalHandler().register(p2pClient, true, archiver, getValidatorAddresses);
715
+
716
+ if (!options.dontStartSequencer) {
717
+ await validatorClient.registerHandlers();
718
+ }
719
+ }
720
+ }
396
721
 
397
- // Start world state and wait for it to sync to the archiver.
398
- await worldStateSynchronizer.start();
722
+ // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
723
+ // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
724
+ // while non-reexecution is used for validating the proposals and collecting their txs.
725
+ // Checkpoint proposals rebuild blobs if the blob client can upload blobs.
726
+ if (!validatorClient) {
727
+ const reexecute = !!config.alwaysReexecuteBlockProposals;
728
+ log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
729
+ createProposalHandler(config, {
730
+ checkpointsBuilder: validatorCheckpointsBuilder,
731
+ worldState: worldStateSynchronizer,
732
+ epochCache,
733
+ blockSource: archiver,
734
+ l1ToL2MessageSource: archiver,
735
+ p2pClient,
736
+ blobClient,
737
+ dateProvider,
738
+ telemetry,
739
+ }).register(p2pClient, reexecute, archiver);
740
+ }
399
741
 
400
- // Start p2p. Note that it depends on world state to be running.
401
- await p2pClient.start();
742
+ // Start world state and wait for it to sync to the archiver.
743
+ await worldStateSynchronizer.start();
402
744
 
403
- const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
404
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
405
- watchers.push(validatorsSentinel);
406
- }
745
+ // Start p2p. Note that it depends on world state to be running.
746
+ await p2pClient.start();
407
747
 
408
- let epochPruneWatcher: EpochPruneWatcher | undefined;
409
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
410
- epochPruneWatcher = new EpochPruneWatcher(
411
- archiver,
412
- archiver,
413
- epochCache,
414
- p2pClient.getTxProvider(),
415
- validatorCheckpointsBuilder,
416
- config,
417
- );
418
- watchers.push(epochPruneWatcher);
419
- }
748
+ let validatorsSentinel: Awaited<ReturnType<typeof createSentinel>> | undefined;
749
+ let epochPruneWatcher: EpochPruneWatcher | undefined;
750
+ let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
420
751
 
421
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
422
- let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
423
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
424
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
425
- watchers.push(attestationsBlockWatcher);
426
- }
752
+ if (!proverOnly) {
753
+ validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
754
+ if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
755
+ watchers.push(validatorsSentinel);
756
+ }
427
757
 
428
- // Start p2p-related services once the archiver has completed sync
429
- void archiver
430
- .waitForInitialSync()
431
- .then(async () => {
432
- await p2pClient.start();
433
- await validatorsSentinel?.start();
434
- await epochPruneWatcher?.start();
435
- await attestationsBlockWatcher?.start();
436
- log.info(`All p2p services started`);
437
- })
438
- .catch(err => log.error('Failed to start p2p services after archiver sync', err));
439
-
440
- // Validator enabled, create/start relevant service
441
- let sequencer: SequencerClient | undefined;
442
- let slasherClient: SlasherClientInterface | undefined;
443
- if (!config.disableValidator && validatorClient) {
444
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
445
- // as they are executed when the node is selected as proposer.
446
- const validatorAddresses = keyStoreManager
447
- ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses()
448
- : [];
449
-
450
- slasherClient = await createSlasher(
451
- config,
452
- config.l1Contracts,
453
- getPublicClient(config),
454
- watchers,
455
- dateProvider,
456
- epochCache,
457
- validatorAddresses,
458
- undefined, // logger
459
- );
460
- await slasherClient.start();
758
+ if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
759
+ epochPruneWatcher = new EpochPruneWatcher(
760
+ archiver,
761
+ archiver,
762
+ epochCache,
763
+ p2pClient.getTxProvider(),
764
+ validatorCheckpointsBuilder,
765
+ config,
766
+ );
767
+ watchers.push(epochPruneWatcher);
768
+ }
461
769
 
462
- const l1TxUtils = config.sequencerPublisherForwarderAddress
463
- ? await createForwarderL1TxUtilsFromSigners(
464
- publicClient,
465
- keyStoreManager!.createAllValidatorPublisherSigners(),
466
- config.sequencerPublisherForwarderAddress,
467
- { ...config, scope: 'sequencer' },
468
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
469
- )
470
- : await createL1TxUtilsFromSigners(
770
+ // We assume we want to slash for invalid attestations unless all max penalties are set to 0
771
+ if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
772
+ attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
773
+ watchers.push(attestationsBlockWatcher);
774
+ }
775
+ }
776
+
777
+ // Start p2p-related services once the archiver has completed sync
778
+ void archiver
779
+ .waitForInitialSync()
780
+ .then(async () => {
781
+ if (validatorsSentinel) {
782
+ await validatorsSentinel.start();
783
+ started.push(validatorsSentinel);
784
+ }
785
+ if (epochPruneWatcher) {
786
+ await epochPruneWatcher.start();
787
+ started.push(epochPruneWatcher);
788
+ }
789
+ if (attestationsBlockWatcher) {
790
+ await attestationsBlockWatcher.start();
791
+ started.push(attestationsBlockWatcher);
792
+ }
793
+ log.info(`All p2p services started`);
794
+ })
795
+ .catch(err => log.error('Failed to start p2p services after archiver sync', err));
796
+
797
+ // Validator enabled, create/start relevant service
798
+ let sequencer: SequencerClient | undefined;
799
+ let slasherClient: SlasherClientInterface | undefined;
800
+ if (!config.disableValidator && validatorClient) {
801
+ // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
802
+ // as they are executed when the node is selected as proposer.
803
+ const validatorAddresses = keyStoreManager
804
+ ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses()
805
+ : [];
806
+
807
+ slasherClient = await createSlasher(
808
+ config,
809
+ config.l1Contracts,
810
+ getPublicClient(config),
811
+ watchers,
812
+ dateProvider,
813
+ epochCache,
814
+ validatorAddresses,
815
+ undefined, // logger
816
+ );
817
+ await slasherClient.start();
818
+ started.push(slasherClient);
819
+
820
+ const l1TxUtils = config.sequencerPublisherForwarderAddress
821
+ ? await createForwarderL1TxUtilsFromSigners(
822
+ publicClient,
823
+ keyStoreManager!.createAllValidatorPublisherSigners(),
824
+ config.sequencerPublisherForwarderAddress,
825
+ { ...config, scope: 'sequencer' },
826
+ { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
827
+ )
828
+ : await createL1TxUtilsFromSigners(
829
+ publicClient,
830
+ keyStoreManager!.createAllValidatorPublisherSigners(),
831
+ { ...config, scope: 'sequencer' },
832
+ { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
833
+ );
834
+
835
+ // Create a funder L1TxUtils from the keystore funding account (if configured)
836
+ const fundingSigner = keyStoreManager?.createFundingSigner();
837
+ let funderL1TxUtils: L1TxUtils | undefined;
838
+ if (fundingSigner) {
839
+ const [funder] = await createL1TxUtilsFromSigners(
471
840
  publicClient,
472
- keyStoreManager!.createAllValidatorPublisherSigners(),
841
+ [fundingSigner],
473
842
  { ...config, scope: 'sequencer' },
474
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
843
+ { telemetry, logger: log.createChild('l1-tx-utils:funder'), dateProvider },
475
844
  );
845
+ funderL1TxUtils = funder;
846
+ }
476
847
 
477
- // Create and start the sequencer client
478
- const checkpointsBuilder = new CheckpointsBuilder(
479
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
480
- worldStateSynchronizer,
481
- archiver,
482
- dateProvider,
483
- telemetry,
484
- debugLogStore,
485
- );
848
+ // Create and start the sequencer client
849
+ const checkpointsBuilder = new CheckpointsBuilder(
850
+ { ...config, l1GenesisTime, slotDuration: Number(slotDuration), rollupManaLimit },
851
+ worldStateSynchronizer,
852
+ archiver,
853
+ dateProvider,
854
+ telemetry,
855
+ debugLogStore,
856
+ );
486
857
 
487
- sequencer = await SequencerClient.new(config, {
488
- ...deps,
489
- epochCache,
490
- l1TxUtils,
491
- validatorClient,
492
- p2pClient,
493
- worldStateSynchronizer,
494
- slasherClient,
495
- checkpointsBuilder,
496
- l2BlockSource: archiver,
497
- l1ToL2MessageSource: archiver,
498
- telemetry,
499
- dateProvider,
500
- blobClient,
501
- nodeKeyStore: keyStoreManager!,
502
- });
503
- }
858
+ sequencer = await SequencerClient.new(config, {
859
+ ...deps,
860
+ epochCache,
861
+ l1TxUtils,
862
+ funderL1TxUtils,
863
+ validatorClient,
864
+ p2pClient,
865
+ worldStateSynchronizer,
866
+ slasherClient,
867
+ checkpointsBuilder,
868
+ l2BlockSource: archiver,
869
+ l1ToL2MessageSource: archiver,
870
+ telemetry,
871
+ dateProvider,
872
+ blobClient,
873
+ nodeKeyStore: keyStoreManager!,
874
+ globalVariableBuilder,
875
+ });
876
+ }
504
877
 
505
- if (!options.dontStartSequencer && sequencer) {
506
- await sequencer.start();
507
- log.verbose(`Sequencer started`);
508
- } else if (sequencer) {
509
- log.warn(`Sequencer created but not started`);
510
- }
878
+ if (!options.dontStartSequencer && sequencer) {
879
+ await sequencer.start();
880
+ started.push(sequencer);
881
+ log.verbose(`Sequencer started`);
882
+ } else if (sequencer) {
883
+ log.warn(`Sequencer created but not started`);
884
+ }
511
885
 
512
- // Create prover node subsystem if enabled
513
- let proverNode: ProverNode | undefined;
514
- if (config.enableProverNode) {
515
- proverNode = await createProverNode(config, {
516
- ...deps.proverNodeDeps,
517
- telemetry,
518
- dateProvider,
886
+ // Create prover node subsystem if enabled
887
+ let proverNode: ProverNode | undefined;
888
+ if (config.enableProverNode) {
889
+ proverNode = await createProverNode(config, {
890
+ ...deps.proverNodeDeps,
891
+ telemetry,
892
+ dateProvider,
893
+ archiver,
894
+ worldStateSynchronizer,
895
+ p2pClient,
896
+ epochCache,
897
+ blobClient,
898
+ keyStoreManager,
899
+ });
900
+
901
+ if (!options.dontStartProverNode) {
902
+ await proverNode.start();
903
+ started.push(proverNode);
904
+ log.info(`Prover node subsystem started`);
905
+ } else {
906
+ log.info(`Prover node subsystem created but not started`);
907
+ }
908
+ }
909
+
910
+ const node = new AztecNodeService(
911
+ config,
912
+ p2pClient,
913
+ archiver,
914
+ archiver,
915
+ archiver,
519
916
  archiver,
520
917
  worldStateSynchronizer,
521
- p2pClient,
918
+ sequencer,
919
+ proverNode,
920
+ slasherClient,
921
+ validatorsSentinel,
922
+ epochPruneWatcher,
923
+ attestationsBlockWatcher,
924
+ ethereumChain.chainInfo.id,
925
+ config.rollupVersion,
926
+ globalVariableBuilder,
927
+ feeProvider,
522
928
  epochCache,
929
+ packageVersion,
930
+ peerProofVerifier,
931
+ rpcProofVerifier,
932
+ telemetry,
933
+ log,
523
934
  blobClient,
935
+ validatorClient,
524
936
  keyStoreManager,
525
- });
937
+ debugLogStore,
938
+ );
526
939
 
527
- if (!options.dontStartProverNode) {
528
- await proverNode.start();
529
- log.info(`Prover node subsystem started`);
530
- } else {
531
- log.info(`Prover node subsystem created but not started`);
940
+ return node;
941
+ } catch (err) {
942
+ log.error('Failed during node creation, stopping started resources', err);
943
+ for (const resource of started.reverse()) {
944
+ await tryStop(resource);
532
945
  }
946
+ throw err;
533
947
  }
534
-
535
- const globalVariableBuilder = new GlobalVariableBuilder({
536
- ...config,
537
- rollupVersion: BigInt(config.rollupVersion),
538
- l1GenesisTime,
539
- slotDuration: Number(slotDuration),
540
- });
541
-
542
- const node = new AztecNodeService(
543
- config,
544
- p2pClient,
545
- archiver,
546
- archiver,
547
- archiver,
548
- archiver,
549
- worldStateSynchronizer,
550
- sequencer,
551
- proverNode,
552
- slasherClient,
553
- validatorsSentinel,
554
- epochPruneWatcher,
555
- ethereumChain.chainInfo.id,
556
- config.rollupVersion,
557
- globalVariableBuilder,
558
- epochCache,
559
- packageVersion,
560
- proofVerifier,
561
- telemetry,
562
- log,
563
- blobClient,
564
- validatorClient,
565
- keyStoreManager,
566
- debugLogStore,
567
- );
568
-
569
- return node;
570
948
  }
571
949
 
572
950
  /**
@@ -607,7 +985,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
607
985
  }
608
986
 
609
987
  public async getAllowedPublicSetup(): Promise<AllowedElement[]> {
610
- return this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
988
+ return [...(await getDefaultAllowedSetupFunctions()), ...(this.config.txPublicSetupAllowListExtend ?? [])];
611
989
  }
612
990
 
613
991
  /**
@@ -641,73 +1019,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
641
1019
  return nodeInfo;
642
1020
  }
643
1021
 
644
- /**
645
- * Get a block specified by its block number, block hash, or 'latest'.
646
- * @param block - The block parameter (block number, block hash, or 'latest').
647
- * @returns The requested block.
648
- */
649
- public async getBlock(block: BlockParameter): Promise<L2Block | undefined> {
650
- if (BlockHash.isBlockHash(block)) {
651
- return this.getBlockByHash(block);
652
- }
653
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
654
- if (blockNumber === BlockNumber.ZERO) {
655
- return this.buildInitialBlock();
656
- }
657
- return await this.blockSource.getL2Block(blockNumber);
658
- }
659
-
660
- /**
661
- * Get a block specified by its hash.
662
- * @param blockHash - The block hash being requested.
663
- * @returns The requested block.
664
- */
665
- public async getBlockByHash(blockHash: BlockHash): Promise<L2Block | undefined> {
666
- const initialBlockHash = await this.#getInitialHeaderHash();
667
- if (blockHash.equals(initialBlockHash)) {
668
- return this.buildInitialBlock();
669
- }
670
- return await this.blockSource.getL2BlockByHash(blockHash);
671
- }
672
-
673
- private buildInitialBlock(): L2Block {
674
- const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
675
- return L2Block.empty(initialHeader);
676
- }
677
-
678
- /**
679
- * Get a block specified by its archive root.
680
- * @param archive - The archive root being requested.
681
- * @returns The requested block.
682
- */
683
- public async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
684
- return await this.blockSource.getL2BlockByArchive(archive);
685
- }
686
-
687
- /**
688
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
689
- * @param from - The start of the range of blocks to return.
690
- * @param limit - The maximum number of blocks to obtain.
691
- * @returns The blocks requested.
692
- */
693
- public async getBlocks(from: BlockNumber, limit: number): Promise<L2Block[]> {
694
- return (await this.blockSource.getBlocks(from, BlockNumber(limit))) ?? [];
695
- }
696
-
697
- public async getCheckpoints(from: CheckpointNumber, limit: number): Promise<PublishedCheckpoint[]> {
698
- return (await this.blockSource.getCheckpoints(from, limit)) ?? [];
699
- }
700
-
701
- public async getCheckpointedBlocks(from: BlockNumber, limit: number) {
702
- return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
1022
+ public async getCurrentMinFees(): Promise<GasFees> {
1023
+ return await this.feeProvider.getCurrentMinFees();
703
1024
  }
704
1025
 
705
- /**
706
- * Method to fetch the current min L2 fees.
707
- * @returns The current min L2 fees.
708
- */
709
- public async getCurrentMinFees(): Promise<GasFees> {
710
- return await this.globalVariableBuilder.getCurrentMinFees();
1026
+ /** Returns predicted min fees for the current slot and next N slots. */
1027
+ public async getPredictedMinFees(manaUsage?: ManaUsageEstimate): Promise<GasFees[]> {
1028
+ return await this.feeProvider.getPredictedMinFees(manaUsage);
711
1029
  }
712
1030
 
713
1031
  public async getMaxPriorityFees(): Promise<GasFees> {
@@ -718,22 +1036,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
718
1036
  return GasFees.from({ feePerDaGas: 0n, feePerL2Gas: 0n });
719
1037
  }
720
1038
 
721
- /**
722
- * Method to fetch the latest block number synchronized by the node.
723
- * @returns The block number.
724
- */
725
- public async getBlockNumber(): Promise<BlockNumber> {
726
- return await this.blockSource.getBlockNumber();
727
- }
728
-
729
- public async getProvenBlockNumber(): Promise<BlockNumber> {
730
- return await this.blockSource.getProvenBlockNumber();
731
- }
732
-
733
- public async getCheckpointedBlockNumber(): Promise<BlockNumber> {
734
- return await this.blockSource.getCheckpointedL2BlockNumber();
735
- }
736
-
737
1039
  /**
738
1040
  * Method to fetch the version of the package.
739
1041
  * @returns The node package version
@@ -771,18 +1073,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
771
1073
  page?: number,
772
1074
  referenceBlock?: BlockHash,
773
1075
  ): Promise<TxScopedL2Log[][]> {
1076
+ let upToBlockNumber: BlockNumber | undefined;
774
1077
  if (referenceBlock) {
775
1078
  const initialBlockHash = await this.#getInitialHeaderHash();
776
- if (!referenceBlock.equals(initialBlockHash)) {
1079
+ if (referenceBlock.equals(initialBlockHash)) {
1080
+ upToBlockNumber = BlockNumber(0);
1081
+ } else {
777
1082
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
778
1083
  if (!header) {
779
1084
  throw new Error(
780
1085
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
781
1086
  );
782
1087
  }
1088
+ upToBlockNumber = header.globalVariables.blockNumber;
783
1089
  }
784
1090
  }
785
- return this.logsSource.getPrivateLogsByTags(tags, page);
1091
+ return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
786
1092
  }
787
1093
 
788
1094
  public async getPublicLogsByTagsFromContract(
@@ -791,18 +1097,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
791
1097
  page?: number,
792
1098
  referenceBlock?: BlockHash,
793
1099
  ): Promise<TxScopedL2Log[][]> {
1100
+ let upToBlockNumber: BlockNumber | undefined;
794
1101
  if (referenceBlock) {
795
1102
  const initialBlockHash = await this.#getInitialHeaderHash();
796
- if (!referenceBlock.equals(initialBlockHash)) {
1103
+ if (referenceBlock.equals(initialBlockHash)) {
1104
+ upToBlockNumber = BlockNumber(0);
1105
+ } else {
797
1106
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
798
1107
  if (!header) {
799
1108
  throw new Error(
800
1109
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
801
1110
  );
802
1111
  }
1112
+ upToBlockNumber = header.globalVariables.blockNumber;
803
1113
  }
804
1114
  }
805
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
1115
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
806
1116
  }
807
1117
 
808
1118
  /**
@@ -843,9 +1153,16 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
843
1153
  throw new Error(`Invalid tx: ${reason}`);
844
1154
  }
845
1155
 
846
- await this.p2pClient!.sendTx(tx);
847
- this.metrics.receivedTx(timer.ms(), true);
848
- this.log.info(`Received tx ${txHash}`, { txHash });
1156
+ try {
1157
+ await this.p2pClient!.sendTx(tx);
1158
+ } catch (err) {
1159
+ this.metrics.receivedTx(timer.ms(), false);
1160
+ this.log.warn(`Mempool rejected tx ${txHash}: ${(err as Error).message}`, { txHash });
1161
+ throw err;
1162
+ }
1163
+ const duration = timer.ms();
1164
+ this.metrics.receivedTx(duration, true);
1165
+ this.log.info(`Received tx ${txHash} in ${duration}ms`, { txHash });
849
1166
  }
850
1167
 
851
1168
  public async getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
@@ -864,10 +1181,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
864
1181
  // If the tx is in the pool but not in the archiver, it's pending.
865
1182
  // This handles race conditions between archiver and p2p, where the archiver
866
1183
  // has pruned the block in which a tx was mined, but p2p has not caught up yet.
867
- receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
1184
+ receipt = new TxReceipt(txHash, TxStatus.PENDING, /*executionResult=*/ undefined, /*error=*/ undefined);
868
1185
  } else {
869
1186
  // Otherwise, if we don't know the tx, we consider it dropped.
870
- receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
1187
+ receipt = new TxReceipt(
1188
+ txHash,
1189
+ TxStatus.DROPPED,
1190
+ /*executionResult=*/ undefined,
1191
+ /*error=*/ 'Tx dropped by P2P node',
1192
+ );
871
1193
  }
872
1194
 
873
1195
  this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
@@ -884,10 +1206,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
884
1206
  */
885
1207
  public async stop() {
886
1208
  this.log.info(`Stopping Aztec Node`);
1209
+ await tryStop(this.attestationsBlockWatcher);
887
1210
  await tryStop(this.validatorsSentinel);
888
1211
  await tryStop(this.epochPruneWatcher);
889
1212
  await tryStop(this.slasherClient);
890
- await tryStop(this.proofVerifier);
1213
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
891
1214
  await tryStop(this.sequencer);
892
1215
  await tryStop(this.proverNode);
893
1216
  await tryStop(this.p2pClient);
@@ -943,59 +1266,65 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
943
1266
  treeId: MerkleTreeId,
944
1267
  leafValues: Fr[],
945
1268
  ): Promise<(DataInBlock<bigint> | undefined)[]> {
946
- const committedDb = await this.#getWorldState(referenceBlock);
1269
+ const committedDb = await this.getWorldState(referenceBlock);
947
1270
  const maybeIndices = await committedDb.findLeafIndices(
948
1271
  treeId,
949
1272
  leafValues.map(x => x.toBuffer()),
950
1273
  );
951
- // We filter out undefined values
952
- const indices = maybeIndices.filter(x => x !== undefined) as bigint[];
1274
+ // Filter out undefined values to query block numbers only for found leaves
1275
+ const definedIndices = maybeIndices.filter(x => x !== undefined);
953
1276
 
954
- // Now we find the block numbers for the indices
955
- const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, indices);
1277
+ // Now we find the block numbers for the defined indices
1278
+ const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
956
1279
 
957
- // If any of the block numbers are undefined, we throw an error.
958
- for (let i = 0; i < indices.length; i++) {
959
- if (blockNumbers[i] === undefined) {
960
- throw new Error(`Block number is undefined for leaf index ${indices[i]} in tree ${MerkleTreeId[treeId]}`);
1280
+ // Build a map from leaf index to block number
1281
+ const indexToBlockNumber = new Map<bigint, BlockNumber>();
1282
+ for (let i = 0; i < definedIndices.length; i++) {
1283
+ const blockNumber = blockNumbers[i];
1284
+ if (blockNumber === undefined) {
1285
+ throw new Error(
1286
+ `Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`,
1287
+ );
961
1288
  }
1289
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
962
1290
  }
963
1291
 
964
1292
  // Get unique block numbers in order to optimize num calls to getLeafValue function.
965
- const uniqueBlockNumbers = [...new Set(blockNumbers.filter(x => x !== undefined))];
1293
+ const uniqueBlockNumbers = [...new Set(indexToBlockNumber.values())];
966
1294
 
967
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
968
- // (note that block number corresponds to the leaf index in the archive tree).
1295
+ // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
969
1296
  const blockHashes = await Promise.all(
970
1297
  uniqueBlockNumbers.map(blockNumber => {
971
1298
  return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
972
1299
  }),
973
1300
  );
974
1301
 
975
- // If any of the block hashes are undefined, we throw an error.
1302
+ // Build a map from block number to block hash
1303
+ const blockNumberToHash = new Map<BlockNumber, BlockHash>();
976
1304
  for (let i = 0; i < uniqueBlockNumbers.length; i++) {
977
- if (blockHashes[i] === undefined) {
1305
+ const blockHash = blockHashes[i];
1306
+ if (blockHash === undefined) {
978
1307
  throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
979
1308
  }
1309
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
980
1310
  }
981
1311
 
982
1312
  // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
983
- return maybeIndices.map((index, i) => {
1313
+ return maybeIndices.map(index => {
984
1314
  if (index === undefined) {
985
1315
  return undefined;
986
1316
  }
987
- const blockNumber = blockNumbers[i];
1317
+ const blockNumber = indexToBlockNumber.get(index);
988
1318
  if (blockNumber === undefined) {
989
- return undefined;
1319
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
990
1320
  }
991
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
992
- const blockHash = blockHashes[blockHashIndex];
993
- if (!blockHash) {
994
- return undefined;
1321
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
1322
+ if (l2BlockHash === undefined) {
1323
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
995
1324
  }
996
1325
  return {
997
- l2BlockNumber: BlockNumber(Number(blockNumber)),
998
- l2BlockHash: new BlockHash(blockHash),
1326
+ l2BlockNumber: blockNumber,
1327
+ l2BlockHash,
999
1328
  data: index,
1000
1329
  };
1001
1330
  });
@@ -1005,7 +1334,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1005
1334
  referenceBlock: BlockParameter,
1006
1335
  blockHash: BlockHash,
1007
1336
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
1008
- const committedDb = await this.#getWorldState(referenceBlock);
1337
+ // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
1338
+ // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1339
+ // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1340
+ const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1341
+ if (referenceBlockNumber === BlockNumber.ZERO) {
1342
+ // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
1343
+ return undefined;
1344
+ }
1345
+ const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
1009
1346
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
1010
1347
  return pathAndIndex === undefined
1011
1348
  ? undefined
@@ -1016,7 +1353,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1016
1353
  referenceBlock: BlockParameter,
1017
1354
  noteHash: Fr,
1018
1355
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
1019
- const committedDb = await this.#getWorldState(referenceBlock);
1356
+ const committedDb = await this.getWorldState(referenceBlock);
1020
1357
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
1021
1358
  MerkleTreeId.NOTE_HASH_TREE,
1022
1359
  [noteHash],
@@ -1030,7 +1367,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1030
1367
  referenceBlock: BlockParameter,
1031
1368
  l1ToL2Message: Fr,
1032
1369
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
1033
- const db = await this.#getWorldState(referenceBlock);
1370
+ const db = await this.getWorldState(referenceBlock);
1034
1371
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
1035
1372
  if (!witness) {
1036
1373
  return undefined;
@@ -1040,11 +1377,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1040
1377
  return [witness.index, witness.path];
1041
1378
  }
1042
1379
 
1043
- public async getL1ToL2MessageBlock(l1ToL2Message: Fr): Promise<BlockNumber | undefined> {
1380
+ public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
1044
1381
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1045
- return messageIndex
1046
- ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex))
1047
- : undefined;
1382
+ return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1048
1383
  }
1049
1384
 
1050
1385
  /**
@@ -1065,19 +1400,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1065
1400
  public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
1066
1401
  // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1067
1402
  const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1068
- const blocksInCheckpoints: L2Block[][] = [];
1069
- let previousSlotNumber = SlotNumber.ZERO;
1070
- let checkpointIndex = -1;
1071
- for (const checkpointedBlock of checkpointedBlocks) {
1072
- const block = checkpointedBlock.block;
1073
- const slotNumber = block.header.globalVariables.slotNumber;
1074
- if (slotNumber !== previousSlotNumber) {
1075
- checkpointIndex++;
1076
- blocksInCheckpoints.push([]);
1077
- previousSlotNumber = slotNumber;
1078
- }
1079
- blocksInCheckpoints[checkpointIndex].push(block);
1080
- }
1403
+ const blocksInCheckpoints = chunkBy(checkpointedBlocks, cb => cb.block.header.globalVariables.slotNumber).map(
1404
+ group => group.map(cb => cb.block),
1405
+ );
1081
1406
  return blocksInCheckpoints.map(blocks =>
1082
1407
  blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1083
1408
  );
@@ -1087,7 +1412,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1087
1412
  referenceBlock: BlockParameter,
1088
1413
  nullifier: Fr,
1089
1414
  ): Promise<NullifierMembershipWitness | undefined> {
1090
- const db = await this.#getWorldState(referenceBlock);
1415
+ const db = await this.getWorldState(referenceBlock);
1091
1416
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
1092
1417
  if (!witness) {
1093
1418
  return undefined;
@@ -1102,33 +1427,20 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1102
1427
  return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
1103
1428
  }
1104
1429
 
1105
- /**
1106
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1107
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1108
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1109
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1110
- * @returns The low nullifier membership witness (if found).
1111
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1112
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1113
- * we are trying to prove non-inclusion for.
1114
- *
1115
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1116
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1117
- * index of the nullifier itself when it already exists in the tree.
1118
- * TODO: This is a confusing behavior and we should eventually address that.
1119
- */
1120
1430
  public async getLowNullifierMembershipWitness(
1121
1431
  referenceBlock: BlockParameter,
1122
1432
  nullifier: Fr,
1123
1433
  ): Promise<NullifierMembershipWitness | undefined> {
1124
- const committedDb = await this.#getWorldState(referenceBlock);
1434
+ const committedDb = await this.getWorldState(referenceBlock);
1125
1435
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1126
1436
  if (!findResult) {
1127
1437
  return undefined;
1128
1438
  }
1129
1439
  const { index, alreadyPresent } = findResult;
1130
1440
  if (alreadyPresent) {
1131
- this.log.warn(`Nullifier ${nullifier.toBigInt()} already exists in the tree`);
1441
+ throw new Error(
1442
+ `Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`,
1443
+ );
1132
1444
  }
1133
1445
  const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
1134
1446
 
@@ -1137,7 +1449,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1137
1449
  }
1138
1450
 
1139
1451
  async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1140
- const committedDb = await this.#getWorldState(referenceBlock);
1452
+ const committedDb = await this.getWorldState(referenceBlock);
1141
1453
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1142
1454
  if (!lowLeafResult) {
1143
1455
  return undefined;
@@ -1152,7 +1464,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1152
1464
  }
1153
1465
 
1154
1466
  public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1155
- const committedDb = await this.#getWorldState(referenceBlock);
1467
+ const committedDb = await this.getWorldState(referenceBlock);
1156
1468
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1157
1469
 
1158
1470
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
@@ -1166,41 +1478,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1166
1478
  return preimage.leaf.value;
1167
1479
  }
1168
1480
 
1169
- public async getBlockHeader(block: BlockParameter = 'latest'): Promise<BlockHeader | undefined> {
1170
- if (BlockHash.isBlockHash(block)) {
1171
- const initialBlockHash = await this.#getInitialHeaderHash();
1172
- if (block.equals(initialBlockHash)) {
1173
- // Block source doesn't handle initial header so we need to handle the case separately.
1174
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1175
- }
1176
- return this.blockSource.getBlockHeaderByHash(block);
1177
- } else {
1178
- // Block source doesn't handle initial header so we need to handle the case separately.
1179
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
1180
- if (blockNumber === BlockNumber.ZERO) {
1181
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1182
- }
1183
- return this.blockSource.getBlockHeader(block);
1184
- }
1185
- }
1186
-
1187
- /**
1188
- * Get a block header specified by its archive root.
1189
- * @param archive - The archive root being requested.
1190
- * @returns The requested block header.
1191
- */
1192
- public async getBlockHeaderByArchive(archive: Fr): Promise<BlockHeader | undefined> {
1193
- return await this.blockSource.getBlockHeaderByArchive(archive);
1194
- }
1195
-
1196
- public getBlockData(number: BlockNumber): Promise<BlockData | undefined> {
1197
- return this.blockSource.getBlockData(number);
1198
- }
1199
-
1200
- public getBlockDataByArchive(archive: Fr): Promise<BlockData | undefined> {
1201
- return this.blockSource.getBlockDataByArchive(archive);
1202
- }
1203
-
1204
1481
  /**
1205
1482
  * Simulates the public part of a transaction with the current state.
1206
1483
  * @param tx - The transaction to simulate.
@@ -1266,7 +1543,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1266
1543
  const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1267
1544
 
1268
1545
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1269
- const [processedTxs, failedTxs, _usedTxs, returns, _blobFields, debugLogs] = await processor.process([tx]);
1546
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1270
1547
  // REFACTOR: Consider returning the error rather than throwing
1271
1548
  if (failedTxs.length) {
1272
1549
  this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
@@ -1292,11 +1569,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1292
1569
  { isSimulation, skipFeeEnforcement }: { isSimulation?: boolean; skipFeeEnforcement?: boolean } = {},
1293
1570
  ): Promise<TxValidationResult> {
1294
1571
  const db = this.worldStateSynchronizer.getCommitted();
1295
- const verifier = isSimulation ? undefined : this.proofVerifier;
1572
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1296
1573
 
1297
1574
  // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1298
1575
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1299
1576
  const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1577
+ const l1Constants = await this.blockSource.getL1Constants();
1300
1578
  const validator = createTxValidatorForAcceptingTxsOverRPC(
1301
1579
  db,
1302
1580
  this.contractDataSource,
@@ -1306,10 +1584,16 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1306
1584
  blockNumber,
1307
1585
  l1ChainId: this.l1ChainId,
1308
1586
  rollupVersion: this.version,
1309
- setupAllowList: this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions()),
1587
+ setupAllowList: [
1588
+ ...(await getDefaultAllowedSetupFunctions()),
1589
+ ...(this.config.txPublicSetupAllowListExtend ?? []),
1590
+ ],
1310
1591
  gasFees: await this.getCurrentMinFees(),
1311
1592
  skipFeeEnforcement,
1312
1593
  txsPermitted: !this.config.disableTransactions,
1594
+ rollupManaLimit: l1Constants.rollupManaLimit,
1595
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1596
+ maxBlockDAGas: this.config.validateMaxDABlockGas,
1313
1597
  },
1314
1598
  this.log.getBindings(),
1315
1599
  );
@@ -1334,7 +1618,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1334
1618
  archiver.updateConfig(config);
1335
1619
  }
1336
1620
  if (newConfig.realProofs !== this.config.realProofs) {
1337
- this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
1621
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
1622
+ if (newConfig.realProofs) {
1623
+ this.peerProofVerifier = await BatchChonkVerifier.new(newConfig, newConfig.bbChonkVerifyMaxBatch, 'peer');
1624
+ const rpcVerifier = await BBCircuitVerifier.new(newConfig);
1625
+ this.rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, newConfig.numConcurrentIVCVerifiers);
1626
+ } else {
1627
+ this.peerProofVerifier = new TestCircuitVerifier();
1628
+ this.rpcProofVerifier = new TestCircuitVerifier();
1629
+ }
1338
1630
  }
1339
1631
 
1340
1632
  this.config = newConfig;
@@ -1409,7 +1701,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1409
1701
  return Promise.resolve();
1410
1702
  }
1411
1703
 
1412
- public async rollbackTo(targetBlock: BlockNumber, force?: boolean): Promise<void> {
1704
+ public async rollbackTo(targetBlock: BlockNumber, force?: boolean, resumeSync = true): Promise<void> {
1413
1705
  const archiver = this.blockSource as Archiver;
1414
1706
  if (!('rollbackTo' in archiver)) {
1415
1707
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1439,9 +1731,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1439
1731
  this.log.error(`Error during rollback`, err);
1440
1732
  throw err;
1441
1733
  } finally {
1442
- this.log.info(`Resuming world state and archiver sync.`);
1443
- this.worldStateSynchronizer.resumeSync();
1444
- archiver.resume();
1734
+ if (resumeSync) {
1735
+ this.log.info(`Resuming world state and archiver sync.`);
1736
+ this.worldStateSynchronizer.resumeSync();
1737
+ archiver.resume();
1738
+ } else {
1739
+ this.log.info(`Sync left paused after rollback (resumeSync=false).`);
1740
+ }
1445
1741
  }
1446
1742
  }
1447
1743
 
@@ -1458,19 +1754,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1458
1754
  return Promise.resolve();
1459
1755
  }
1460
1756
 
1461
- public getSlashPayloads(): Promise<SlashPayloadRound[]> {
1462
- if (!this.slasherClient) {
1463
- throw new Error(`Slasher client not enabled`);
1464
- }
1465
- return this.slasherClient.getSlashPayloads();
1466
- }
1467
-
1468
1757
  public getSlashOffenses(round: bigint | 'all' | 'current'): Promise<Offense[]> {
1469
1758
  if (!this.slasherClient) {
1470
1759
  throw new Error(`Slasher client not enabled`);
1471
1760
  }
1472
1761
  if (round === 'all') {
1473
- return this.slasherClient.getPendingOffenses();
1762
+ return this.slasherClient.getOffenses();
1474
1763
  } else {
1475
1764
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1476
1765
  }
@@ -1564,6 +1853,40 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1564
1853
  this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1565
1854
  }
1566
1855
 
1856
+ public async mineBlock(): Promise<void> {
1857
+ if (!this.sequencer) {
1858
+ throw new BadRequestError('Cannot mine block: no sequencer is running');
1859
+ }
1860
+
1861
+ const currentBlockNumber = await this.getBlockNumber();
1862
+
1863
+ // Use slot duration + 50% buffer as the timeout so this works on running networks too
1864
+ const { slotDuration } = await this.blockSource.getL1Constants();
1865
+ const timeoutSeconds = Math.ceil(slotDuration * 1.5);
1866
+
1867
+ // Temporarily set minTxsPerBlock to 0 so the sequencer produces a block even with no txs
1868
+ const originalMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock;
1869
+ this.sequencer.updateConfig({ minTxsPerBlock: 0 });
1870
+
1871
+ try {
1872
+ // Trigger the sequencer to produce a block immediately
1873
+ void this.sequencer.trigger();
1874
+
1875
+ // Wait for the new L2 block to appear
1876
+ await retryUntil(
1877
+ async () => {
1878
+ const newBlockNumber = await this.getBlockNumber();
1879
+ return newBlockNumber > currentBlockNumber ? true : undefined;
1880
+ },
1881
+ 'mineBlock',
1882
+ timeoutSeconds,
1883
+ 0.1,
1884
+ );
1885
+ } finally {
1886
+ this.sequencer.updateConfig({ minTxsPerBlock: originalMinTxsPerBlock });
1887
+ }
1888
+ }
1889
+
1567
1890
  #getInitialHeaderHash(): Promise<BlockHash> {
1568
1891
  if (!this.initialHeaderHashPromise) {
1569
1892
  this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
@@ -1576,7 +1899,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1576
1899
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1577
1900
  * @returns An instance of a committed MerkleTreeOperations
1578
1901
  */
1579
- async #getWorldState(block: BlockParameter) {
1902
+ protected async getWorldState(block: BlockParameter) {
1580
1903
  let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1581
1904
  try {
1582
1905
  // Attempt to sync the world state if necessary
@@ -1590,35 +1913,77 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1590
1913
  return this.worldStateSynchronizer.getCommitted();
1591
1914
  }
1592
1915
 
1916
+ // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1917
+ let blockNumber: BlockNumber;
1593
1918
  if (BlockHash.isBlockHash(block)) {
1594
1919
  const initialBlockHash = await this.#getInitialHeaderHash();
1595
1920
  if (block.equals(initialBlockHash)) {
1596
- // Block source doesn't handle initial header so we need to handle the case separately.
1597
- return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1921
+ // Block 0 is a first-class historical block: its state lives in the trees' persisted
1922
+ // block-0 payload. Resolving the genesis hash to block number 0 lets the snapshot path
1923
+ // pin reads to genesis state even after the node has advanced past it.
1924
+ blockNumber = BlockNumber.ZERO;
1925
+ } else {
1926
+ const header = await this.blockSource.getBlockHeaderByHash(block);
1927
+ if (!header) {
1928
+ throw new Error(
1929
+ `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.`,
1930
+ );
1931
+ }
1932
+ blockNumber = header.getBlockNumber();
1598
1933
  }
1934
+ } else {
1935
+ blockNumber = block as BlockNumber;
1936
+ }
1599
1937
 
1600
- const header = await this.blockSource.getBlockHeaderByHash(block);
1601
- if (!header) {
1938
+ // Check it's within world state sync range
1939
+ if (blockNumber > blockSyncedTo) {
1940
+ throw new Error(
1941
+ `Queried block ${inspectBlockParameter(block)} not yet synced by the node (node is synced upto ${blockSyncedTo}).`,
1942
+ );
1943
+ }
1944
+ this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1945
+
1946
+ const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
1947
+
1948
+ // Double-check world-state synced to the same block hash as was requested
1949
+ if (BlockHash.isBlockHash(block)) {
1950
+ const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1951
+ if (!blockHash || !block.equals(blockHash)) {
1952
+ const initialBlockHash = await this.#getInitialHeaderHash();
1602
1953
  throw new Error(
1603
- `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.`,
1954
+ `Block hash ${block.toString()} not found in world state at block number ${blockNumber} (world state has ${blockHash?.toString() ?? 'no hash'} at that index, genesis header hash is ${initialBlockHash.toString()}). If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
1604
1955
  );
1605
1956
  }
1606
- const blockNumber = header.getBlockNumber();
1607
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1608
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1609
1957
  }
1610
1958
 
1611
- // Block number provided
1612
- {
1613
- const blockNumber = block as BlockNumber;
1959
+ return snapshot;
1960
+ }
1614
1961
 
1615
- if (blockNumber > blockSyncedTo) {
1616
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
1962
+ /** Resolves any {@link BlockParameter} variant to a concrete block number. */
1963
+ protected async resolveBlockNumber(block: BlockParameter): Promise<BlockNumber> {
1964
+ const resolved = await this.resolveBlockParameter(block);
1965
+ if (resolved.number !== undefined) {
1966
+ return resolved.number;
1967
+ }
1968
+ if (resolved.hash !== undefined) {
1969
+ const initialBlockHash = await this.#getInitialHeaderHash();
1970
+ if (resolved.hash.equals(initialBlockHash)) {
1971
+ return BlockNumber.ZERO;
1617
1972
  }
1618
-
1619
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1620
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1973
+ const header = await this.blockSource.getBlockHeaderByHash(resolved.hash);
1974
+ if (!header) {
1975
+ throw new Error(`Block hash ${resolved.hash.toString()} not found.`);
1976
+ }
1977
+ return header.getBlockNumber();
1978
+ }
1979
+ if (resolved.archive !== undefined) {
1980
+ const header = await this.blockSource.getBlockHeaderByArchive(resolved.archive);
1981
+ if (!header) {
1982
+ throw new Error(`Block with archive ${resolved.archive.toString()} not found.`);
1983
+ }
1984
+ return header.getBlockNumber();
1621
1985
  }
1986
+ throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(block)}`);
1622
1987
  }
1623
1988
 
1624
1989
  /**