@aztec/aztec-node 0.0.1-commit.29c6b1a3 → 0.0.1-commit.2c0ee1788

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,36 +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';
4
- import {
5
- ARCHIVE_HEIGHT,
6
- type L1_TO_L2_MSG_TREE_HEIGHT,
7
- type NOTE_HASH_TREE_HEIGHT,
8
- type NULLIFIER_TREE_HEIGHT,
9
- type PUBLIC_DATA_TREE_HEIGHT,
10
- } from '@aztec/constants';
5
+ import { Blob } from '@aztec/blob-lib';
6
+ import { ARCHIVE_HEIGHT, type L1_TO_L2_MSG_TREE_HEIGHT, type NOTE_HASH_TREE_HEIGHT } from '@aztec/constants';
11
7
  import { EpochCache, type EpochCacheInterface } from '@aztec/epoch-cache';
12
8
  import { createEthereumChain } from '@aztec/ethereum/chain';
13
- import { getPublicClient } from '@aztec/ethereum/client';
9
+ import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
14
10
  import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
15
11
  import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
12
+ import type { L1TxUtils } from '@aztec/ethereum/l1-tx-utils';
16
13
  import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
17
- import { compactArray, pick } from '@aztec/foundation/collection';
14
+ import { chunkBy, compactArray, pick, unique } from '@aztec/foundation/collection';
18
15
  import { Fr } from '@aztec/foundation/curves/bn254';
19
16
  import { EthAddress } from '@aztec/foundation/eth-address';
20
17
  import { BadRequestError } from '@aztec/foundation/json-rpc';
21
18
  import { type Logger, createLogger } from '@aztec/foundation/log';
19
+ import { retryUntil } from '@aztec/foundation/retry';
22
20
  import { count } from '@aztec/foundation/string';
23
21
  import { DateProvider, Timer } from '@aztec/foundation/timer';
