@aztec/aztec-node 0.0.1-commit.9372f48 → 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,30 +1,44 @@
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';
5
+ import { Blob } from '@aztec/blob-lib';
4
6
  import { ARCHIVE_HEIGHT, type L1_TO_L2_MSG_TREE_HEIGHT, type NOTE_HASH_TREE_HEIGHT } from '@aztec/constants';
5
7
  import { EpochCache, type EpochCacheInterface } from '@aztec/epoch-cache';
6
8
  import { createEthereumChain } from '@aztec/ethereum/chain';
7
- import { getPublicClient } from '@aztec/ethereum/client';
9
+ import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
8
10
  import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
9
11
  import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
12
+ import type { L1TxUtils } from '@aztec/ethereum/l1-tx-utils';
10
13
  import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
11
- import { compactArray, pick } from '@aztec/foundation/collection';
14
+ import { chunkBy, compactArray, pick, unique } from '@aztec/foundation/collection';
12
15
  import { Fr } from '@aztec/foundation/curves/bn254';
13
16
  import { EthAddress } from '@aztec/foundation/eth-address';
14
17
  import { BadRequestError } from '@aztec/foundation/json-rpc';
15
18
  import { type Logger, createLogger } from '@aztec/foundation/log';
19
+ import { retryUntil } from '@aztec/foundation/retry';
16
20
  import { count } from '@aztec/foundation/string';
17
21
  import { DateProvider, Timer } from '@aztec/foundation/timer';
18
22
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
19
- import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
23
+ import { type KeyStore, KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
20
24
  import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
25
+ import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
21
26
  import {
22
- createForwarderL1TxUtilsFromEthSigner,
23
- createL1TxUtilsWithBlobsFromEthSigner,
24
- } from '@aztec/node-lib/factories';
25
- import { type P2P, type P2PClientDeps, createP2PClient, getDefaultAllowedSetupFunctions } from '@aztec/p2p';
27
+ type P2P,
28
+ type P2PClientDeps,
29
+ createP2PClient,
30
+ createTxValidatorForAcceptingTxsOverRPC,
31
+ getDefaultAllowedSetupFunctions,
32
+ } from '@aztec/p2p';
26
33
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
27
- import { GlobalVariableBuilder, SequencerClient, type SequencerPublisher } from '@aztec/sequencer-client';
34
+ import { type ProverNode, type ProverNodeDeps, createProverNode } from '@aztec/prover-node';
35
+ import { createKeyStoreForProver } from '@aztec/prover-node/config';
36
+ import {
37
+ FeeProviderImpl,
38
+ GlobalVariableBuilder,
39
+ SequencerClient,
40
+ type SequencerPublisher,
41
+ } from '@aztec/sequencer-client';
28
42
  import { PublicProcessorFactory } from '@aztec/simulator/server';