24
22
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
25
- import { KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
23
+ import { type KeyStore, KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
26
24
  import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
25
+ import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
27
26
  import {
28
- createForwarderL1TxUtilsFromEthSigner,
29
- createL1TxUtilsWithBlobsFromEthSigner,
30
- } from '@aztec/node-lib/factories';
31
- 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';
32
33
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
33
- 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';
34
42
  import { PublicProcessorFactory } from '@aztec/simulator/server';
35
43
  import {
36
44
  AttestationsBlockWatcher,
@@ -41,8 +49,14 @@ import {
41
49
  } from '@aztec/slasher';
42
50
  import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
43
51
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
44
- import { BlockHash, type BlockParameter, type DataInBlock, L2Block, type L2BlockSource } from '@aztec/stdlib/block';
45
- 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';
46
60
  import type {
47
61
  ContractClassPublic,
48
62
  ContractDataSource,
@@ -50,16 +64,24 @@ import type {
50
64
  NodeInfo,
51
65
  ProtocolContractAddresses,
52
66
  } from '@aztec/stdlib/contract';
53
- import { GasFees } from '@aztec/stdlib/gas';
67
+ import { GasFees, type ManaUsageEstimate } from '@aztec/stdlib/gas';
54
68
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
55
- import {
56
- type AztecNode,
57
- type AztecNodeAdmin,
58
- type AztecNodeAdminConfig,
59
- AztecNodeAdminConfigSchema,
60
- type GetContractClassLogsResponse,
61
- 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,
62
83
  } from '@aztec/stdlib/interfaces/client';
84
+ import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
63
85
  import {
64
86
  type AllowedElement,
65
87
  type ClientProtocolCircuitVerifier,
@@ -69,14 +91,15 @@ import {
69
91
  type WorldStateSynchronizer,
70
92
  tryStop,
71
93
  } from '@aztec/stdlib/interfaces/server';
72
- 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';
73
96
  import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
74
- import { P2PClientType } from '@aztec/stdlib/p2p';
75
- import type { Offense, SlashPayloadRound } from '@aztec/stdlib/slashing';
76
- 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';
77
99
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
78
100
  import {
79
101
  type BlockHeader,
102
+ type FeeProvider,
80
103
  type GlobalVariableBuilder as GlobalVariableBuilderInterface,
81
104
  type IndexedTxEffect,
82
105
  PublicSimulationOutput,
@@ -88,6 +111,7 @@ import {
88
111
  } from '@aztec/stdlib/tx';
89
112
  import { getPackageVersion } from '@aztec/stdlib/update-checker';
90
113
  import type { SingleValidatorStats, ValidatorsStats } from '@aztec/stdlib/validators';
114
+ import type { GenesisData } from '@aztec/stdlib/world-state';
91
115
  import {
92
116
  Attributes,
93
117
  type TelemetryClient,
@@ -101,23 +125,29 @@ import {
101
125
  FullNodeCheckpointsBuilder,
102
126
  NodeKeystoreAdapter,
103
127
  ValidatorClient,
104
- createBlockProposalHandler,
128
+ createProposalHandler,
105
129
  createValidatorClient,
106
- createValidatorForAcceptingTxs,
107
130
  } from '@aztec/validator-client';
131
+ import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
108
132
  import { createWorldStateSynchronizer } from '@aztec/world-state';
109
133
 
110
- import { createPublicClient, fallback, http } from 'viem';
134
+ import { createPublicClient } from 'viem';
111
135
 
112
136
  import { createSentinel } from '../sentinel/factory.js';
113
137
  import { Sentinel } from '../sentinel/sentinel.js';
138
+ import {
139
+ blockResponseFromBlockData,
140
+ blockResponseFromL2Block,
141
+ checkpointResponseFromCheckpointData,
142
+ checkpointResponseFromPublishedCheckpoint,
143
+ } from './block_response_helpers.js';
114
144
  import { type AztecNodeConfig, createKeyStoreForValidator } from './config.js';
115
145
  import { NodeMetrics } from './node_metrics.js';
116
146
 
117
147
  /**
118
148
  * The aztec node.
119
149
  */
120
- export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
150
+ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDebug, Traceable {
121
151
  private metrics: NodeMetrics;
122
152
  private initialHeaderHashPromise: Promise<BlockHash> | undefined = undefined;
123
153
 
@@ -135,24 +165,43 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
135
165
  protected readonly l1ToL2MessageSource: L1ToL2MessageSource,
136
166
  protected readonly worldStateSynchronizer: WorldStateSynchronizer,
137
167
  protected readonly sequencer: SequencerClient | undefined,
168
+ protected readonly proverNode: ProverNode | undefined,
138
169
  protected readonly slasherClient: SlasherClientInterface | undefined,
139
170
  protected readonly validatorsSentinel: Sentinel | undefined,
140
171
  protected readonly epochPruneWatcher: EpochPruneWatcher | undefined,
172
+ protected readonly attestationsBlockWatcher: AttestationsBlockWatcher | undefined,
141
173
  protected readonly l1ChainId: number,
142
174
  protected readonly version: number,
143
175
  protected readonly globalVariableBuilder: GlobalVariableBuilderInterface,
176
+ protected readonly feeProvider: FeeProvider,
144
177
  protected readonly epochCache: EpochCacheInterface,
145
178
  protected readonly packageVersion: string,
146
- private proofVerifier: ClientProtocolCircuitVerifier,
179
+ private peerProofVerifier: ClientProtocolCircuitVerifier,
180
+ private rpcProofVerifier: ClientProtocolCircuitVerifier,
147
181
  private telemetry: TelemetryClient = getTelemetryClient(),
148
182
  private log = createLogger('node'),
149
183
  private blobClient?: BlobClientInterface,
184
+ private validatorClient?: ValidatorClient,
185
+ private keyStoreManager?: KeystoreManager,
186
+ private debugLogStore: DebugLogStore = new NullDebugLogStore(),
150
187
  ) {
151
188
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
152
189
  this.tracer = telemetry.getTracer('AztecNodeService');
153
190
 
154
191
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
155
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;
156
205
  }
157
206
 
158
207
  public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
@@ -160,10 +209,281 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
160
209
  return status.syncSummary;
161
210
  }
162
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
+
163
217
  public getL2Tips() {
164
218
  return this.blockSource.getL2Tips();
165
219
  }
166
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
+
167
487
  /**
168
488
  * initializes the Aztec Node, wait for component to sync.
169
489
  * @param config - The configuration to be used by the aztec node.
@@ -176,11 +496,14 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
176
496
  logger?: Logger;
177
497
  publisher?: SequencerPublisher;
178
498
  dateProvider?: DateProvider;
179
- p2pClientDeps?: P2PClientDeps<P2PClientType.Full>;
499
+ p2pClientDeps?: P2PClientDeps;
500
+ proverNodeDeps?: Partial<ProverNodeDeps>;
501
+ slashingProtectionDb?: SlashingProtectionDatabase;
180
502
  } = {},
181
503
  options: {
182
- prefilledPublicData?: PublicDataTreeLeaf[];
504
+ genesis?: GenesisData;
183
505
  dontStartSequencer?: boolean;
506
+ dontStartProverNode?: boolean;
184
507
  } = {},
185
508
  ): Promise<AztecNodeService> {
186
509
  const config = { ...inputConfig }; // Copy the config so we dont mutate the input object
@@ -190,16 +513,29 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
190
513
  const dateProvider = deps.dateProvider ?? new DateProvider();
191
514
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
192
515
 
193
- // 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.
194
518
  let keyStoreManager: KeystoreManager | undefined;
195
519
  const keyStoreProvided = config.keyStoreDirectory !== undefined && config.keyStoreDirectory.length > 0;
196
520
  if (keyStoreProvided) {
197
521
  const keyStores = loadKeystores(config.keyStoreDirectory!);
198
522
  keyStoreManager = new KeystoreManager(mergeKeystores(keyStores));
199
523
  } else {
200
- const keyStore = createKeyStoreForValidator(config);
201
- if (keyStore) {
202
- 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
+ );
203
539
  }
204
540
  }
205
541
 
@@ -210,10 +546,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
210
546
  if (keyStoreManager === undefined) {
211
547
  throw new Error('Failed to create key store, a requirement for running a validator');
212
548
  }
213
- if (!keyStoreProvided) {
214
- log.warn(
215
- 'KEY STORE CREATED FROM ENVIRONMENT, IT IS RECOMMENDED TO USE A FILE-BASED KEY STORE IN PRODUCTION ENVIRONMENTS',
216
- );
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");
217
551
  }
218
552
  ValidatorClient.validateKeyStoreConfiguration(keyStoreManager, log);
219
553
  }
@@ -227,7 +561,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
227
561
 
228
562
  const publicClient = createPublicClient({
229
563
  chain: ethereumChain.chainInfo,
230
- transport: fallback(config.l1RpcUrls.map((url: string) => http(url, { batch: false }))),
564
+ transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
231
565
  pollingInterval: config.viemPollingIntervalMS,
232
566
  });
233
567
 
@@ -241,10 +575,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
241
575
  config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
242
576
 
243
577
  const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
244
- const [l1GenesisTime, slotDuration, rollupVersionFromRollup] = await Promise.all([
578
+ const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
245
579
  rollupContract.getL1GenesisTime(),
246
580
  rollupContract.getSlotDuration(),
247
581
  rollupContract.getVersion(),
582
+ rollupContract.getManaLimit().then(Number),
248
583
  ] as const);
249
584
 
250
585
  config.rollupVersion ??= Number(rollupVersionFromRollup);
@@ -255,247 +590,361 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
255
590
  );
256
591
  }
257
592
 
258
- const blobClient = await createBlobClientWithFileStores(config, createLogger('node:blob-client:client'));
593
+ const blobClient = await createBlobClientWithFileStores(config, log.createChild('blob-client'));
259
594
 
260
595
  // attempt snapshot sync if possible
261
596
  await trySnapshotSync(config, log);
262
597
 
263
598
  const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, { dateProvider });
264
599
 
265
- const archiver = await createArchiver(
266
- config,
267
- { blobClient, epochCache, telemetry, dateProvider },
268
- { blockUntilSync: !config.skipArchiverInitialSync },
269
- );
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);
270
625
 
271
- // now create the merkle trees and the world state synchronizer
272
- const worldStateSynchronizer = await createWorldStateSynchronizer(
273
- config,
274
- archiver,
275
- options.prefilledPublicData,
276
- telemetry,
277
- );
278
- const circuitVerifier =
279
- config.realProofs || config.debugForceTxProofVerification
280
- ? await BBCircuitVerifier.new(config)
281
- : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
282
- if (!config.realProofs) {
283
- log.warn(`Aztec node is accepting fake proofs`);
284
- }
285
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
286
-
287
- // create the tx pool and the p2p client, which will need the l2 block source
288
- const p2pClient = await createP2PClient(
289
- P2PClientType.Full,
290
- config,
291
- archiver,
292
- proofVerifier,
293
- worldStateSynchronizer,
294
- epochCache,
295
- packageVersion,
296
- dateProvider,
297
- telemetry,
298
- deps.p2pClientDeps,
299
- );
626
+ let debugLogStore: DebugLogStore;
627
+ if (!config.realProofs) {
628
+ log.warn(`Aztec node is accepting fake proofs`);
300
629
 
301
- // We should really not be modifying the config object
302
- 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
+ }
303
637
 
304
- // Create FullNodeCheckpointsBuilder for validator and non-validator block proposal handling
305
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
306
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
307
- worldStateSynchronizer,
308
- archiver,
309
- dateProvider,
310
- telemetry,
311
- );
638
+ const globalVariableBuilderConfig = {
639
+ l1Contracts: config.l1Contracts,
640
+ ethereumSlotDuration: config.ethereumSlotDuration,
641
+ rollupVersion: BigInt(config.rollupVersion),
642
+ l1GenesisTime,
643
+ slotDuration: Number(slotDuration),
644
+ };
312
645
 
313
- // We'll accumulate sentinel watchers here
314
- const watchers: Watcher[] = [];
315
-
316
- // Create validator client if required
317
- const validatorClient = await createValidatorClient(config, {
318
- checkpointsBuilder: validatorCheckpointsBuilder,
319
- worldState: worldStateSynchronizer,
320
- p2pClient,
321
- telemetry,
322
- dateProvider,
323
- epochCache,
324
- blockSource: archiver,
325
- l1ToL2MessageSource: archiver,
326
- keyStoreManager,
327
- blobClient,
328
- });
646
+ const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, globalVariableBuilderConfig);
647
+ const feeProvider = new FeeProviderImpl(dateProvider, publicClient, globalVariableBuilderConfig);
329
648
 
330
- // If we have a validator client, register it as a source of offenses for the slasher,
331
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
332
- // like attestations or auths will fail.
333
- if (validatorClient) {
334
- watchers.push(validatorClient);
335
- if (!options.dontStartSequencer) {
336
- 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');
337
652
  }
338
- }
339
653
 
340
- // If there's no validator client but alwaysReexecuteBlockProposals is enabled,
341
- // create a BlockProposalHandler to reexecute block proposals for monitoring
342
- if (!validatorClient && config.alwaysReexecuteBlockProposals) {
343
- log.info('Setting up block proposal reexecution for monitoring');
344
- createBlockProposalHandler(config, {
345
- checkpointsBuilder: validatorCheckpointsBuilder,
346
- 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,
347
660
  epochCache,
348
- blockSource: archiver,
349
- l1ToL2MessageSource: archiver,
350
- p2pClient,
661
+ feeProvider,
662
+ packageVersion,
351
663
  dateProvider,
352
664
  telemetry,
353
- }).registerForReexecution(p2pClient);
354
- }
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
+ );
355
687
 
356
- // Start world state and wait for it to sync to the archiver.
357
- 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
+ }
358
721
 
359
- // Start p2p. Note that it depends on world state to be running.
360
- 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
+ }
361
741
 
362
- const validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
363
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
364
- watchers.push(validatorsSentinel);
365
- }
742
+ // Start world state and wait for it to sync to the archiver.
743
+ await worldStateSynchronizer.start();
366
744
 
367
- let epochPruneWatcher: EpochPruneWatcher | undefined;
368
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
369
- epochPruneWatcher = new EpochPruneWatcher(
370
- archiver,
371
- archiver,
372
- epochCache,
373
- p2pClient.getTxProvider(),
374
- validatorCheckpointsBuilder,
375
- config,
376
- );
377
- watchers.push(epochPruneWatcher);
378
- }
745
+ // Start p2p. Note that it depends on world state to be running.
746
+ await p2pClient.start();
379
747
 
380
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
381
- let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
382
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
383
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
384
- watchers.push(attestationsBlockWatcher);
385
- }
748
+ let validatorsSentinel: Awaited<ReturnType<typeof createSentinel>> | undefined;
749
+ let epochPruneWatcher: EpochPruneWatcher | undefined;
750
+ let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
386
751
 
387
- // Start p2p-related services once the archiver has completed sync
388
- void archiver
389
- .waitForInitialSync()
390
- .then(async () => {
391
- await p2pClient.start();
392
- await validatorsSentinel?.start();
393
- await epochPruneWatcher?.start();
394
- await attestationsBlockWatcher?.start();
395
- log.info(`All p2p services started`);
396
- })
397
- .catch(err => log.error('Failed to start p2p services after archiver sync', err));
398
-
399
- // Validator enabled, create/start relevant service
400
- let sequencer: SequencerClient | undefined;
401
- let slasherClient: SlasherClientInterface | undefined;
402
- if (!config.disableValidator && validatorClient) {
403
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
404
- // as they are executed when the node is selected as proposer.
405
- const validatorAddresses = keyStoreManager
406
- ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses()
407
- : [];
408
-
409
- slasherClient = await createSlasher(
410
- config,
411
- config.l1Contracts,
412
- getPublicClient(config),
413
- watchers,
414
- dateProvider,
415
- epochCache,
416
- validatorAddresses,
417
- undefined, // logger
418
- );
419
- 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
+ }
420
757
 
421
- const l1TxUtils = config.publisherForwarderAddress
422
- ? await createForwarderL1TxUtilsFromEthSigner(
423
- publicClient,
424
- keyStoreManager!.createAllValidatorPublisherSigners(),
425
- config.publisherForwarderAddress,
426
- { ...config, scope: 'sequencer' },
427
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider },
428
- )
429
- : await createL1TxUtilsWithBlobsFromEthSigner(
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(
430
840
  publicClient,
431
- keyStoreManager!.createAllValidatorPublisherSigners(),
841
+ [fundingSigner],
432
842
  { ...config, scope: 'sequencer' },
433
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider },
843
+ { telemetry, logger: log.createChild('l1-tx-utils:funder'), dateProvider },
434
844
  );
845
+ funderL1TxUtils = funder;
846
+ }
435
847
 
436
- // Create and start the sequencer client
437
- const checkpointsBuilder = new CheckpointsBuilder(
438
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration) },
439
- worldStateSynchronizer,
440
- archiver,
441
- dateProvider,
442
- telemetry,
443
- );
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
+ );
444
857
 
445
- sequencer = await SequencerClient.new(config, {
446
- ...deps,
447
- epochCache,
448
- l1TxUtils,
449
- 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,
450
912
  p2pClient,
913
+ archiver,
914
+ archiver,
915
+ archiver,
916
+ archiver,
451
917
  worldStateSynchronizer,
918
+ sequencer,
919
+ proverNode,
452
920
  slasherClient,
453
- checkpointsBuilder,
454
- l2BlockSource: archiver,
455
- 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,
456
932
  telemetry,
457
- dateProvider,
933
+ log,
458
934
  blobClient,
459
- nodeKeyStore: keyStoreManager!,
460
- });
461
- }
935
+ validatorClient,
936
+ keyStoreManager,
937
+ debugLogStore,
938
+ );
462
939
 
463
- if (!options.dontStartSequencer && sequencer) {
464
- await sequencer.start();
465
- log.verbose(`Sequencer started`);
466
- } else if (sequencer) {
467
- 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;
468
947
  }
469
-
470
- const globalVariableBuilder = new GlobalVariableBuilder({
471
- ...config,
472
- rollupVersion: BigInt(config.rollupVersion),
473
- l1GenesisTime,
474
- slotDuration: Number(slotDuration),
475
- });
476
-
477
- return new AztecNodeService(
478
- config,
479
- p2pClient,
480
- archiver,
481
- archiver,
482
- archiver,
483
- archiver,
484
- worldStateSynchronizer,
485
- sequencer,
486
- slasherClient,
487
- validatorsSentinel,
488
- epochPruneWatcher,
489
- ethereumChain.chainInfo.id,
490
- config.rollupVersion,
491
- globalVariableBuilder,
492
- epochCache,
493
- packageVersion,
494
- proofVerifier,
495
- telemetry,
496
- log,
497
- blobClient,
498
- );
499
948
  }
500
949
 
501
950
  /**
@@ -506,6 +955,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
506
955
  return this.sequencer;
507
956
  }
508
957
 
958
+ /** Returns the prover node subsystem, if enabled. */
959
+ public getProverNode(): ProverNode | undefined {
960
+ return this.proverNode;
961
+ }
962
+
509
963
  public getBlockSource(): L2BlockSource {
510
964
  return this.blockSource;
511
965
  }
@@ -531,7 +985,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
531
985
  }
532
986
 
533
987
  public async getAllowedPublicSetup(): Promise<AllowedElement[]> {
534
- return this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
988
+ return [...(await getDefaultAllowedSetupFunctions()), ...(this.config.txPublicSetupAllowListExtend ?? [])];
535
989
  }
536
990
 
537
991
  /**
@@ -559,78 +1013,19 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
559
1013
  enr,
560
1014
  l1ContractAddresses: contractAddresses,
561
1015
  protocolContractAddresses: protocolContractAddresses,
1016
+ realProofs: !!this.config.realProofs,
562
1017
  };
563
1018
 
564
1019
  return nodeInfo;
565
1020
  }
566
1021
 
567
- /**
568
- * Get a block specified by its block number, block hash, or 'latest'.
569
- * @param block - The block parameter (block number, block hash, or 'latest').
570
- * @returns The requested block.
571
- */
572
- public async getBlock(block: BlockParameter): Promise<L2Block | undefined> {
573
- if (BlockHash.isL2BlockHash(block)) {
574
- return this.getBlockByHash(Fr.fromBuffer(block.toBuffer()));
575
- }
576
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
577
- if (blockNumber === BlockNumber.ZERO) {
578
- return this.buildInitialBlock();
579
- }
580
- return await this.blockSource.getL2Block(blockNumber);
581
- }
582
-
583
- /**
584
- * Get a block specified by its hash.
585
- * @param blockHash - The block hash being requested.
586
- * @returns The requested block.
587
- */
588
- public async getBlockByHash(blockHash: Fr): Promise<L2Block | undefined> {
589
- const initialBlockHash = await this.#getInitialHeaderHash();
590
- if (blockHash.equals(Fr.fromBuffer(initialBlockHash.toBuffer()))) {
591
- return this.buildInitialBlock();
592
- }
593
- return await this.blockSource.getL2BlockByHash(blockHash);
594
- }
595
-
596
- private buildInitialBlock(): L2Block {
597
- const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
598
- return L2Block.empty(initialHeader);
599
- }
600
-
601
- /**
602
- * Get a block specified by its archive root.
603
- * @param archive - The archive root being requested.
604
- * @returns The requested block.
605
- */
606
- public async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
607
- return await this.blockSource.getL2BlockByArchive(archive);
608
- }
609
-
610
- /**
611
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
612
- * @param from - The start of the range of blocks to return.
613
- * @param limit - The maximum number of blocks to obtain.
614
- * @returns The blocks requested.
615
- */
616
- public async getBlocks(from: BlockNumber, limit: number): Promise<L2Block[]> {
617
- return (await this.blockSource.getBlocks(from, BlockNumber(limit))) ?? [];
618
- }
619
-
620
- public async getCheckpoints(from: CheckpointNumber, limit: number): Promise<PublishedCheckpoint[]> {
621
- return (await this.blockSource.getCheckpoints(from, limit)) ?? [];
622
- }
623
-
624
- public async getCheckpointedBlocks(from: BlockNumber, limit: number) {
625
- return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
1022
+ public async getCurrentMinFees(): Promise<GasFees> {
1023
+ return await this.feeProvider.getCurrentMinFees();
626
1024
  }
627
1025
 
628
- /**
629
- * Method to fetch the current min L2 fees.
630
- * @returns The current min L2 fees.
631
- */
632
- public async getCurrentMinFees(): Promise<GasFees> {
633
- 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);
634
1029
  }
635
1030
 
636
1031
  public async getMaxPriorityFees(): Promise<GasFees> {
@@ -641,22 +1036,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
641
1036
  return GasFees.from({ feePerDaGas: 0n, feePerL2Gas: 0n });
642
1037
  }
643
1038
 
644
- /**
645
- * Method to fetch the latest block number synchronized by the node.
646
- * @returns The block number.
647
- */
648
- public async getBlockNumber(): Promise<BlockNumber> {
649
- return await this.blockSource.getBlockNumber();
650
- }
651
-
652
- public async getProvenBlockNumber(): Promise<BlockNumber> {
653
- return await this.blockSource.getProvenBlockNumber();
654
- }
655
-
656
- public async getCheckpointedBlockNumber(): Promise<BlockNumber> {
657
- return await this.blockSource.getCheckpointedL2BlockNumber();
658
- }
659
-
660
1039
  /**
661
1040
  * Method to fetch the version of the package.
662
1041
  * @returns The node package version
@@ -694,19 +1073,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
694
1073
  page?: number,
695
1074
  referenceBlock?: BlockHash,
696
1075
  ): Promise<TxScopedL2Log[][]> {
1076
+ let upToBlockNumber: BlockNumber | undefined;
697
1077
  if (referenceBlock) {
698
1078
  const initialBlockHash = await this.#getInitialHeaderHash();
699
- if (!referenceBlock.equals(initialBlockHash)) {
700
- const blockHashFr = Fr.fromBuffer(referenceBlock.toBuffer());
701
- const header = await this.blockSource.getBlockHeaderByHash(blockHashFr);
1079
+ if (referenceBlock.equals(initialBlockHash)) {
1080
+ upToBlockNumber = BlockNumber(0);
1081
+ } else {
1082
+ const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
702
1083
  if (!header) {
703
1084
  throw new Error(
704
1085
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
705
1086
  );
706
1087
  }
1088
+ upToBlockNumber = header.globalVariables.blockNumber;
707
1089
  }
708
1090
  }
709
- return this.logsSource.getPrivateLogsByTags(tags, page);
1091
+ return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
710
1092
  }
711
1093
 
712
1094
  public async getPublicLogsByTagsFromContract(
@@ -715,19 +1097,22 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
715
1097
  page?: number,
716
1098
  referenceBlock?: BlockHash,
717
1099
  ): Promise<TxScopedL2Log[][]> {
1100
+ let upToBlockNumber: BlockNumber | undefined;
718
1101
  if (referenceBlock) {
719
1102
  const initialBlockHash = await this.#getInitialHeaderHash();
720
- if (!referenceBlock.equals(initialBlockHash)) {
721
- const blockHashFr = Fr.fromBuffer(referenceBlock.toBuffer());
722
- const header = await this.blockSource.getBlockHeaderByHash(blockHashFr);
1103
+ if (referenceBlock.equals(initialBlockHash)) {
1104
+ upToBlockNumber = BlockNumber(0);
1105
+ } else {
1106
+ const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
723
1107
  if (!header) {
724
1108
  throw new Error(
725
1109
  `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
726
1110
  );
727
1111
  }
1112
+ upToBlockNumber = header.globalVariables.blockNumber;
728
1113
  }
729
1114
  }
730
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page);
1115
+ return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
731
1116
  }
732
1117
 
733
1118
  /**
@@ -768,9 +1153,16 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
768
1153
  throw new Error(`Invalid tx: ${reason}`);
769
1154
  }
770
1155
 
771
- await this.p2pClient!.sendTx(tx);
772
- this.metrics.receivedTx(timer.ms(), true);
773
- 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 });
774
1166
  }
775
1167
 
776
1168
  public async getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
@@ -782,18 +1174,27 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
782
1174
  // Then get the actual tx from the archiver, which tracks every tx in a mined block.
783
1175
  const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
784
1176
 
1177
+ let receipt: TxReceipt;
785
1178
  if (settledTxReceipt) {
786
- // If the archiver has the receipt then return it.
787
- return settledTxReceipt;
1179
+ receipt = settledTxReceipt;
788
1180
  } else if (isKnownToPool) {
789
1181
  // If the tx is in the pool but not in the archiver, it's pending.
790
1182
  // This handles race conditions between archiver and p2p, where the archiver
791
1183
  // has pruned the block in which a tx was mined, but p2p has not caught up yet.
792
- return new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
1184
+ receipt = new TxReceipt(txHash, TxStatus.PENDING, /*executionResult=*/ undefined, /*error=*/ undefined);
793
1185
  } else {
794
1186
  // Otherwise, if we don't know the tx, we consider it dropped.
795
- return new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
1187
+ receipt = new TxReceipt(
1188
+ txHash,
1189
+ TxStatus.DROPPED,
1190
+ /*executionResult=*/ undefined,
1191
+ /*error=*/ 'Tx dropped by P2P node',
1192
+ );
796
1193
  }
1194
+
1195
+ this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
1196
+
1197
+ return receipt;
797
1198
  }
798
1199
 
799
1200
  public getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined> {
@@ -805,11 +1206,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
805
1206
  */
806
1207
  public async stop() {
807
1208
  this.log.info(`Stopping Aztec Node`);
1209
+ await tryStop(this.attestationsBlockWatcher);
808
1210
  await tryStop(this.validatorsSentinel);
809
1211
  await tryStop(this.epochPruneWatcher);
810
1212
  await tryStop(this.slasherClient);
811
- await tryStop(this.proofVerifier);
1213
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
812
1214
  await tryStop(this.sequencer);
1215
+ await tryStop(this.proverNode);
813
1216
  await tryStop(this.p2pClient);
814
1217
  await tryStop(this.worldStateSynchronizer);
815
1218
  await tryStop(this.blockSource);
@@ -859,100 +1262,98 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
859
1262
  }
860
1263
 
861
1264
  public async findLeavesIndexes(
862
- block: BlockParameter,
1265
+ referenceBlock: BlockParameter,
863
1266
  treeId: MerkleTreeId,
864
1267
  leafValues: Fr[],
865
1268
  ): Promise<(DataInBlock<bigint> | undefined)[]> {
866
- const committedDb = await this.#getWorldState(block);
1269
+ const committedDb = await this.getWorldState(referenceBlock);
867
1270
  const maybeIndices = await committedDb.findLeafIndices(
868
1271
  treeId,
869
1272
  leafValues.map(x => x.toBuffer()),
870
1273
  );
871
- // We filter out undefined values
872
- 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);
873
1276
 
874
- // Now we find the block numbers for the indices
875
- 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);
876
1279
 
877
- // If any of the block numbers are undefined, we throw an error.
878
- for (let i = 0; i < indices.length; i++) {
879
- if (blockNumbers[i] === undefined) {
880
- 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
+ );
881
1288
  }
1289
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
882
1290
  }
883
1291
 
884
1292
  // Get unique block numbers in order to optimize num calls to getLeafValue function.
885
- const uniqueBlockNumbers = [...new Set(blockNumbers.filter(x => x !== undefined))];
1293
+ const uniqueBlockNumbers = [...new Set(indexToBlockNumber.values())];
886
1294
 
887
- // Now we obtain the block hashes from the archive tree by calling await `committedDb.getLeafValue(treeId, index)`
888
- // (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).
889
1296
  const blockHashes = await Promise.all(
890
1297
  uniqueBlockNumbers.map(blockNumber => {
891
1298
  return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
892
1299
  }),
893
1300
  );
894
1301
 
895
- // 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>();
896
1304
  for (let i = 0; i < uniqueBlockNumbers.length; i++) {
897
- if (blockHashes[i] === undefined) {
1305
+ const blockHash = blockHashes[i];
1306
+ if (blockHash === undefined) {
898
1307
  throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
899
1308
  }
1309
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
900
1310
  }
901
1311
 
902
1312
  // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
903
- return maybeIndices.map((index, i) => {
1313
+ return maybeIndices.map(index => {
904
1314
  if (index === undefined) {
905
1315
  return undefined;
906
1316
  }
907
- const blockNumber = blockNumbers[i];
1317
+ const blockNumber = indexToBlockNumber.get(index);
908
1318
  if (blockNumber === undefined) {
909
- return undefined;
1319
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
910
1320
  }
911
- const blockHashIndex = uniqueBlockNumbers.indexOf(blockNumber);
912
- const blockHash = blockHashes[blockHashIndex];
913
- if (!blockHash) {
914
- return undefined;
1321
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
1322
+ if (l2BlockHash === undefined) {
1323
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
915
1324
  }
916
1325
  return {
917
- l2BlockNumber: BlockNumber(Number(blockNumber)),
918
- l2BlockHash: BlockHash.fromField(blockHash),
1326
+ l2BlockNumber: blockNumber,
1327
+ l2BlockHash,
919
1328
  data: index,
920
1329
  };
921
1330
  });
922
1331
  }
923
1332
 
924
- public async getNullifierSiblingPath(
925
- block: BlockParameter,
926
- leafIndex: bigint,
927
- ): Promise<SiblingPath<typeof NULLIFIER_TREE_HEIGHT>> {
928
- const committedDb = await this.#getWorldState(block);
929
- return committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, leafIndex);
930
- }
931
-
932
- public async getNoteHashSiblingPath(
933
- block: BlockParameter,
934
- leafIndex: bigint,
935
- ): Promise<SiblingPath<typeof NOTE_HASH_TREE_HEIGHT>> {
936
- const committedDb = await this.#getWorldState(block);
937
- return committedDb.getSiblingPath(MerkleTreeId.NOTE_HASH_TREE, leafIndex);
938
- }
939
-
940
- public async getArchiveMembershipWitness(
941
- block: BlockParameter,
942
- archive: Fr,
1333
+ public async getBlockHashMembershipWitness(
1334
+ referenceBlock: BlockParameter,
1335
+ blockHash: BlockHash,
943
1336
  ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
944
- const committedDb = await this.#getWorldState(block);
945
- const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [archive]);
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));
1346
+ const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
946
1347
  return pathAndIndex === undefined
947
1348
  ? undefined
948
1349
  : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
949
1350
  }