29
43
  import {
30
44
  AttestationsBlockWatcher,
@@ -35,8 +49,14 @@ import {
35
49
  } from '@aztec/slasher';
36
50
  import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
37
51
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
38
- import { BlockHash, type BlockParameter, type DataInBlock, L2Block, type L2BlockSource } from '@aztec/stdlib/block';
39
- import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
52
+ import {
53
+ BlockHash,
54
+ type BlockParameter,
55
+ type DataInBlock,
56
+ L2Block,
57
+ type L2BlockSource,
58
+ inspectBlockParameter,
59
+ } from '@aztec/stdlib/block';
40
60
  import type {
41
61
  ContractClassPublic,
42
62
  ContractDataSource,
@@ -44,16 +64,24 @@ import type {
44
64
  NodeInfo,
45
65
  ProtocolContractAddresses,
46
66
  } from '@aztec/stdlib/contract';
47
- import { GasFees } from '@aztec/stdlib/gas';
67
+ import { GasFees, type ManaUsageEstimate } from '@aztec/stdlib/gas';
48
68
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
49
- import {
50
- type AztecNode,
51
- type AztecNodeAdmin,
52
- type AztecNodeAdminConfig,
53
- AztecNodeAdminConfigSchema,
54
- type GetContractClassLogsResponse,
55
- 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,
56
83
  } from '@aztec/stdlib/interfaces/client';
84
+ import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
57
85
  import {
58
86
  type AllowedElement,
59
87
  type ClientProtocolCircuitVerifier,
@@ -63,14 +91,15 @@ import {
63
91
  type WorldStateSynchronizer,
64
92
  tryStop,
65
93
  } from '@aztec/stdlib/interfaces/server';
66
- import type { LogFilter, SiloedTag, Tag, TxScopedL2Log } from '@aztec/stdlib/logs';
94
+ import type { DebugLogStore, LogFilter, SiloedTag, Tag, TxScopedL2Log } from '@aztec/stdlib/logs';
95
+ import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
67
96
  import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
68
- import { P2PClientType } from '@aztec/stdlib/p2p';
69
- import type { Offense, SlashPayloadRound } from '@aztec/stdlib/slashing';
70
- 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';
71
99
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
72
100
  import {
73
101
  type BlockHeader,
102
+ type FeeProvider,
74
103
  type GlobalVariableBuilder as GlobalVariableBuilderInterface,
75
104
  type IndexedTxEffect,
76
105
  PublicSimulationOutput,
@@ -82,6 +111,7 @@ import {
82
111
  } from '@aztec/stdlib/tx';
83
112
  import { getPackageVersion } from '@aztec/stdlib/update-checker';
84
113
  import type { SingleValidatorStats, ValidatorsStats } from '@aztec/stdlib/validators';
114
+ import type { GenesisData } from '@aztec/stdlib/world-state';
85
115
  import {
86
116
  Attributes,
87
117
  type TelemetryClient,
@@ -95,23 +125,29 @@ import {
95
125
  FullNodeCheckpointsBuilder,
96
126
  NodeKeystoreAdapter,
97
127
  ValidatorClient,
98
- createBlockProposalHandler,
128
+ createProposalHandler,
99
129
  createValidatorClient,
100
- createValidatorForAcceptingTxs,
101
130
  } from '@aztec/validator-client';
131
+ import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
102
132
  import { createWorldStateSynchronizer } from '@aztec/world-state';
103
133
 
104
- import { createPublicClient, fallback, http } from 'viem';
134
+ import { createPublicClient } from 'viem';
105
135
 
106
136
  import { createSentinel } from '../sentinel/factory.js';
107
137
  import { Sentinel } from '../sentinel/sentinel.js';
138
+ import {
139
+ blockResponseFromBlockData,
140
+ blockResponseFromL2Block,
141
+ checkpointResponseFromCheckpointData,
142
+ checkpointResponseFromPublishedCheckpoint,
143
+ } from './block_response_helpers.js';
108
144
  import { type AztecNodeConfig, createKeyStoreForValidator } from './config.js';
109
145
  import { NodeMetrics } from './node_metrics.js';
110
146
 
111
147
  /**
112
148
  * The aztec node.
113
149
  */
114
- export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
150
+ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDebug, Traceable {
115
151
  private metrics: NodeMetrics;
116
152
  private initialHeaderHashPromise: Promise<BlockHash> | undefined = undefined;
117
153
 
@@ -129,24 +165,43 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
129
165
  protected readonly l1ToL2MessageSource: L1ToL2MessageSource,
130
166
  protected readonly worldStateSynchronizer: WorldStateSynchronizer,
131
167
  protected readonly sequencer: SequencerClient | undefined,
168
+ protected readonly proverNode: ProverNode | undefined,
132
169
  protected readonly slasherClient: SlasherClientInterface | undefined,
133
170
  protected readonly validatorsSentinel: Sentinel | undefined,
134
171
  protected readonly epochPruneWatcher: EpochPruneWatcher | undefined,
172
+ protected readonly attestationsBlockWatcher: AttestationsBlockWatcher | undefined,
135
173
  protected readonly l1ChainId: number,
136
174
  protected readonly version: number,
137
175
  protected readonly globalVariableBuilder: GlobalVariableBuilderInterface,
176
+ protected readonly feeProvider: FeeProvider,
138
177
  protected readonly epochCache: EpochCacheInterface,
139
178
  protected readonly packageVersion: string,
140
- private proofVerifier: ClientProtocolCircuitVerifier,
179
+ private peerProofVerifier: ClientProtocolCircuitVerifier,
180
+ private rpcProofVerifier: ClientProtocolCircuitVerifier,
141
181
  private telemetry: TelemetryClient = getTelemetryClient(),
142
182
  private log = createLogger('node'),
143
183
  private blobClient?: BlobClientInterface,
184
+ private validatorClient?: ValidatorClient,
185
+ private keyStoreManager?: KeystoreManager,
186
+ private debugLogStore: DebugLogStore = new NullDebugLogStore(),
144
187
  ) {
145
188
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
146
189
  this.tracer = telemetry.getTracer('AztecNodeService');
147
190
 
148
191
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
149
192
  this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
193
+
194
+ // A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
195
+ // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
196
+ // memory which could be a DoS vector on the sequencer (since no fees are paid for debug logs).
197
+ if (debugLogStore.isEnabled && config.realProofs) {
198
+ throw new Error('debugLogStore should never be enabled when realProofs are set');
199
+ }
200
+ }
201
+
202
+ /** @internal Exposed for testing — returns the RPC proof verifier. */
203
+ public getProofVerifier(): ClientProtocolCircuitVerifier {
204
+ return this.rpcProofVerifier;
150
205
  }
151
206
 
152
207
  public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
@@ -154,10 +209,281 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
154
209
  return status.syncSummary;
155
210
  }
156
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
+
157
217
  public getL2Tips() {
158
218
  return this.blockSource.getL2Tips();
159
219
  }
160
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
+
161
487
  /**
162
488
  * initializes the Aztec Node, wait for component to sync.
163
489
  * @param config - The configuration to be used by the aztec node.
@@ -170,11 +496,14 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
170
496
  logger?: Logger;
171
497
  publisher?: SequencerPublisher;
172
498
  dateProvider?: DateProvider;
173
- p2pClientDeps?: P2PClientDeps<P2PClientType.Full>;
499
+ p2pClientDeps?: P2PClientDeps;
500
+ proverNodeDeps?: Partial<ProverNodeDeps>;
501
+ slashingProtectionDb?: SlashingProtectionDatabase;
174
502
  } = {},
175
503
  options: {
176
- prefilledPublicData?: PublicDataTreeLeaf[];
504
+ genesis?: GenesisData;
177
505
  dontStartSequencer?: boolean;
506
+ dontStartProverNode?: boolean;
178
507
  } = {},
179
508
  ): Promise<AztecNodeService> {
180
509
  const config = { ...inputConfig }; // Copy the config so we dont mutate the input object
@@ -184,16 +513,29 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
184
513
  const dateProvider = deps.dateProvider ?? new DateProvider();
185
514
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
186
515
 
187
- // Build a key store from file if given or from environment otherwise
516
+ // Build a key store from file if given or from environment otherwise.
517
+ // We keep the raw KeyStore available so we can merge with prover keys if enableProverNode is set.
188
518
  let keyStoreManager: KeystoreManager | undefined;
189
519
  const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
190
520
  if (keyStoreProvided) {
191
521
  const keyStores = loadKeystores(config.keyStoreDirectory!);
192
522
  keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
193
523
  } else {
194
- const keyStore = createKeyStoreForValidator(config);
195
- if (keyStore) {
196
- keyStoreManager = new KeystoreManager(keyStore);
524
+ const rawKeyStores: KeyStore[] = [];
525
+ const validatorKeyStore = createKeyStoreForValidator(config);
526
+ if (validatorKeyStore) {
527
+ rawKeyStores.push(validatorKeyStore);
528
+ }
529
+ if (config.enableProverNode) {
530
+ const proverKeyStore = createKeyStoreForProver(config);
531
+ if (proverKeyStore) {
532
+ rawKeyStores.push(proverKeyStore);
533
+ }
534
+ }
535
+ if (rawKeyStores.length > 0) {
536
+ keyStoreManager = new KeystoreManager(
537
+ rawKeyStores.length === 1 ? rawKeyStores[0] : mergeKeystores(rawKeyStores),
538
+ );
197
539
  }
198
540
  }
199
541
 
@@ -204,10 +546,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
204
546
  if (keyStoreManager === undefined) {
205
547
  throw new Error('Failed to create key store, a requirement for running a validator');
206
548
  }
207
- if (!keyStoreProvided) {
208
- log.warn(
209
- 'KEY STORE CREATED FROM ENVIRONMENT, IT IS RECOMMENDED TO USE A FILE-BASED KEY STORE IN PRODUCTION ENVIRONMENTS',
210
- );
549
+ if (!keyStoreProvided && process.env.NODE_ENV !== 'test') {
550
+ log.warn("Keystore created from env: it's recommended to use a file-based key store for production");
211
551
  }
212
552
  ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
213
553
  }
@@ -221,7 +561,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
221
561
 
222
562
  const publicClient = createPublicClient({
223
563
  chain: ethereumChain.chainInfo,
224
- transport: fallback(config.l1RpcUrls.map((url: string) => http(url, { batch: false }))),
564
+ transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
225
565
  pollingInterval: config.viemPollingIntervalMS,
226
566
  });
227
567
 
@@ -235,10 +575,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
235
575
  config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
236
576
 
237
577
  const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
238
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
578
+ const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
239
579
  rollupContract.getL1GenesisTime(),
240
580
  rollupContract.getSlotDuration(),
241
581
  rollupContract.getVersion(),
582
+ rollupContract.getManaLimit().then(Number),
242
583
  ] as const);
243
584
 
244
585
  config.rollupVersion ??= Number(rollupVersionFromRollup);
@@ -249,247 +590,361 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
249
590
  );
250
591
  }
251
592
 
252
- const blobClient = await createBlobClientWithFileStores(config, createLogger('node:blob-client:client'));
593
+ const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
253
594
 
254
595
  // attempt snapshot sync if possible
255
596
  await trySnapshotSync(config, log);
256
597
 
257
598
  const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, { dateProvider });
258
599
 
259
- const archiver = await createArchiver(
260
- config,
261
- { blobClient, epochCache, telemetry, dateProvider },
262
- { blockUntilSync: !config.skipArchiverInitialSync },
263
- );
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 },
607
+ );
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);
264
625
 
265
- // now create the merkle trees and the world state synchronizer
266
- const worldStateSynchronizer = await createWorldStateSynchronizer(
267
- config,
268
- archiver,
269
- options.prefilledPublicData,
270
- telemetry,
271
- );
272
- const circuitVerifier =
273
- config.realProofs || config.debugForceTxProofVerification
274
- ? await BBCircuitVerifier.new(config)
275
- : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
276
- if (!config.realProofs) {
277
- log.warn(`Aztec node is accepting fake proofs`);
278
- }
279
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
280
-
281
- // create the tx pool and the p2p client, which will need the l2 block source
282
- const p2pClient = await createP2PClient(
283
- P2PClientType.Full,
284
- config,
285
- archiver,
286
- proofVerifier,
287
- worldStateSynchronizer,
288
- epochCache,
289
- packageVersion,
290
- dateProvider,
291
- telemetry,
292
- deps.p2pClientDeps,
293
- );
626
+ let debugLogStore: DebugLogStore;
627
+ if (!config.realProofs) {
628
+ log.warn(`Aztec node is accepting fake proofs`);
294
629
 
295
- // We should really not be modifying the config object
296
- config.txPublicSetupAllowList = config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
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
+ }
297
637
 
298
- // Create FullNodeCheckpointsBuilder for validator and non-validator block proposal handling
299
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
300
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
301
- worldStateSynchronizer,
302
- archiver,
303
- dateProvider,
304
- telemetry,
305
- );
638
+ const globalVariableBuilderConfig = {
639
+ l1Contracts: config.l1Contracts,
640
+ ethereumSlotDuration: config.ethereumSlotDuration,
641
+ rollupVersion: BigInt(config.rollupVersion),
642
+ l1GenesisTime,
643
+ slotDuration: Number(slotDuration),
644
+ };
306
645
 
307
- // We'll accumulate sentinel watchers here
308
- const watchers: Watcher[] = [];
309
-
310
- // Create validator client if required
311
- const validatorClient = await createValidatorClient(config, {
312
- checkpointsBuilder: validatorCheckpointsBuilder,
313
- worldState: worldStateSynchronizer,
314
- p2pClient,
315
- telemetry,
316
- dateProvider,
317
- epochCache,
318
- blockSource: archiver,
319
- l1ToL2MessageSource: archiver,
320
- keyStoreManager,
321
- blobClient,
322
- });
646
+ const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, globalVariableBuilderConfig);
647
+ const feeProvider = new FeeProviderImpl(dateProvider, publicClient, globalVariableBuilderConfig);
323
648
 
324
- // If we have a validator client, register it as a source of offenses for the slasher,
325
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
326
- // like attestations or auths will fail.
327
- if (validatorClient) {
328
- watchers.push(validatorClient);
329
- if (!options.dontStartSequencer) {
330
- await validatorClient.registerHandlers();
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');
331
652
  }
332
- }
333
653
 
334
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
335
- // create a BlockProposalHandler to reexecute block proposals for monitoring
336
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
337
- log.info('Setting up block proposal reexecution for monitoring');
338
- createBlockProposalHandler(config, {
339
- checkpointsBuilder: validatorCheckpointsBuilder,
340
- 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,
341
660
  epochCache,
342
- blockSource: archiver,
343
- l1ToL2MessageSource: archiver,
344
- p2pClient,
661
+ feeProvider,
662
+ packageVersion,
345
663
  dateProvider,
346
664
  telemetry,
347
- }).registerForReexecution(p2pClient);
348
- }
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
+ );
349
687
 
350
- // Start world state and wait for it to sync to the archiver.
351
- await worldStateSynchronizer.start();
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
+ }
352
721
 
353
- // Start p2p. Note that it depends on world state to be running.
354
- await p2pClient.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
+ }
355
741
 
356
- const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
357
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
358
- watchers.push(validatorsSentinel);
359
- }
742
+ // Start world state and wait for it to sync to the archiver.
743
+ await worldStateSynchronizer.start();
360
744
 
361
- let epochPruneWatcher: EpochPruneWatcher | undefined;
362
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
363
- epochPruneWatcher = new EpochPruneWatcher(
364
- archiver,
365
- archiver,
366
- epochCache,
367
- p2pClient.getTxProvider(),
368
- validatorCheckpointsBuilder,
369
- config,
370
- );
371
- watchers.push(epochPruneWatcher);
372
- }
745
+ // Start p2p. Note that it depends on world state to be running.
746
+ await p2pClient.start();
373
747
 
374
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
375
- let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
376
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
377
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
378
- watchers.push(attestationsBlockWatcher);
379
- }
748
+ let validatorsSentinel: Awaited<ReturnType<typeof createSentinel>> | undefined;
749
+ let epochPruneWatcher: EpochPruneWatcher | undefined;
750
+ let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
380
751
 
381
- // Start p2p-related services once the archiver has completed sync
382
- void archiver
383
- .waitForInitialSync()
384
- .then(async () => {
385
- await p2pClient.start();
386
- await validatorsSentinel?.start();
387
- await epochPruneWatcher?.start();
388
- await attestationsBlockWatcher?.start();
389
- log.info(`All p2p services started`);
390
- })
391
- .catch(err => log.error('Failed to start p2p services after archiver sync', err));
392
-
393
- // Validator enabled, create/start relevant service
394
- let sequencer: SequencerClient | undefined;
395
- let slasherClient: SlasherClientInterface | undefined;
396
- if (!config.disableValidator && validatorClient) {
397
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
398
- // as they are executed when the node is selected as proposer.
399
- const validatorAddresses = keyStoreManager
400
- ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses()
401
- : [];
402
-
403
- slasherClient = await createSlasher(
404
- config,
405
- config.l1Contracts,
406
- getPublicClient(config),
407
- watchers,
408
- dateProvider,
409
- epochCache,
410
- validatorAddresses,
411
- undefined, // logger
412
- );
413
- await slasherClient.start();
752
+ if (!proverOnly) {
753
+ validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
754
+ if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
755
+ watchers.push(validatorsSentinel);
756
+ }
414
757
 
415
- const l1TxUtils = config.publisherForwarderAddress
416
- ? await createForwarderL1TxUtilsFromEthSigner(
417
- publicClient,
418
- keyStoreManager!.createAllValidatorPublisherSigners(),
419
- config.publisherForwarderAddress,
420
- { ...config, scope: 'sequencer' },
421
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider },
422
- )
423
- : await createL1TxUtilsWithBlobsFromEthSigner(
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
+ }
769
+
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(
424
840
  publicClient,
425
- keyStoreManager!.createAllValidatorPublisherSigners(),
841
+ [fundingSigner],
426
842
  { ...config, scope: 'sequencer' },
427
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider },
843
+ { telemetry, logger: log.createChild('l1-tx-utils:funder'), dateProvider },
428
844
  );
845
+ funderL1TxUtils = funder;
846
+ }
429
847
 
430
- // Create and start the sequencer client
431
- const checkpointsBuilder = new CheckpointsBuilder(
432
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
433
- worldStateSynchronizer,
434
- archiver,
435
- dateProvider,
436
- telemetry,
437
- );
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
+ );
438
857
 
439
- sequencer = await SequencerClient.new(config, {
440
- ...deps,
441
- epochCache,
442
- l1TxUtils,
443
- validatorClient,
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
+ }
877
+
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
+ }
885
+
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,
444
912
  p2pClient,
913
+ archiver,
914
+ archiver,
915
+ archiver,
916
+ archiver,
445
917
  worldStateSynchronizer,
918
+ sequencer,
919
+ proverNode,
446
920
  slasherClient,
447
- checkpointsBuilder,
448
- l2BlockSource: archiver,
449
- l1ToL2MessageSource: archiver,
921
+ validatorsSentinel,
922
+ epochPruneWatcher,
923
+ attestationsBlockWatcher,
924
+ ethereumChain.chainInfo.id,
925
+ config.rollupVersion,
926
+ globalVariableBuilder,
927
+ feeProvider,
928
+ epochCache,
929
+ packageVersion,
930
+ peerProofVerifier,
931
+ rpcProofVerifier,
450
932
  telemetry,
451
- dateProvider,
933
+ log,
452
934
  blobClient,
453
- nodeKeyStore: keyStoreManager!,
454
- });
455
- }
935
+ validatorClient,
936
+ keyStoreManager,
937
+ debugLogStore,
938
+ );
456
939
 
457
- if (!options.dontStartSequencer && sequencer) {
458
- await sequencer.start();
459
- log.verbose(`Sequencer started`);
460
- } else if (sequencer) {
461
- log.warn(`Sequencer 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);
945
+ }
946
+ throw err;
462
947
  }
463
-
464
- const globalVariableBuilder = new GlobalVariableBuilder({
465
- ...config,
466
- rollupVersion: BigInt(config.rollupVersion),
467
- l1GenesisTime,
468
- slotDuration: Number(slotDuration),
469
- });
470
-
471
- return new AztecNodeService(
472
- config,
473
- p2pClient,
474
- archiver,
475
- archiver,
476
- archiver,
477
- archiver,
478
- worldStateSynchronizer,
479
- sequencer,
480
- slasherClient,
481
- validatorsSentinel,
482
- epochPruneWatcher,
483
- ethereumChain.chainInfo.id,
484
- config.rollupVersion,
485
- globalVariableBuilder,
486
- epochCache,
487
- packageVersion,
488
- proofVerifier,
489
- telemetry,
490
- log,
491
- blobClient,
492
- );
493
948
  }
494
949
 
495
950
  /**
@@ -500,6 +955,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
500
955
  return this.sequencer;
501
956
  }
502
957
 
958
+ /** Returns the prover node subsystem, if enabled. */
959
+ public getProverNode(): ProverNode | undefined {
960
+ return this.proverNode;
961
+ }
962
+
503
963
  public getBlockSource(): L2BlockSource {
504
964
  return this.blockSource;
505
965
  }
@@ -525,7 +985,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
525
985
  }
526
986
 
527
987
  public async getAllowedPublicSetup(): Promise<AllowedElement[]> {
528
- return this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
988
+ return [...(await getDefaultAllowedSetupFunctions()), ...(this.config.txPublicSetupAllowListExtend ?? [])];
529
989
  }
530
990
 
531
991
  /**
@@ -553,78 +1013,19 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
553
1013
  enr,
554
1014
  l1ContractAddresses: contractAddresses,
555
1015
  protocolContractAddresses: protocolContractAddresses,
1016
+ realProofs: !!this.config.realProofs,
556
1017
  };
557
1018
 
558
1019
  return nodeInfo;
559
1020
  }
560
1021
 
561
- /**
562
- * Get a block specified by its block number, block hash, or 'latest'.
563
- * @param block - The block parameter (block number, block hash, or 'latest').
564
- * @returns The requested block.
565
- */
566
- public async getBlock(block: BlockParameter): Promise<L2Block | undefined> {
567
- if (BlockHash.isBlockHash(block)) {
568
- return this.getBlockByHash(block);
569
- }
570
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
571
- if (blockNumber === BlockNumber.ZERO) {
572
- return this.buildInitialBlock();
573
- }
574
- return await this.blockSource.getL2Block(blockNumber);
575
- }
576
-
577
- /**
578
- * Get a block specified by its hash.
579
- * @param blockHash - The block hash being requested.
580
- * @returns The requested block.
581
- */
582
- public async getBlockByHash(blockHash: BlockHash): Promise<L2Block | undefined> {
583
- const initialBlockHash = await this.#getInitialHeaderHash();
584
- if (blockHash.equals(initialBlockHash)) {
585
- return this.buildInitialBlock();
586
- }
587
- return await this.blockSource.getL2BlockByHash(blockHash);
588
- }
589
-
590
- private buildInitialBlock(): L2Block {
591
- const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
592
- return L2Block.empty(initialHeader);
593
- }
594
-
595
- /**
596
- * Get a block specified by its archive root.
597
- * @param archive - The archive root being requested.
598
- * @returns The requested block.
599
- */
600
- public async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
601
- return await this.blockSource.getL2BlockByArchive(archive);
602
- }
603
-
604
- /**
605
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
606
- * @param from - The start of the range of blocks to return.
607
- * @param limit - The maximum number of blocks to obtain.
608
- * @returns The blocks requested.
609
- */
610
- public async getBlocks(from: BlockNumber, limit: number): Promise<L2Block[]> {
611
- return (await this.blockSource.getBlocks(from, BlockNumber(limit))) ?? [];
612
- }
613
-
614
- public async getCheckpoints(from: CheckpointNumber, limit: number): Promise<PublishedCheckpoint[]> {
615
- return (await this.blockSource.getCheckpoints(from, limit)) ?? [];
1022
+ public async getCurrentMinFees(): Promise<GasFees> {
1023
+ return await this.feeProvider.getCurrentMinFees();
616
1024
  }
617
1025
 
618
- public async getCheckpointedBlocks(from: BlockNumber, limit: number) {
619
- return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
620
- }
621
-
622
- /**
623
- * Method to fetch the current min L2 fees.
624
- * @returns The current min L2 fees.
625
- */
626
- public async getCurrentMinFees(): Promise<GasFees> {
627
- 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);
628
1029
  }
629
1030
 
630
1031
  public async getMaxPriorityFees(): Promise<GasFees> {
@@ -635,22 +1036,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
635
1036
  return GasFees.from({ feePerDaGas: 0n, feePerL2Gas: 0n });
636
1037
  }
637
1038
 
638
- /**
639
- * Method to fetch the latest block number synchronized by the node.
640
- * @returns The block number.
641
- */
642
- public async getBlockNumber(): Promise<BlockNumber> {
643
- return await this.blockSource.getBlockNumber();
644
- }
645
-
646
- public async getProvenBlockNumber(): Promise<BlockNumber> {
647
- return await this.blockSource.getProvenBlockNumber();
648
- }
649
-
650
- public async getCheckpointedBlockNumber(): Promise<BlockNumber> {
651
- return await this.blockSource.getCheckpointedL2BlockNumber();
652
- }
653
-
654
1039
  /**
655
1040
  * Method to fetch the version of the package.
656
1041
  * @returns The node package version
@@ -688,18 +1073,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
688
1073
  page?: number,
689
1074
  referenceBlock?: BlockHash,
690
1075
  ): Promise<TxScopedL2Log[][]> {
1076
+ let upToBlockNumber: BlockNumber | undefined;
691
1077
  if (referenceBlock) {
692
1078
  const initialBlockHash = await this.#getInitialHeaderHash();
693
- if (!referenceBlock.equals(initialBlockHash)) {
1079
+ if (referenceBlock.equals(initialBlockHash)) {
1080
+ upToBlockNumber = BlockNumber(0);
1081
+ } else {
694
1082
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
695
1083
  if (!header) {
696
1084
  throw new Error(
697
1085
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
698
1086
  );
699
1087
  }
1088
+ upToBlockNumber = header.globalVariables.blockNumber;
700
1089
  }
701
1090
  }
702
- return this.logsSource.getPrivateLogsByTags(tags, page);
1091
+ return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
703
1092
  }
704
1093
 
705
1094
  public async getPublicLogsByTagsFromContract(
@@ -708,18 +1097,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
708
1097
  page?: number,
709
1098
  referenceBlock?: BlockHash,
710
1099
  ): Promise<TxScopedL2Log[][]> {
1100
+ let upToBlockNumber: BlockNumber | undefined;
711
1101
  if (referenceBlock) {
712
1102
  const initialBlockHash = await this.#getInitialHeaderHash();
713
- if (!referenceBlock.equals(initialBlockHash)) {
1103
+ if (referenceBlock.equals(initialBlockHash)) {
1104
+ upToBlockNumber = BlockNumber(0);
1105
+ } else {
714
1106
  const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
715
1107
  if (!header) {
716
1108
  throw new Error(
717
1109
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
718
1110
  );
719
1111
  }
1112
+ upToBlockNumber = header.globalVariables.blockNumber;
720
1113
  }
721
1114
  }
722
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
1115
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
723
1116
  }
724
1117
 
725
1118
  /**
@@ -760,9 +1153,16 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
760
1153
  throw new Error(`Invalid tx: ${reason}`);
761
1154
  }
762
1155
 
763
- await this.p2pClient!.sendTx(tx);
764
- this.metrics.receivedTx(timer.ms(), true);
765
- 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 });
766
1166
  }
767
1167
 
768
1168
  public async getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
@@ -774,18 +1174,27 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
774
1174
  // Then get the actual tx from the archiver, which tracks every tx in a mined block.
775
1175
  const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
776
1176
 
1177
+ let receipt: TxReceipt;
777
1178
  if (settledTxReceipt) {
778
- // If the archiver has the receipt then return it.
779
- return settledTxReceipt;
1179
+ receipt = settledTxReceipt;
780
1180
  } else if (isKnownToPool) {
781
1181
  // If the tx is in the pool but not in the archiver, it's pending.
782
1182
  // This handles race conditions between archiver and p2p, where the archiver
783
1183
  // has pruned the block in which a tx was mined, but p2p has not caught up yet.
784
- return new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
1184
+ receipt = new TxReceipt(txHash, TxStatus.PENDING, /*executionResult=*/ undefined, /*error=*/ undefined);
785
1185
  } else {
786
1186
  // Otherwise, if we don't know the tx, we consider it dropped.
787
- return 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
+ );
788
1193
  }