950
1351
 
951
1352
  public async getNoteHashMembershipWitness(
952
- block: BlockParameter,
1353
+ referenceBlock: BlockParameter,
953
1354
  noteHash: Fr,
954
1355
  ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
955
- const committedDb = await this.#getWorldState(block);
1356
+ const committedDb = await this.getWorldState(referenceBlock);
956
1357
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
957
1358
  MerkleTreeId.NOTE_HASH_TREE,
958
1359
  [noteHash],
@@ -963,10 +1364,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
963
1364
  }
964
1365
 
965
1366
  public async getL1ToL2MessageMembershipWitness(
966
- block: BlockParameter,
1367
+ referenceBlock: BlockParameter,
967
1368
  l1ToL2Message: Fr,
968
1369
  ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
969
- const db = await this.#getWorldState(block);
1370
+ const db = await this.getWorldState(referenceBlock);
970
1371
  const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
971
1372
  if (!witness) {
972
1373
  return undefined;
@@ -976,11 +1377,9 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
976
1377
  return [witness.index, witness.path];
977
1378
  }
978
1379
 
979
- public async getL1ToL2MessageBlock(l1ToL2Message: Fr): Promise<BlockNumber | undefined> {
1380
+ public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
980
1381
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
981
- return messageIndex
982
- ? BlockNumber.fromCheckpointNumber(InboxLeaf.checkpointNumberFromIndex(messageIndex))
983
- : undefined;
1382
+ return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
984
1383
  }
985
1384
 
986
1385
  /**
@@ -1001,45 +1400,19 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1001
1400
  public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
1002
1401
  // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1003
1402
  const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1004
- const blocksInCheckpoints: L2Block[][] = [];
1005
- let previousSlotNumber = SlotNumber.ZERO;
1006
- let checkpointIndex = -1;
1007
- for (const checkpointedBlock of checkpointedBlocks) {
1008
- const block = checkpointedBlock.block;
1009
- const slotNumber = block.header.globalVariables.slotNumber;
1010
- if (slotNumber !== previousSlotNumber) {
1011
- checkpointIndex++;
1012
- blocksInCheckpoints.push([]);
1013
- previousSlotNumber = slotNumber;
1014
- }
1015
- blocksInCheckpoints[checkpointIndex].push(block);
1016
- }
1403
+ const blocksInCheckpoints = chunkBy(checkpointedBlocks, cb => cb.block.header.globalVariables.slotNumber).map(
1404
+ group => group.map(cb => cb.block),
1405
+ );
1017
1406
  return blocksInCheckpoints.map(blocks =>
1018
1407
  blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1019
1408
  );
1020
1409
  }
1021
1410
 
1022
- public async getArchiveSiblingPath(
1023
- block: BlockParameter,
1024
- leafIndex: bigint,
1025
- ): Promise<SiblingPath<typeof ARCHIVE_HEIGHT>> {
1026
- const committedDb = await this.#getWorldState(block);
1027
- return committedDb.getSiblingPath(MerkleTreeId.ARCHIVE, leafIndex);
1028
- }
1029
-
1030
- public async getPublicDataSiblingPath(
1031
- block: BlockParameter,
1032
- leafIndex: bigint,
1033
- ): Promise<SiblingPath<typeof PUBLIC_DATA_TREE_HEIGHT>> {
1034
- const committedDb = await this.#getWorldState(block);
1035
- return committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, leafIndex);
1036
- }
1037
-
1038
1411
  public async getNullifierMembershipWitness(
1039
- block: BlockParameter,
1412
+ referenceBlock: BlockParameter,
1040
1413
  nullifier: Fr,
1041
1414
  ): Promise<NullifierMembershipWitness | undefined> {
1042
- const db = await this.#getWorldState(block);
1415
+ const db = await this.getWorldState(referenceBlock);
1043
1416
  const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
1044
1417
  if (!witness) {
1045
1418
  return undefined;
@@ -1054,32 +1427,20 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1054
1427
  return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
1055
1428
  }
1056
1429
 
1057
- /**
1058
- * Returns a low nullifier membership witness for a given nullifier at a given block.
1059
- * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1060
- * @param nullifier - Nullifier we try to find the low nullifier witness for.
1061
- * @returns The low nullifier membership witness (if found).
1062
- * @remarks Low nullifier witness can be used to perform a nullifier non-inclusion proof by leveraging the "linked
1063
- * list structure" of leaves and proving that a lower nullifier is pointing to a bigger next value than the nullifier
1064
- * we are trying to prove non-inclusion for.
1065
- *
1066
- * Note: This function returns the membership witness of the nullifier itself and not the low nullifier when
1067
- * the nullifier already exists in the tree. This is because the `getPreviousValueIndex` function returns the
1068
- * index of the nullifier itself when it already exists in the tree.
1069
- * TODO: This is a confusing behavior and we should eventually address that.
1070
- */
1071
1430
  public async getLowNullifierMembershipWitness(
1072
- block: BlockParameter,
1431
+ referenceBlock: BlockParameter,
1073
1432
  nullifier: Fr,
1074
1433
  ): Promise<NullifierMembershipWitness | undefined> {
1075
- const committedDb = await this.#getWorldState(block);
1434
+ const committedDb = await this.getWorldState(referenceBlock);
1076
1435
  const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
1077
1436
  if (!findResult) {
1078
1437
  return undefined;
1079
1438
  }
1080
1439
  const { index, alreadyPresent } = findResult;
1081
1440
  if (alreadyPresent) {
1082
- 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
+ );
1083
1444
  }
1084
1445
  const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
1085
1446
 
@@ -1087,8 +1448,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1087
1448
  return new NullifierMembershipWitness(BigInt(index), preimageData as NullifierLeafPreimage, siblingPath);
1088
1449
  }
1089
1450
 
1090
- async getPublicDataWitness(block: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1091
- const committedDb = await this.#getWorldState(block);
1451
+ async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
1452
+ const committedDb = await this.getWorldState(referenceBlock);
1092
1453
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
1093
1454
  if (!lowLeafResult) {
1094
1455
  return undefined;
@@ -1102,8 +1463,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1102
1463
  }
1103
1464
  }
1104
1465
 
1105
- public async getPublicStorageAt(block: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1106
- const committedDb = await this.#getWorldState(block);
1466
+ public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
1467
+ const committedDb = await this.getWorldState(referenceBlock);
1107
1468
  const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
1108
1469
 
1109
1470
  const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
@@ -1117,34 +1478,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1117
1478
  return preimage.leaf.value;
1118
1479
  }
1119
1480
 
1120
- public async getBlockHeader(block: BlockParameter = 'latest'): Promise<BlockHeader | undefined> {
1121
- if (BlockHash.isL2BlockHash(block)) {
1122
- const initialBlockHash = await this.#getInitialHeaderHash();
1123
- if (block.equals(initialBlockHash)) {
1124
- // Block source doesn't handle initial header so we need to handle the case separately.
1125
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1126
- }
1127
- const blockHashFr = Fr.fromBuffer(block.toBuffer());
1128
- return this.blockSource.getBlockHeaderByHash(blockHashFr);
1129
- } else {
1130
- // Block source doesn't handle initial header so we need to handle the case separately.
1131
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
1132
- if (blockNumber === BlockNumber.ZERO) {
1133
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1134
- }
1135
- return this.blockSource.getBlockHeader(block);
1136
- }
1137
- }
1138
-
1139
- /**
1140
- * Get a block header specified by its archive root.
1141
- * @param archive - The archive root being requested.
1142
- * @returns The requested block header.
1143
- */
1144
- public async getBlockHeaderByArchive(archive: Fr): Promise<BlockHeader | undefined> {
1145
- return await this.blockSource.getBlockHeaderByArchive(archive);
1146
- }
1147
-
1148
1481
  /**
1149
1482
  * Simulates the public part of a transaction with the current state.
1150
1483
  * @param tx - The transaction to simulate.
@@ -1168,7 +1501,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1168
1501
  }
1169
1502
 
1170
1503
  const txHash = tx.getTxHash();
1171
- const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1504
+ const latestBlockNumber = await this.blockSource.getBlockNumber();
1505
+ const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1172
1506
 
1173
1507
  // If sequencer is not initialized, we just set these values to zero for simulation.
1174
1508
  const coinbase = EthAddress.ZERO;
@@ -1183,6 +1517,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1183
1517
  this.contractDataSource,
1184
1518
  new DateProvider(),
1185
1519
  this.telemetry,
1520
+ this.log.getBindings(),
1186
1521
  );
1187
1522
 
1188
1523
  this.log.verbose(`Simulating public calls for tx ${txHash}`, {
@@ -1191,6 +1526,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1191
1526
  blockNumber,
1192
1527
  });
1193
1528
 
1529
+ // Ensure world-state has caught up with the latest block we loaded from the archiver
1530
+ await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1194
1531
  const merkleTreeFork = await this.worldStateSynchronizer.fork();
1195
1532
  try {
1196
1533
  const config = PublicSimulatorConfig.from({
@@ -1206,7 +1543,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1206
1543
  const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1207
1544
 
1208
1545
  // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1209
- const [processedTxs, failedTxs, _usedTxs, returns] = await processor.process([tx]);
1546
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1210
1547
  // REFACTOR: Consider returning the error rather than throwing
1211
1548
  if (failedTxs.length) {
1212
1549
  this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
@@ -1220,6 +1557,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1220
1557
  processedTx.txEffect,
1221
1558
  returns,
1222
1559
  processedTx.gasUsed,
1560
+ debugLogs,
1223
1561
  );
1224
1562
  } finally {
1225
1563
  await merkleTreeFork.close();
@@ -1231,21 +1569,34 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1231
1569
  { isSimulation, skipFeeEnforcement }: { isSimulation?: boolean; skipFeeEnforcement?: boolean } = {},
1232
1570
  ): Promise<TxValidationResult> {
1233
1571
  const db = this.worldStateSynchronizer.getCommitted();
1234
- const verifier = isSimulation ? undefined : this.proofVerifier;
1572
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1235
1573
 
1236
- // 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)
1237
1575
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
1238
1576
  const blockNumber = BlockNumber((await this.blockSource.getBlockNumber()) + 1);
1239
- const validator = createValidatorForAcceptingTxs(db, this.contractDataSource, verifier, {
1240
- timestamp: nextSlotTimestamp,
1241
- blockNumber,
1242
- l1ChainId: this.l1ChainId,
1243
- rollupVersion: this.version,
1244
- setupAllowList: this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions()),
1245
- gasFees: await this.getCurrentMinFees(),
1246
- skipFeeEnforcement,
1247
- txsPermitted: !this.config.disableTransactions,
1248
- });
1577
+ const l1Constants = await this.blockSource.getL1Constants();
1578
+ const validator = createTxValidatorForAcceptingTxsOverRPC(
1579
+ db,
1580
+ this.contractDataSource,
1581
+ verifier,
1582
+ {
1583
+ timestamp: nextSlotTimestamp,
1584
+ blockNumber,
1585
+ l1ChainId: this.l1ChainId,
1586
+ rollupVersion: this.version,
1587
+ setupAllowList: [
1588
+ ...(await getDefaultAllowedSetupFunctions()),
1589
+ ...(this.config.txPublicSetupAllowListExtend ?? []),
1590
+ ],
1591
+ gasFees: await this.getCurrentMinFees(),
1592
+ skipFeeEnforcement,
1593
+ txsPermitted: !this.config.disableTransactions,
1594
+ rollupManaLimit: l1Constants.rollupManaLimit,
1595
+ maxBlockL2Gas: this.config.validateMaxL2BlockGas,
1596
+ maxBlockDAGas: this.config.validateMaxDABlockGas,
1597
+ },
1598
+ this.log.getBindings(),
1599
+ );
1249
1600
 
1250
1601
  return await validator.validateTx(tx);
1251
1602
  }
@@ -1267,7 +1618,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1267
1618
  archiver.updateConfig(config);
1268
1619
  }
1269
1620
  if (newConfig.realProofs !== this.config.realProofs) {
1270
- 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
+ }
1271
1630
  }
1272
1631
 
1273
1632
  this.config = newConfig;
@@ -1342,7 +1701,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1342
1701
  return Promise.resolve();
1343
1702
  }
1344
1703
 
1345
- public async rollbackTo(targetBlock: BlockNumber, force?: boolean): Promise<void> {
1704
+ public async rollbackTo(targetBlock: BlockNumber, force?: boolean, resumeSync = true): Promise<void> {
1346
1705
  const archiver = this.blockSource as Archiver;
1347
1706
  if (!('rollbackTo' in archiver)) {
1348
1707
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1372,9 +1731,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1372
1731
  this.log.error(`Error during rollback`, err);
1373
1732
  throw err;
1374
1733
  } finally {
1375
- this.log.info(`Resuming world state and archiver sync.`);
1376
- this.worldStateSynchronizer.resumeSync();
1377
- 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
+ }
1378
1741
  }
1379
1742
  }
1380
1743
 
@@ -1391,24 +1754,139 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1391
1754
  return Promise.resolve();
1392
1755
  }
1393
1756
 
1394
- public getSlashPayloads(): Promise<SlashPayloadRound[]> {
1395
- if (!this.slasherClient) {
1396
- throw new Error(`Slasher client not enabled`);
1397
- }
1398
- return this.slasherClient.getSlashPayloads();
1399
- }
1400
-
1401
1757
  public getSlashOffenses(round: bigint | 'all' | 'current'): Promise<Offense[]> {
1402
1758
  if (!this.slasherClient) {
1403
1759
  throw new Error(`Slasher client not enabled`);
1404
1760
  }
1405
1761
  if (round === 'all') {
1406
- return this.slasherClient.getPendingOffenses();
1762
+ return this.slasherClient.getOffenses();
1407
1763
  } else {
1408
1764
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1409
1765
  }
1410
1766
  }
1411
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
+
1412
1890
  #getInitialHeaderHash(): Promise<BlockHash> {
1413
1891
  if (!this.initialHeaderHashPromise) {
1414
1892
  this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
@@ -1421,7 +1899,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1421
1899
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1422
1900
  * @returns An instance of a committed MerkleTreeOperations
1423
1901
  */