1194
+
1195
+ this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
1196
+
1197
+ return receipt;
789
1198
  }
790
1199
 
791
1200
  public getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined> {
@@ -797,11 +1206,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
797
1206
  */
798
1207
  public async stop() {
799
1208
  this.log.info(`Stopping Aztec Node`);
1209
+ await tryStop(this.attestationsBlockWatcher);
800
1210
  await tryStop(this.validatorsSentinel);
801
1211
  await tryStop(this.epochPruneWatcher);
802
1212
  await tryStop(this.slasherClient);
803
- await tryStop(this.proofVerifier);
1213
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
804
1214
  await tryStop(this.sequencer);
1215
+ await tryStop(this.proverNode);
805
1216
  await tryStop(this.p2pClient);
806
1217
  await tryStop(this.worldStateSynchronizer);
807
1218
  await tryStop(this.blockSource);
@@ -855,59 +1266,65 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
855
1266
  treeId: MerkleTreeId,
856
1267
  leafValues: Fr[],
857
1268
  ): Promise<(DataInBlock<bigint> | undefined)[]> {
858
- const committedDb = await this.#getWorldState(referenceBlock);
1269
+ const committedDb = await this.getWorldState(referenceBlock);
859
1270
  const maybeIndices = await committedDb.findLeafIndices(
860
1271
  treeId,
861
1272
  leafValues.map(x => x.toBuffer()),
862
1273
  );
863
- // We filter out undefined values
864
- 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);
865
1276
 
866
- // Now we find the block numbers for the indices
867
- 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);
868
1279
 
869
- // If any of the block numbers are undefined, we throw an error.
870
- for (let i = 0; i < indices.length; i++) {
871
- if (blockNumbers[i] === undefined) {
872
- 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
+ );
873
1288
  }
1289
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
874
1290
  }
875
1291
 
876
1292
  // Get unique block numbers in order to optimize num calls to getLeafValue function.
877
- const uniqueBlockNumbers = [...new Set(blockNumbers.filter(x => x !== undefined))];
1293
+ const uniqueBlockNumbers = [...new Set(indexToBlockNumber.values())];
878
1294
 
879
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
880
- // (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).
881
1296
  const blockHashes = await Promise.all(
882
1297
  uniqueBlockNumbers.map(blockNumber => {
883
1298
  return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
884
1299
  }),
885
1300
  );
886
1301
 
887
- // 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>();
888
1304
  for (let i = 0; i < uniqueBlockNumbers.length; i++) {
889
- if (blockHashes[i] === undefined) {
1305
+ const blockHash = blockHashes[i];
1306
+ if (blockHash === undefined) {
890
1307
  throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
891
1308
  }
1309
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
892
1310
  }
893
1311
 
894
1312
  // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
895
- return maybeIndices.map((index, i) => {
1313
+ return maybeIndices.map(index => {
896
1314
  if (index === undefined) {
897
1315
  return undefined;
898
1316
  }
899
- const blockNumber = blockNumbers[i];
1317
+ const blockNumber = indexToBlockNumber.get(index);
900
1318
  if (blockNumber === undefined) {
901
- return undefined;
1319
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
902
1320
  }
903
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
904
- const blockHash = blockHashes[blockHashIndex];
905
- if (!blockHash) {
906
- return undefined;
1321
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
1322
+ if (l2BlockHash === undefined) {
1323
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
907
1324
  }
908
1325
  return {
909
- l2BlockNumber: BlockNumber(Number(blockNumber)),
910
- l2BlockHash: new BlockHash(blockHash),
1326
+ l2BlockNumber: blockNumber,
1327
+ l2BlockHash,
911
1328
  data: index,
912
1329
  };
913
1330
  });
@@ -917,7 +1334,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
917
1334
  referenceBlock: BlockParameter,
918
1335
  blockHash: BlockHash,
919
1336
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
920
- 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));
921
1346
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
922
1347
  return pathAndIndex === undefined
923
1348
  ? undefined
@@ -928,7 +1353,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
928
1353
  referenceBlock: BlockParameter,
929
1354
  noteHash: Fr,
930
1355
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
931
- const committedDb = await this.#getWorldState(referenceBlock);
1356
+ const committedDb = await this.getWorldState(referenceBlock);
932
1357
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
933
1358
  MerkleTreeId.NOTE_HASH_TREE,
934
1359
  [noteHash],
@@ -942,7 +1367,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
942
1367
  referenceBlock: BlockParameter,
943
1368
  l1ToL2Message: Fr,
944
1369
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
945
- const db = await this.#getWorldState(referenceBlock);
1370
+ const db = await this.getWorldState(referenceBlock);
946
1371
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
947
1372
  if (!witness) {
948
1373
  return undefined;
@@ -952,11 +1377,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
952
1377
  return [witness.index, witness.path];
953
1378
  }
954
1379
 
955
- public async getL1ToL2MessageBlock(l1ToL2Message: Fr): Promise<BlockNumber | undefined> {
1380
+ public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
956
1381
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
957
- return messageIndex
958
- ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex))
959
- : undefined;
1382
+ return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
960
1383
  }