1424
- async #getWorldState(block: BlockParameter) {
1902
+ protected async getWorldState(block: BlockParameter) {
1425
1903
  let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1426
1904
  try {
1427
1905
  // Attempt to sync the world state if necessary
@@ -1435,36 +1913,77 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1435
1913
  return this.worldStateSynchronizer.getCommitted();
1436
1914
  }
1437
1915
 
1438
- if (BlockHash.isL2BlockHash(block)) {
1916
+ // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1917
+ let blockNumber: BlockNumber;
1918
+ if (BlockHash.isBlockHash(block)) {
1439
1919
  const initialBlockHash = await this.#getInitialHeaderHash();
1440
1920
  if (block.equals(initialBlockHash)) {
1441
- // Block source doesn't handle initial header so we need to handle the case separately.
1442
- 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();
1443
1933
  }
1934
+ } else {
1935
+ blockNumber = block as BlockNumber;
1936
+ }
1444
1937
 
1445
- const blockHashFr = Fr.fromBuffer(block.toBuffer());
1446
- const header = await this.blockSource.getBlockHeaderByHash(blockHashFr);
1447
- 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();
1448
1953
  throw new Error(
1449
- `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.`,
1450
1955
  );
1451
1956
  }
1452
- const blockNumber = header.getBlockNumber();
1453
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1454
- return this.worldStateSynchronizer.getSnapshot(blockNumber);
1455
1957
  }
1456
1958
 
1457
- // Block number provided
1458
- {
1459
- const blockNumber = block as BlockNumber;
1959
+ return snapshot;
1960
+ }
1460
1961
 
1461
- if (blockNumber > blockSyncedTo) {
1462
- 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;
1463
1972
  }
1464
-
1465
- this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1466
- 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();
1467
1985
  }
1986
+ throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(block)}`);
1468
1987
  }
1469
1988
 
1470
1989
  /**