961
1384
 
962
1385
  /**
@@ -977,19 +1400,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
977
1400
  public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
978
1401
  // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
979
1402
  const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
980
- const blocksInCheckpoints: L2Block[][] = [];
981
- let previousSlotNumber = SlotNumber.ZERO;
982
- let checkpointIndex = -1;
983
- for (const checkpointedBlock of checkpointedBlocks) {
984
- const block = checkpointedBlock.block;
985
- const slotNumber = block.header.globalVariables.slotNumber;
986
- if (slotNumber !== previousSlotNumber) {
987
- checkpointIndex++;
988
- blocksInCheckpoints.push([]);
989
- previousSlotNumber = slotNumber;
990
- }
991
- blocksInCheckpoints[checkpointIndex].push(block);
992
- }
1403
+ const blocksInCheckpoints = chunkBy(checkpointedBlocks, cb => cb.block.header.globalVariables.slotNumber).map(
1404
+ group => group.map(cb => cb.block),
1405
+ );
993
1406
  return blocksInCheckpoints.map(blocks =>
994
1407
  blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
995
1408
  );
@@ -999,7 +1412,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
999
1412
  referenceBlock: BlockParameter,
1000
1413
  nullifier: Fr,
1001
1414
  ): Promise<NullifierMembershipWitness | undefined> {
1002
- const db = await this.#getWorldState(referenceBlock);
1415
+ const db = await this.getWorldState(referenceBlock);
1003
1416
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
1004
1417
  if (!witness) {
1005
1418
  return undefined;
@@ -1014,33 +1427,20 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1014
1427
  return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
1015
1428
  }
1016
1429
 
1017
- /**
1018
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1019
- * @param referenceBlock - The block parameter (block number, block hash, or 'latest') at which to get the data
1020
- * (which contains the root of the nullifier tree in which we are searching for the nullifier).
1021
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1022
- * @returns The low nullifier membership witness (if found).
1023
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1024
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1025
- * we are trying to prove non-inclusion for.
1026
- *
1027
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1028
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1029
- * index of the nullifier itself when it already exists in the tree.
1030
- * TODO: This is a confusing behavior and we should eventually address that.
1031
- */
1032
1430
  public async getLowNullifierMembershipWitness(
1033
1431
  referenceBlock: BlockParameter,
1034
1432
  nullifier: Fr,
1035
1433
  ): Promise<NullifierMembershipWitness | undefined> {
1036
- const committedDb = await this.#getWorldState(referenceBlock);
1434
+ const committedDb = await this.getWorldState(referenceBlock);
1037
1435
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1038
1436
  if (!findResult) {
1039
1437
  return undefined;
1040
1438
  }
1041
1439
  const { index, alreadyPresent } = findResult;
1042
1440
  if (alreadyPresent) {
1043
- 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
+ );
1044
1444
  }
1045
1445
  const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
1046
1446
 
@@ -1049,7 +1449,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1049
1449
  }
1050
1450
 
1051
1451
  async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1052
- const committedDb = await this.#getWorldState(referenceBlock);
1452
+ const committedDb = await this.getWorldState(referenceBlock);
1053
1453
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1054
1454
  if (!lowLeafResult) {
1055
1455
  return undefined;
@@ -1064,7 +1464,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1064
1464
  }
1065
1465
 
1066
1466
  public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1067
- const committedDb = await this.#getWorldState(referenceBlock);
1467
+ const committedDb = await this.getWorldState(referenceBlock);
1068
1468
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1069
1469
 
1070
1470
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
@@ -1078,33 +1478,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1078
1478
  return preimage.leaf.value;
1079
1479
  }
1080
1480
 
1081
- public async getBlockHeader(block: BlockParameter = 'latest'): Promise<BlockHeader | undefined> {
1082
- if (BlockHash.isBlockHash(block)) {
1083
- const initialBlockHash = await this.#getInitialHeaderHash();
1084
- if (block.equals(initialBlockHash)) {
1085
- // Block source doesn't handle initial header so we need to handle the case separately.
1086
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1087
- }
1088
- return this.blockSource.getBlockHeaderByHash(block);
1089
- } else {
1090
- // Block source doesn't handle initial header so we need to handle the case separately.
1091
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
1092
- if (blockNumber === BlockNumber.ZERO) {
1093
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1094
- }
1095
- return this.blockSource.getBlockHeader(block);
1096
- }
1097
- }
1098
-
1099
- /**
1100
- * Get a block header specified by its archive root.
1101
- * @param archive - The archive root being requested.
1102
- * @returns The requested block header.
1103
- */
1104
- public async getBlockHeaderByArchive(archive: Fr): Promise<BlockHeader | undefined> {
1105
- return await this.blockSource.getBlockHeaderByArchive(archive);
1106
- }
1107
-
1108
1481
  /**
1109
1482
  * Simulates the public part of a transaction with the current state.
1110
1483
  * @param tx - The transaction to simulate.
@@ -1128,7 +1501,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1128
1501
  }
1129
1502
 
1130
1503
  const txHash = tx.getTxHash();
1131
- const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1504
+ const latestBlockNumber = await this.blockSource.getBlockNumber();
1505
+ const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1132
1506
 
1133
1507
  // If sequencer is not initialized, we just set these values to zero for simulation.
1134
1508
  const coinbase = EthAddress.ZERO;
@@ -1152,6 +1526,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1152
1526
  blockNumber,
1153
1527
  });
1154
1528
 
1529
+ // Ensure world-state has caught up with the latest block we loaded from the archiver
1530
+ await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1155
1531
  const merkleTreeFork = await this.worldStateSynchronizer.fork();
1156
1532
  try {
1157
1533
  const config = PublicSimulatorConfig.from({
@@ -1167,7 +1543,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1167
1543
  const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1168
1544
 
1169
1545
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1170
- const [processedTxs, failedTxs, _usedTxs, returns] = await processor.process([tx]);
1546
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1171
1547
  // REFACTOR: Consider returning the error rather than throwing
1172
1548
  if (failedTxs.length) {
1173
1549
  this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
@@ -1181,6 +1557,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1181
1557
  processedTx.txEffect,
1182
1558
  returns,
1183
1559
  processedTx.gasUsed,
1560
+ debugLogs,
1184
1561
  );
1185
1562
  } finally {
1186
1563
  await merkleTreeFork.close();
@@ -1192,12 +1569,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1192
1569
  { isSimulation, skipFeeEnforcement }: { isSimulation?: boolean; skipFeeEnforcement?: boolean } = {},
1193
1570
  ): Promise<TxValidationResult> {
1194
1571
  const db = this.worldStateSynchronizer.getCommitted();
1195
- const verifier = isSimulation ? undefined : this.proofVerifier;
1572
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1196
1573
 
1197
- // We accept transactions if they are not expired by the next slot (checked based on the IncludeByTimestamp field)
1574
+ // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1198
1575
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1199
1576
  const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1200
- const validator = createValidatorForAcceptingTxs(
1577
+ const l1Constants = await this.blockSource.getL1Constants();
1578
+ const validator = createTxValidatorForAcceptingTxsOverRPC(
1201
1579
  db,
1202
1580
  this.contractDataSource,
1203
1581
  verifier,
@@ -1206,10 +1584,16 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1206
1584
  blockNumber,
1207
1585
  l1ChainId: this.l1ChainId,
1208
1586
  rollupVersion: this.version,
1209
- setupAllowList: this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions()),
1587
+ setupAllowList: [
1588
+ ...(await getDefaultAllowedSetupFunctions()),
1589
+ ...(this.config.txPublicSetupAllowListExtend ?? []),
1590
+ ],
1210
1591
  gasFees: await this.getCurrentMinFees(),
1211
1592
  skipFeeEnforcement,
1212
1593
  txsPermitted: !this.config.disableTransactions,
1594
+ rollupManaLimit: l1Constants.rollupManaLimit,
1595
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1596
+ maxBlockDAGas: this.config.validateMaxDABlockGas,
1213
1597
  },
1214
1598
  this.log.getBindings(),
1215
1599
  );
@@ -1234,7 +1618,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1234
1618
  archiver.updateConfig(config);
1235
1619
  }
1236
1620
  if (newConfig.realProofs !== this.config.realProofs) {
1237
- 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
+ }
1238
1630
  }
1239
1631
 
1240
1632
  this.config = newConfig;
@@ -1309,7 +1701,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1309
1701
  return Promise.resolve();
1310
1702
  }
1311
1703
 
1312
- public async rollbackTo(targetBlock: BlockNumber, force?: boolean): Promise<void> {
1704
+ public async rollbackTo(targetBlock: BlockNumber, force?: boolean, resumeSync = true): Promise<void> {
1313
1705
  const archiver = this.blockSource as Archiver;
1314
1706
  if (!('rollbackTo' in archiver)) {
1315
1707
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1339,9 +1731,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1339
1731
  this.log.error(`Error during rollback`, err);
1340
1732
  throw err;
1341
1733
  } finally {
1342
- this.log.info(`Resuming world state and archiver sync.`);
1343
- this.worldStateSynchronizer.resumeSync();
1344
- 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
+ }
1345
1741
  }
1346
1742
  }
1347
1743
 
@@ -1358,24 +1754,139 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1358
1754
  return Promise.resolve();
1359
1755
  }
1360
1756
 
1361
- public getSlashPayloads(): Promise<SlashPayloadRound[]> {
1362
- if (!this.slasherClient) {
1363
- throw new Error(`Slasher client not enabled`);
1364
- }
1365
- return this.slasherClient.getSlashPayloads();
1366
- }
1367
-
1368
1757
  public getSlashOffenses(round: bigint | 'all' | 'current'): Promise<Offense[]> {
1369
1758
  if (!this.slasherClient) {
1370
1759
  throw new Error(`Slasher client not enabled`);
1371
1760
  }
1372
1761
  if (round === 'all') {
1373
- return this.slasherClient.getPendingOffenses();
1762
+ return this.slasherClient.getOffenses();
1374
1763
  } else {
1375
1764
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1376
1765
  }
1377
1766
  }
1378
1767
 
1768
+ public async reloadKeystore(): Promise<void> {
1769
+ if (!this.config.keyStoreDirectory?.length) {
1770
+ throw new BadRequestError(
1771
+ 'Cannot reload keystore: node is not using a file-based keystore. ' +
1772
+ 'Set KEY_STORE_DIRECTORY to use file-based keystores.',
1773
+ );
1774
+ }
1775
+ if (!this.validatorClient) {
1776
+ throw new BadRequestError('Cannot reload keystore: validator is not enabled.');
1777
+ }
1778
+
1779
+ this.log.info('Reloading keystore from disk');
1780
+
1781
+ // Re-read and validate keystore files
1782
+ const keyStores = loadKeystores(this.config.keyStoreDirectory);
1783
+ const newManager = new KeystoreManager(mergeKeystores(keyStores));
1784
+ await newManager.validateSigners();
1785
+ ValidatorClient.validateKeyStoreConfiguration(newManager, this.log);
1786
+
1787
+ // Validate that every validator's publisher keys overlap with the L1 signers
1788
+ // that were initialized at startup. Publishers cannot be hot-reloaded, so a
1789
+ // validator with a publisher key that doesn't match any existing L1 signer
1790
+ // would silently fail on every proposer slot.
1791
+ if (this.keyStoreManager && this.sequencer) {
1792
+ const oldAdapter = NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager);
1793
+ const availablePublishers = new Set(
1794
+ oldAdapter
1795
+ .getAttesterAddresses()
1796
+ .flatMap(a => oldAdapter.getPublisherAddresses(a).map(p => p.toString().toLowerCase())),
1797
+ );
1798
+
1799
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
1800
+ for (const attester of newAdapter.getAttesterAddresses()) {
1801
+ const pubs = newAdapter.getPublisherAddresses(attester);
1802
+ if (pubs.length > 0 && !pubs.some(p => availablePublishers.has(p.toString().toLowerCase()))) {
1803
+ throw new BadRequestError(
1804
+ `Cannot reload keystore: validator ${attester} has publisher keys ` +
1805
+ `[${pubs.map(p => p.toString()).join(', ')}] but none match the L1 signers initialized at startup ` +
1806
+ `[${[...availablePublishers].join(', ')}]. Publishers cannot be hot-reloaded — ` +
1807
+ `use an existing publisher key or restart the node.`,
1808
+ );
1809
+ }
1810
+ }
1811
+ }
1812
+
1813
+ // Build adapters for old and new keystores to compute diff
1814
+ const newAdapter = NodeKeystoreAdapter.fromKeyStoreManager(newManager);
1815
+ const newAddresses = newAdapter.getAttesterAddresses();
1816
+ const oldAddresses = this.keyStoreManager
1817
+ ? NodeKeystoreAdapter.fromKeyStoreManager(this.keyStoreManager).getAttesterAddresses()
1818
+ : [];
1819
+
1820
+ const oldSet = new Set(oldAddresses.map(a => a.toString()));
1821
+ const newSet = new Set(newAddresses.map(a => a.toString()));
1822
+ const added = newAddresses.filter(a => !oldSet.has(a.toString()));
1823
+ const removed = oldAddresses.filter(a => !newSet.has(a.toString()));
1824
+
1825
+ if (added.length > 0) {
1826
+ this.log.info(`Keystore reload: adding attester keys: ${added.map(a => a.toString()).join(', ')}`);
1827
+ }
1828
+ if (removed.length > 0) {
1829
+ this.log.info(`Keystore reload: removing attester keys: ${removed.map(a => a.toString()).join(', ')}`);
1830
+ }
1831
+ if (added.length === 0 && removed.length === 0) {
1832
+ this.log.info('Keystore reload: attester keys unchanged');
1833
+ }
1834
+
1835
+ // Update the validator client (coinbase, feeRecipient, attester keys)
1836
+ this.validatorClient.reloadKeystore(newManager);
1837
+
1838
+ // Update the publisher factory's keystore so newly-added validators
1839
+ // can be matched to existing publisher keys when proposing blocks.
1840
+ if (this.sequencer) {
1841
+ this.sequencer.updatePublisherNodeKeyStore(newAdapter);
1842
+ }
1843
+
1844
+ // Update slasher's "don't-slash-self" list with new validator addresses
1845
+ if (this.slasherClient && !this.config.slashSelfAllowed) {
1846
+ const slashValidatorsNever = unique(
1847
+ [...(this.config.slashValidatorsNever ?? []), ...newAddresses].map(a => a.toString()),
1848
+ ).map(EthAddress.fromString);
1849
+ this.slasherClient.updateConfig({ slashValidatorsNever });
1850
+ }
1851
+
1852
+ this.keyStoreManager = newManager;
1853
+ this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1854
+ }
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
+
1379
1890
  #getInitialHeaderHash(): Promise<BlockHash> {
1380
1891
  if (!this.initialHeaderHashPromise) {
1381
1892
  this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
@@ -1388,7 +1899,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1388
1899
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1389
1900
  * @returns An instance of a committed MerkleTreeOperations
1390
1901
  */
1391
- async #getWorldState(block: BlockParameter) {
1902
+ protected async getWorldState(block: BlockParameter) {
1392
1903
  let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1393
1904
  try {
1394
1905
  // Attempt to sync the world state if necessary
@@ -1402,35 +1913,77 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1402
1913
  return this.worldStateSynchronizer.getCommitted();
1403
1914
  }
1404
1915
 
1916
+ // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1917
+ let blockNumber: BlockNumber;
1405
1918
  if (BlockHash.isBlockHash(block)) {
1406
1919
  const initialBlockHash = await this.#getInitialHeaderHash();
1407
1920
  if (block.equals(initialBlockHash)) {
1408
- // Block source doesn't handle initial header so we need to handle the case separately.
1409
- 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();
1410
1933
  }
1934
+ } else {
1935
+ blockNumber = block as BlockNumber;
1936
+ }
1411
1937
 
1412
- const header = await this.blockSource.getBlockHeaderByHash(block);
1413
- 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();
1414
1953
  throw new Error(
1415
- `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.`,
1416
1955
  );
1417
1956
  }
1418
- const blockNumber = header.getBlockNumber();
1419
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1420
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1421
1957
  }
1422
1958
 
1423
- // Block number provided
1424
- {
1425
- const blockNumber = block as BlockNumber;
1959
+ return snapshot;
1960
+ }
1426
1961
 
1427
- if (blockNumber > blockSyncedTo) {
1428
- 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;
1429
1972
  }
1430
-
1431
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1432
- 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();
1433
1985
  }
1986
+ throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(block)}`);
1434
1987
  }
1435
1988
 
1436
1989
  /**