@aztec/aztec-node 5.0.0-private.20260319 → 6.0.0-nightly.20260603

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.
Files changed (37) hide show
  1. package/dest/aztec-node/block_response_helpers.d.ts +25 -0
  2. package/dest/aztec-node/block_response_helpers.d.ts.map +1 -0
  3. package/dest/aztec-node/block_response_helpers.js +112 -0
  4. package/dest/aztec-node/config.d.ts +7 -4
  5. package/dest/aztec-node/config.d.ts.map +1 -1
  6. package/dest/aztec-node/config.js +5 -5
  7. package/dest/aztec-node/public_data_overrides.d.ts +13 -0
  8. package/dest/aztec-node/public_data_overrides.d.ts.map +1 -0
  9. package/dest/aztec-node/public_data_overrides.js +21 -0
  10. package/dest/aztec-node/server.d.ts +55 -93
  11. package/dest/aztec-node/server.d.ts.map +1 -1
  12. package/dest/aztec-node/server.js +906 -468
  13. package/dest/sentinel/config.d.ts +3 -2
  14. package/dest/sentinel/config.d.ts.map +1 -1
  15. package/dest/sentinel/config.js +15 -5
  16. package/dest/sentinel/factory.d.ts +4 -2
  17. package/dest/sentinel/factory.d.ts.map +1 -1
  18. package/dest/sentinel/factory.js +4 -4
  19. package/dest/sentinel/sentinel.d.ts +133 -9
  20. package/dest/sentinel/sentinel.d.ts.map +1 -1
  21. package/dest/sentinel/sentinel.js +212 -70
  22. package/dest/sentinel/store.d.ts +8 -8
  23. package/dest/sentinel/store.d.ts.map +1 -1
  24. package/dest/sentinel/store.js +25 -17
  25. package/dest/test/index.d.ts +3 -3
  26. package/dest/test/index.d.ts.map +1 -1
  27. package/package.json +27 -26
  28. package/src/aztec-node/block_response_helpers.ts +161 -0
  29. package/src/aztec-node/config.ts +11 -7
  30. package/src/aztec-node/public_data_overrides.ts +35 -0
  31. package/src/aztec-node/server.ts +974 -596
  32. package/src/sentinel/README.md +103 -0
  33. package/src/sentinel/config.ts +18 -6
  34. package/src/sentinel/factory.ts +7 -4
  35. package/src/sentinel/sentinel.ts +267 -82
  36. package/src/sentinel/store.ts +26 -18
  37. package/src/test/index.ts +2 -2
@@ -1,5 +1,6 @@
1
- import { Archiver, createArchiver } from '@aztec/archiver';
2
- import { BBCircuitVerifier, QueuedIVCVerifier, TestCircuitVerifier } from '@aztec/bb-prover';
1
+ import { Archiver, L1ToL2MessagesNotReadyError, createArchiver } from '@aztec/archiver';
2
+ import { BBCircuitVerifier, BatchChonkVerifier, QueuedIVCVerifier } from '@aztec/bb-prover';
3
+ import { TestCircuitVerifier } from '@aztec/bb-prover/test';
3
4
  import { type BlobClientInterface, createBlobClientWithFileStores } from '@aztec/blob-client/client';
4
5
  import { Blob } from '@aztec/blob-lib';
5
6
  import { ARCHIVE_HEIGHT, type L1_TO_L2_MSG_TREE_HEIGHT, type NOTE_HASH_TREE_HEIGHT } from '@aztec/constants';
@@ -7,16 +8,19 @@ import { EpochCache, type EpochCacheInterface } from '@aztec/epoch-cache';
7
8
  import { createEthereumChain } from '@aztec/ethereum/chain';
8
9
  import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
9
10
  import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
10
- import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
11
+ import { type L1ContractAddresses, pickL1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
12
+ import type { L1TxUtils } from '@aztec/ethereum/l1-tx-utils';
11
13
  import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
12
14
  import { chunkBy, compactArray, pick, unique } from '@aztec/foundation/collection';
13
15
  import { Fr } from '@aztec/foundation/curves/bn254';
14
16
  import { EthAddress } from '@aztec/foundation/eth-address';
15
17
  import { BadRequestError } from '@aztec/foundation/json-rpc';
16
18
  import { type Logger, createLogger } from '@aztec/foundation/log';
19
+ import { retryUntil } from '@aztec/foundation/retry';
17
20
  import { count } from '@aztec/foundation/string';
18
21
  import { DateProvider, Timer } from '@aztec/foundation/timer';
19
22
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
23
+ import { isErrorClass } from '@aztec/foundation/types';
20
24
  import { type KeyStore, KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
21
25
  import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
22
26
  import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
@@ -30,26 +34,46 @@ import {
30
34
  import { ProtocolContractAddress } from '@aztec/protocol-contracts';
31
35
  import { type ProverNode, type ProverNodeDeps, createProverNode } from '@aztec/prover-node';
32
36
  import { createKeyStoreForProver } from '@aztec/prover-node/config';
33
- import { GlobalVariableBuilder, SequencerClient, type SequencerPublisher } from '@aztec/sequencer-client';
34
- import { PublicProcessorFactory } from '@aztec/simulator/server';
37
+ import {
38
+ AutomineSequencer,
39
+ FeeProviderImpl,
40
+ GlobalVariableBuilder,
41
+ SequencerClient,
42
+ type SequencerPublisher,
43
+ createAutomineSequencer,
44
+ } from '@aztec/sequencer-client';
45
+ import { PublicContractsDB, PublicProcessorFactory } from '@aztec/simulator/server';
35
46
  import {
36
47
  AttestationsBlockWatcher,
37
- EpochPruneWatcher,
48
+ AttestedInvalidProposalWatcher,
49
+ BroadcastedInvalidCheckpointProposalWatcher,
50
+ CheckpointEquivocationWatcher,
51
+ DataWithholdingWatcher,
38
52
  type SlasherClientInterface,
39
53
  type Watcher,
40
54
  createSlasher,
41
55
  } from '@aztec/slasher';
56
+ import { STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS } from '@aztec/standard-contracts/multi-call-entrypoint';
42
57
  import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
43
58
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
44
59
  import {
45
60
  type BlockData,
46
61
  BlockHash,
47
62
  type BlockParameter,
63
+ BlockTag,
64
+ type CheckpointsQuery,
65
+ type CommitteeAttestation,
48
66
  type DataInBlock,
49
- L2Block,
50
67
  type L2BlockSource,
68
+ type NormalizedBlockParameter,
69
+ inspectBlockParameter,
51
70
  } from '@aztec/stdlib/block';
52
- import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
71
+ import {
72
+ type CheckpointData,
73
+ CheckpointReexecutionTracker,
74
+ L1PublishedData,
75
+ type PublishedCheckpoint,
76
+ } from '@aztec/stdlib/checkpoint';
53
77
  import type {
54
78
  ContractClassPublic,
55
79
  ContractDataSource,
@@ -57,16 +81,23 @@ import type {
57
81
  NodeInfo,
58
82
  ProtocolContractAddresses,
59
83
  } from '@aztec/stdlib/contract';
60
- import { GasFees } from '@aztec/stdlib/gas';
84
+ import { GasFees, type ManaUsageEstimate } from '@aztec/stdlib/gas';
61
85
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
62
- import {
63
- type AztecNode,
64
- type AztecNodeAdmin,
65
- type AztecNodeAdminConfig,
66
- AztecNodeAdminConfigSchema,
67
- type GetContractClassLogsResponse,
68
- type GetPublicLogsResponse,
86
+ import type {
87
+ AztecNode,
88
+ AztecNodeAdmin,
89
+ AztecNodeAdminConfig,
90
+ AztecNodeDebug,
91
+ BlockIncludeOptions,
92
+ BlockResponse,
93
+ BlocksIncludeOptions,
94
+ ChainTip,
95
+ ChainTips,
96
+ CheckpointIncludeOptions,
97
+ CheckpointParameter,
98
+ CheckpointResponse,
69
99
  } from '@aztec/stdlib/interfaces/client';
100
+ import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
70
101
  import {
71
102
  type AllowedElement,
72
103
  type ClientProtocolCircuitVerifier,
@@ -76,17 +107,19 @@ import {
76
107
  type WorldStateSynchronizer,
77
108
  tryStop,
78
109
  } from '@aztec/stdlib/interfaces/server';
79
- import type { DebugLogStore, LogFilter, SiloedTag, Tag, TxScopedL2Log } from '@aztec/stdlib/logs';
110
+ import type { DebugLogStore, LogResult, PrivateLogsQuery, PublicLogsQuery } from '@aztec/stdlib/logs';
80
111
  import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
81
- import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
82
- import type { Offense, SlashPayloadRound } from '@aztec/stdlib/slashing';
83
- import type { NullifierLeafPreimage, PublicDataTreeLeaf, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
112
+ import { InboxLeaf, type L1ToL2MessageSource, appendL1ToL2MessagesToTree } from '@aztec/stdlib/messaging';
113
+ import type { Offense } from '@aztec/stdlib/slashing';
114
+ import { MIN_EXECUTION_TIME } from '@aztec/stdlib/timetable';
115
+ import type { NullifierLeafPreimage, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
84
116
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
85
117
  import {
86
- type BlockHeader,
118
+ type FeeProvider,
87
119
  type GlobalVariableBuilder as GlobalVariableBuilderInterface,
88
120
  type IndexedTxEffect,
89
121
  PublicSimulationOutput,
122
+ type SimulationOverrides,
90
123
  Tx,
91
124
  type TxHash,
92
125
  TxReceipt,
@@ -95,6 +128,7 @@ import {
95
128
  } from '@aztec/stdlib/tx';
96
129
  import { getPackageVersion } from '@aztec/stdlib/update-checker';
97
130
  import type { SingleValidatorStats, ValidatorsStats } from '@aztec/stdlib/validators';
131
+ import type { GenesisData } from '@aztec/stdlib/world-state';
98
132
  import {
99
133
  Attributes,
100
134
  type TelemetryClient,
@@ -108,28 +142,36 @@ import {
108
142
  FullNodeCheckpointsBuilder,
109
143
  NodeKeystoreAdapter,
110
144
  ValidatorClient,
111
- createBlockProposalHandler,
145
+ createProposalHandler,
112
146
  createValidatorClient,
113
147
  } from '@aztec/validator-client';
114
148
  import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
115
- import { createWorldStateSynchronizer } from '@aztec/world-state';
149
+ import { createWorldState, createWorldStateSynchronizer } from '@aztec/world-state';
116
150
 
117
151
  import { createPublicClient } from 'viem';
118
152
 
119
153
  import { createSentinel } from '../sentinel/factory.js';
120
154
  import { Sentinel } from '../sentinel/sentinel.js';
155
+ import {
156
+ blockResponseFromBlockData,
157
+ blockResponseFromL2Block,
158
+ checkpointResponseFromCheckpointData,
159
+ checkpointResponseFromPublishedCheckpoint,
160
+ projectProposedToCheckpointResponse,
161
+ } from './block_response_helpers.js';
121
162
  import { type AztecNodeConfig, createKeyStoreForValidator } from './config.js';
122
163
  import { NodeMetrics } from './node_metrics.js';
164
+ import { applyPublicDataOverrides } from './public_data_overrides.js';
123
165
 
124
166
  /**
125
167
  * The aztec node.
126
168
  */
127
- export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
169
+ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDebug, Traceable {
128
170
  private metrics: NodeMetrics;
129
- private initialHeaderHashPromise: Promise<BlockHash> | undefined = undefined;
130
-
131
171
  // Prevent two snapshot operations to happen simultaneously
132
172
  private isUploadingSnapshot = false;
173
+ // Saved minTxsPerBlock used by `pauseSequencer` to restore production-sequencer config on resume.
174
+ private sequencerPausedMinTxsPerBlock: number | undefined;
133
175
 
134
176
  public readonly tracer: Tracer;
135
177
 
@@ -145,25 +187,28 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
145
187
  protected readonly proverNode: ProverNode | undefined,
146
188
  protected readonly slasherClient: SlasherClientInterface | undefined,
147
189
  protected readonly validatorsSentinel: Sentinel | undefined,
148
- protected readonly epochPruneWatcher: EpochPruneWatcher | undefined,
190
+ private readonly stopStartedWatchers: () => Promise<void>,
149
191
  protected readonly l1ChainId: number,
150
192
  protected readonly version: number,
151
193
  protected readonly globalVariableBuilder: GlobalVariableBuilderInterface,
194
+ protected readonly feeProvider: FeeProvider,
152
195
  protected readonly epochCache: EpochCacheInterface,
153
196
  protected readonly packageVersion: string,
154
- private proofVerifier: ClientProtocolCircuitVerifier,
197
+ private peerProofVerifier: ClientProtocolCircuitVerifier,
198
+ private rpcProofVerifier: ClientProtocolCircuitVerifier,
155
199
  private telemetry: TelemetryClient = getTelemetryClient(),
156
200
  private log = createLogger('node'),
157
201
  private blobClient?: BlobClientInterface,
158
202
  private validatorClient?: ValidatorClient,
159
203
  private keyStoreManager?: KeystoreManager,
160
204
  private debugLogStore: DebugLogStore = new NullDebugLogStore(),
205
+ private readonly automineSequencer?: AutomineSequencer,
161
206
  ) {
162
207
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
163
208
  this.tracer = telemetry.getTracer('AztecNodeService');
164
209
 
165
210
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
166
- this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
211
+ this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, pickL1ContractAddresses(config));
167
212
 
168
213
  // A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
169
214
  // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
@@ -173,13 +218,248 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
173
218
  }
174
219
  }
175
220
 
221
+ /** @internal Exposed for testing — returns the RPC proof verifier. */
222
+ public getProofVerifier(): ClientProtocolCircuitVerifier {
223
+ return this.rpcProofVerifier;
224
+ }
225
+
176
226
  public async getWorldStateSyncStatus(): Promise<WorldStateSyncStatus> {
177
227
  const status = await this.worldStateSynchronizer.status();
178
228
  return status.syncSummary;
179
229
  }
180
230
 
181
- public getL2Tips() {
182
- return this.blockSource.getL2Tips();
231
+ public async getChainTips(): Promise<ChainTips> {
232
+ const { proposed, checkpointed, proven, finalized } = await this.blockSource.getL2Tips();
233
+ return { proposed, checkpointed, proven, finalized };
234
+ }
235
+
236
+ public getCheckpointsData(query: CheckpointsQuery) {
237
+ return this.blockSource.getCheckpointsData(query);
238
+ }
239
+
240
+ public async getBlockNumber(tip?: ChainTip): Promise<BlockNumber> {
241
+ if (tip === undefined || tip === 'proposed') {
242
+ return this.blockSource.getBlockNumber();
243
+ }
244
+ return (await this.blockSource.getBlockNumber({ tag: tip })) ?? BlockNumber.ZERO;
245
+ }
246
+
247
+ public async getCheckpointNumber(tip?: ChainTip): Promise<CheckpointNumber> {
248
+ const tips = await this.blockSource.getL2Tips();
249
+ switch (tip) {
250
+ case undefined:
251
+ case 'checkpointed':
252
+ return tips.checkpointed.checkpoint.number;
253
+ case 'proposed':
254
+ return tips.proposedCheckpoint.checkpoint.number;
255
+ case 'proven':
256
+ return tips.proven.checkpoint.number;
257
+ case 'finalized':
258
+ return tips.finalized.checkpoint.number;
259
+ }
260
+ }
261
+
262
+ private isChainTip(value: unknown): value is ChainTip {
263
+ return value === 'proposed' || value === 'checkpointed' || value === 'proven' || value === 'finalized';
264
+ }
265
+
266
+ /**
267
+ * Normalizes a {@link BlockParameter} (which may be a bare value) into a
268
+ * {@link NormalizedBlockParameter} object form. Performs no chain-tip resolution — tag
269
+ * lookups are deferred to the underlying block source.
270
+ */
271
+ private normalizeBlockParameter(param: BlockParameter): NormalizedBlockParameter {
272
+ if (BlockHash.isBlockHash(param)) {
273
+ return { hash: param };
274
+ }
275
+ if (typeof param === 'number') {
276
+ return { number: param as BlockNumber };
277
+ }
278
+ if (typeof param === 'string') {
279
+ if (this.isBlockTag(param)) {
280
+ return { tag: param === 'latest' ? 'proposed' : param };
281
+ }
282
+ throw new BadRequestError(`Invalid BlockParameter tag: ${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
+ if ('tag' in param) {
295
+ if (this.isBlockTag(param.tag)) {
296
+ return { tag: param.tag };
297
+ }
298
+ throw new BadRequestError(`Invalid BlockParameter tag: ${param.tag}`);
299
+ }
300
+ }
301
+ throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(param)}`);
302
+ }
303
+
304
+ private isBlockTag(value: string): value is BlockTag {
305
+ return BlockTag.includes(value as BlockTag);
306
+ }
307
+
308
+ /**
309
+ * Resolves a {@link CheckpointParameter} into a concrete `{ number }` or `{ slot }` query.
310
+ *
311
+ * Tag-based parameters (`'proposed'`, `'checkpointed'`, `'proven'`, `'finalized'`) are
312
+ * translated up-front to the corresponding tip's checkpoint number via {@link L2BlockSource.getL2Tips}.
313
+ * After resolution the unified {@link getCheckpoint} flow can perform a single
314
+ * confirmed→proposed lookup against either store.
315
+ */
316
+ private async resolveCheckpointParameter(
317
+ param: CheckpointParameter,
318
+ ): Promise<{ number: CheckpointNumber } | { slot: SlotNumber }> {
319
+ if (typeof param === 'number') {
320
+ return { number: param as CheckpointNumber };
321
+ }
322
+ if (this.isChainTip(param)) {
323
+ const tips = await this.blockSource.getL2Tips();
324
+ switch (param) {
325
+ case 'proposed':
326
+ return { number: tips.proposedCheckpoint.checkpoint.number };
327
+ case 'checkpointed':
328
+ return { number: tips.checkpointed.checkpoint.number };
329
+ case 'proven':
330
+ return { number: tips.proven.checkpoint.number };
331
+ case 'finalized':
332
+ return { number: tips.finalized.checkpoint.number };
333
+ }
334
+ }
335
+ if (typeof param === 'object' && param !== null) {
336
+ if ('number' in param) {
337
+ return { number: param.number };
338
+ }
339
+ if ('slot' in param) {
340
+ return { slot: param.slot };
341
+ }
342
+ }
343
+ throw new BadRequestError(`Invalid CheckpointParameter: ${JSON.stringify(param)}`);
344
+ }
345
+
346
+ /** Fetches checkpoint-level L1 and attestation data for use as block response context. */
347
+ async #getCheckpointContext(
348
+ checkpointNumber: CheckpointNumber,
349
+ ): Promise<{ l1?: L1PublishedData; attestations?: CommitteeAttestation[] } | undefined> {
350
+ const checkpoint = await this.blockSource.getCheckpointData({ number: checkpointNumber });
351
+ if (!checkpoint) {
352
+ return undefined;
353
+ }
354
+ return { l1: checkpoint.l1, attestations: checkpoint.attestations };
355
+ }
356
+
357
+ public async getBlock<Opts extends BlockIncludeOptions = {}>(
358
+ param: BlockParameter,
359
+ options: Opts = {} as Opts,
360
+ ): Promise<BlockResponse<Opts> | undefined> {
361
+ const query = this.normalizeBlockParameter(param);
362
+ const wantTxs = !!options.includeTransactions;
363
+ const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
364
+
365
+ if (wantTxs) {
366
+ const block = await this.blockSource.getBlock(query);
367
+ if (!block) {
368
+ return undefined;
369
+ }
370
+ const ctx = wantContext ? await this.#getCheckpointContext(block.checkpointNumber) : undefined;
371
+ return (await blockResponseFromL2Block(block, options, ctx)) as BlockResponse<Opts>;
372
+ }
373
+ const data = await this.blockSource.getBlockData(query);
374
+ if (!data) {
375
+ return undefined;
376
+ }
377
+ const ctx = wantContext ? await this.#getCheckpointContext(data.checkpointNumber) : undefined;
378
+ return blockResponseFromBlockData(data, options, ctx) as BlockResponse<Opts>;
379
+ }
380
+
381
+ public getBlockData(param: BlockParameter): Promise<BlockData | undefined> {
382
+ const query = this.normalizeBlockParameter(param);
383
+ return this.blockSource.getBlockData(query);
384
+ }
385
+
386
+ public async getBlocks<Opts extends BlocksIncludeOptions = {}>(
387
+ from: BlockNumber,
388
+ limit: number,
389
+ options: Opts = {} as Opts,
390
+ ): Promise<BlockResponse<Opts>[]> {
391
+ const wantTxs = !!options.includeTransactions;
392
+ const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
393
+ const onlyCheckpointed = !!options.onlyCheckpointed;
394
+ if (wantTxs) {
395
+ const blocks = await this.blockSource.getBlocks({ from, limit, onlyCheckpointed });
396
+ const ctxByCheckpoint = await this.#getCheckpointContextsForBlocks(wantContext ? blocks : []);
397
+ return (await Promise.all(
398
+ blocks.map(block => blockResponseFromL2Block(block, options, ctxByCheckpoint.get(block.checkpointNumber))),
399
+ )) as BlockResponse<Opts>[];
400
+ }
401
+ const dataItems = await this.blockSource.getBlocksData({ from, limit, onlyCheckpointed });
402
+ const ctxByCheckpoint = await this.#getCheckpointContextsForBlocks(wantContext ? dataItems : []);
403
+ return (await Promise.all(
404
+ dataItems.map(data => blockResponseFromBlockData(data, options, ctxByCheckpoint.get(data.checkpointNumber))),
405
+ )) as BlockResponse<Opts>[];
406
+ }
407
+
408
+ /** Fetches checkpoint context for a set of blocks, deduplicating shared checkpoints. */
409
+ async #getCheckpointContextsForBlocks(
410
+ blocks: { checkpointNumber: CheckpointNumber }[],
411
+ ): Promise<Map<CheckpointNumber, { l1?: L1PublishedData; attestations?: CommitteeAttestation[] } | undefined>> {
412
+ const unique = Array.from(new Set(blocks.map(b => b.checkpointNumber)));
413
+ const entries = await Promise.all(unique.map(async n => [n, await this.#getCheckpointContext(n)] as const));
414
+ return new Map(entries);
415
+ }
416
+
417
+ public async getCheckpoint<Opts extends CheckpointIncludeOptions = {}>(
418
+ param: CheckpointParameter,
419
+ options: Opts = {} as Opts,
420
+ ): Promise<CheckpointResponse<Opts> | undefined> {
421
+ const query = await this.resolveCheckpointParameter(param);
422
+
423
+ // Try the confirmed store first.
424
+ const confirmed = options.includeBlocks
425
+ ? await this.blockSource.getCheckpoint(query)
426
+ : await this.blockSource.getCheckpointData(query);
427
+ if (confirmed) {
428
+ return (await (options.includeBlocks
429
+ ? checkpointResponseFromPublishedCheckpoint(confirmed as PublishedCheckpoint, options)
430
+ : checkpointResponseFromCheckpointData(confirmed as CheckpointData, options))) as CheckpointResponse<Opts>;
431
+ }
432
+
433
+ // Fall back to the proposed store.
434
+ const proposed = await this.blockSource.getProposedCheckpointData(query);
435
+ if (proposed) {
436
+ if (options.includeAttestations || options.includeL1PublishInfo) {
437
+ throw new BadRequestError(
438
+ `Options includeL1PublishInfo or includeAttestations cannot be satisfied for a proposed checkpoint`,
439
+ );
440
+ }
441
+ const blocks = options.includeBlocks
442
+ ? await this.blockSource.getBlocks({ from: proposed.startBlock, limit: proposed.blockCount })
443
+ : undefined;
444
+ return (await projectProposedToCheckpointResponse(proposed, options, blocks)) as CheckpointResponse<Opts>;
445
+ }
446
+
447
+ return undefined;
448
+ }
449
+
450
+ public async getCheckpoints<Opts extends CheckpointIncludeOptions = {}>(
451
+ from: CheckpointNumber,
452
+ limit: number,
453
+ options: Opts = {} as Opts,
454
+ ): Promise<CheckpointResponse<Opts>[]> {
455
+ if (options.includeBlocks) {
456
+ const checkpoints = await this.blockSource.getCheckpoints({ from, limit });
457
+ return (await Promise.all(
458
+ checkpoints.map(cp => checkpointResponseFromPublishedCheckpoint(cp, options)),
459
+ )) as CheckpointResponse<Opts>[];
460
+ }
461
+ const datas = await this.blockSource.getCheckpointsData({ from, limit });
462
+ return datas.map(d => checkpointResponseFromCheckpointData(d, options)) as CheckpointResponse<Opts>[];
183
463
  }
184
464
 
185
465
  /**
@@ -199,14 +479,14 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
199
479
  slashingProtectionDb?: SlashingProtectionDatabase;
200
480
  } = {},
201
481
  options: {
202
- prefilledPublicData?: PublicDataTreeLeaf[];
482
+ genesis?: GenesisData;
203
483
  dontStartSequencer?: boolean;
204
484
  dontStartProverNode?: boolean;
205
485
  } = {},
206
486
  ): Promise<AztecNodeService> {
207
487
  const config = { ...inputConfig }; // Copy the config so we dont mutate the input object
208
488
  const log = deps.logger ?? createLogger('node');
209
- const packageVersion = getPackageVersion() ?? '';
489
+ const packageVersion = getPackageVersion();
210
490
  const telemetry = deps.telemetry ?? getTelemetryClient();
211
491
  const dateProvider = deps.dateProvider ?? new DateProvider();
212
492
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
@@ -265,14 +545,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
265
545
 
266
546
  const l1ContractsAddresses = await RegistryContract.collectAddresses(
267
547
  publicClient,
268
- config.l1Contracts.registryAddress,
548
+ config.registryAddress,
269
549
  config.rollupVersion ?? 'canonical',
270
550
  );
271
551
 
272
- // Overwrite the passed in vars.
273
- config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
552
+ Object.assign(config, l1ContractsAddresses);
274
553
 
275
- const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
554
+ const rollupContract = new RollupContract(publicClient, config.rollupAddress.toString());
276
555
  const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
277
556
  rollupContract.getL1GenesisTime(),
278
557
  rollupContract.getSlotDuration(),
@@ -293,301 +572,442 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
293
572
  // attempt snapshot sync if possible
294
573
  await trySnapshotSync(config, log);
295
574
 
296
- const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, { dateProvider });
297
-
298
- const archiver = await createArchiver(
299
- config,
300
- { blobClient, epochCache, telemetry, dateProvider },
301
- { blockUntilSync: !config.skipArchiverInitialSync },
302
- );
575
+ const epochCache = await EpochCache.create(config.rollupAddress, config, { dateProvider });
303
576
 
304
- // now create the merkle trees and the world state synchronizer
305
- const worldStateSynchronizer = await createWorldStateSynchronizer(
306
- config,
307
- archiver,
308
- options.prefilledPublicData,
309
- telemetry,
310
- );
311
- const circuitVerifier =
312
- config.realProofs || config.debugForceTxProofVerification
313
- ? await BBCircuitVerifier.new(config)
314
- : new TestCircuitVerifier(config.proverTestVerificationDelayMs);
315
-
316
- let debugLogStore: DebugLogStore;
317
- if (!config.realProofs) {
318
- log.warn(`Aztec node is accepting fake proofs`);
319
-
320
- debugLogStore = new InMemoryDebugLogStore();
321
- log.info(
322
- 'Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served',
577
+ // Track started resources so we can clean up on partial failure during node creation.
578
+ const started: { stop?(): Promise<void> | void }[] = [];
579
+ try {
580
+ // Default the orphan-prune grace window from the block build duration when unset, so the archiver
581
+ // waits roughly one build slot for a proposed checkpoint to arrive before pruning a block-only tip.
582
+ config.orphanProposedBlockPruneGraceSeconds ??=
583
+ config.blockDurationMs !== undefined ? Math.ceil(config.blockDurationMs / 1000) : MIN_EXECUTION_TIME;
584
+
585
+ // Create world-state first so we can retrieve the initial header before constructing the archiver.
586
+ const nativeWs = await createWorldState(config, options.genesis);
587
+ const initialHeader = nativeWs.getInitialHeader();
588
+ const initialBlockHash = await initialHeader.hash();
589
+ const archiver = await createArchiver(
590
+ config,
591
+ { blobClient, epochCache, telemetry, dateProvider },
592
+ { blockUntilSync: !config.skipArchiverInitialSync },
593
+ initialHeader,
594
+ initialBlockHash,
323
595
  );
324
- } else {
325
- debugLogStore = new NullDebugLogStore();
326
- }
327
-
328
- const proofVerifier = new QueuedIVCVerifier(config, circuitVerifier);
329
-
330
- const proverOnly = config.enableProverNode && config.disableValidator;
331
- if (proverOnly) {
332
- log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
333
- }
596
+ started.push(archiver);
597
+
598
+ // The synchronizer takes ownership of the native world-state from here
599
+ const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, nativeWs, telemetry);
600
+ started.push(worldStateSynchronizer);
601
+ const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
602
+ let peerProofVerifier: ClientProtocolCircuitVerifier;
603
+ let rpcProofVerifier: ClientProtocolCircuitVerifier;
604
+ if (useRealVerifiers) {
605
+ peerProofVerifier = await BatchChonkVerifier.new(config, config.bbChonkVerifyMaxBatch, 'peer');
606
+ const rpcVerifier = await BBCircuitVerifier.new(config);
607
+ rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, config.numConcurrentIVCVerifiers);
608
+ } else {
609
+ peerProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
610
+ rpcProofVerifier = new TestCircuitVerifier(config.proverTestVerificationDelayMs);
611
+ }
612
+ started.push(peerProofVerifier, rpcProofVerifier);
334
613
 
335
- // create the tx pool and the p2p client, which will need the l2 block source
336
- const p2pClient = await createP2PClient(
337
- config,
338
- archiver,
339
- proofVerifier,
340
- worldStateSynchronizer,
341
- epochCache,
342
- packageVersion,
343
- dateProvider,
344
- telemetry,
345
- deps.p2pClientDeps,
346
- );
614
+ let debugLogStore: DebugLogStore;
615
+ if (!config.realProofs) {
616
+ log.warn(`Aztec node is accepting fake proofs`);
347
617
 
348
- // We'll accumulate sentinel watchers here
349
- const watchers: Watcher[] = [];
618
+ debugLogStore = new InMemoryDebugLogStore();
619
+ log.info(
620
+ 'Aztec node started in test mode (realProofs set to false) hence debug logs from public functions will be collected and served',
621
+ );
622
+ } else {
623
+ debugLogStore = new NullDebugLogStore();
624
+ }
350
625
 
351
- // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
352
- // Override maxTxsPerCheckpoint with the validator-specific limit if set.
353
- const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
354
- {
355
- ...config,
626
+ const globalVariableBuilderConfig = {
627
+ rollupAddress: config.rollupAddress,
628
+ ethereumSlotDuration: config.ethereumSlotDuration,
629
+ rollupVersion: BigInt(config.rollupVersion),
356
630
  l1GenesisTime,
357
631
  slotDuration: Number(slotDuration),
358
- rollupManaLimit,
359
- maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint,
360
- },
361
- worldStateSynchronizer,
362
- archiver,
363
- dateProvider,
364
- telemetry,
365
- );
366
-
367
- let validatorClient: ValidatorClient | undefined;
632
+ };
368
633
 
369
- if (!proverOnly) {
370
- // Create validator client if required
371
- validatorClient = await createValidatorClient(config, {
372
- checkpointsBuilder: validatorCheckpointsBuilder,
373
- worldState: worldStateSynchronizer,
374
- p2pClient,
375
- telemetry,
376
- dateProvider,
377
- epochCache,
378
- blockSource: archiver,
379
- l1ToL2MessageSource: archiver,
380
- keyStoreManager,
381
- blobClient,
382
- slashingProtectionDb: deps.slashingProtectionDb,
383
- });
634
+ const globalVariableBuilder = new GlobalVariableBuilder(dateProvider, publicClient, globalVariableBuilderConfig);
635
+ const feeProvider = new FeeProviderImpl(dateProvider, publicClient, globalVariableBuilderConfig);
384
636
 
385
- // If we have a validator client, register it as a source of offenses for the slasher,
386
- // and have it register callbacks on the p2p client *before* we start it, otherwise messages
387
- // like attestations or auths will fail.
388
- if (validatorClient) {
389
- watchers.push(validatorClient);
390
- if (!options.dontStartSequencer) {
391
- await validatorClient.registerHandlers();
392
- }
637
+ const proverOnly = config.enableProverNode && config.disableValidator;
638
+ if (proverOnly) {
639
+ log.info('Starting in prover-only mode: skipping validator, sequencer, sentinel, and slasher subsystems');
393
640
  }
394
- }
395
641
 
396
- // If there's no validator client, create a BlockProposalHandler to handle block proposals
397
- // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
398
- // while non-reexecution is used for validating the proposals and collecting their txs.
399
- if (!validatorClient) {
400
- const reexecute = !!config.alwaysReexecuteBlockProposals;
401
- log.info(`Setting up block proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
402
- createBlockProposalHandler(config, {
403
- checkpointsBuilder: validatorCheckpointsBuilder,
404
- worldState: worldStateSynchronizer,
642
+ // create the tx pool and the p2p client, which will need the l2 block source
643
+ const p2pClient = await createP2PClient(
644
+ config,
645
+ archiver,
646
+ peerProofVerifier,
647
+ worldStateSynchronizer,
405
648
  epochCache,
406
- blockSource: archiver,
407
- l1ToL2MessageSource: archiver,
408
- p2pClient,
649
+ feeProvider,
650
+ packageVersion,
409
651
  dateProvider,
410
652
  telemetry,
411
- }).register(p2pClient, reexecute);
412
- }
653
+ deps.p2pClientDeps,
654
+ initialBlockHash,
655
+ );
656
+ started.push(p2pClient);
657
+
658
+ // We'll accumulate sentinel watchers here
659
+ const watchers: Watcher[] = [];
660
+
661
+ // Create FullNodeCheckpointsBuilder for block proposal handling and tx validation.
662
+ // Override maxTxsPerCheckpoint with the validator-specific limit if set.
663
+ const validatorCheckpointsBuilder = new FullNodeCheckpointsBuilder(
664
+ {
665
+ ...config,
666
+ l1GenesisTime,
667
+ slotDuration: Number(slotDuration),
668
+ rollupManaLimit,
669
+ maxTxsPerCheckpoint: config.validateMaxTxsPerCheckpoint,
670
+ },
671
+ worldStateSynchronizer,
672
+ archiver,
673
+ dateProvider,
674
+ telemetry,
675
+ );
413
676
 
414
- // Start world state and wait for it to sync to the archiver.
415
- await worldStateSynchronizer.start();
677
+ let validatorClient: ValidatorClient | undefined;
416
678
 
417
- // Start p2p. Note that it depends on world state to be running.
418
- await p2pClient.start();
679
+ // Tracks successful checkpoint re-execution by a checkpoint proposal handler.
680
+ const reexecutionTracker = new CheckpointReexecutionTracker();
419
681
 
420
- let validatorsSentinel: Awaited<ReturnType<typeof createSentinel>> | undefined;
421
- let epochPruneWatcher: EpochPruneWatcher | undefined;
422
- let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
682
+ if (!config.disableValidator) {
683
+ // Create validator client if required
684
+ validatorClient = await createValidatorClient(config, {
685
+ checkpointsBuilder: validatorCheckpointsBuilder,
686
+ worldState: worldStateSynchronizer,
687
+ p2pClient,
688
+ telemetry,
689
+ dateProvider,
690
+ epochCache,
691
+ blockSource: archiver,
692
+ l1ToL2MessageSource: archiver,
693
+ keyStoreManager,
694
+ blobClient,
695
+ reexecutionTracker,
696
+ slashingProtectionDb: deps.slashingProtectionDb,
697
+ });
698
+
699
+ // If we have a validator client, register it as a source of offenses for the slasher,
700
+ // and have it register callbacks on the p2p client *before* we start it, otherwise messages
701
+ // like attestations or auths will fail.
702
+ if (validatorClient) {
703
+ watchers.push(validatorClient);
704
+
705
+ const vc = validatorClient;
706
+ const getValidatorAddresses = () => vc.getValidatorAddresses().map(a => a.toString());
707
+ validatorClient.getProposalHandler().register(p2pClient, true, archiver, getValidatorAddresses);
708
+
709
+ if (!options.dontStartSequencer) {
710
+ await validatorClient.registerHandlers();
711
+ }
712
+ }
713
+ }
423
714
 
424
- if (!proverOnly) {
425
- validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
426
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
427
- watchers.push(validatorsSentinel);
715
+ // If there's no validator client, create a ProposalHandler to handle block and checkpoint proposals
716
+ // for monitoring or reexecution. Reexecution (default) allows us to follow the pending chain,
717
+ // while non-reexecution is used for validating the proposals and collecting their txs.
718
+ // Checkpoint proposals rebuild blobs if the blob client can upload blobs.
719
+ if (!validatorClient) {
720
+ const reexecute = !!config.alwaysReexecuteBlockProposals;
721
+ log.info(`Setting up proposal handler` + (reexecute ? ' with reexecution of proposals' : ''));
722
+ createProposalHandler(config, {
723
+ checkpointsBuilder: validatorCheckpointsBuilder,
724
+ worldState: worldStateSynchronizer,
725
+ epochCache,
726
+ blockSource: archiver,
727
+ l1ToL2MessageSource: archiver,
728
+ p2pClient,
729
+ blobClient,
730
+ dateProvider,
731
+ telemetry,
732
+ reexecutionTracker,
733
+ }).register(p2pClient, reexecute, archiver);
428
734
  }
429
735
 
430
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
431
- epochPruneWatcher = new EpochPruneWatcher(
736
+ // Start world state and wait for it to sync to the archiver.
737
+ await worldStateSynchronizer.start();
738
+
739
+ // Start p2p. Note that it depends on world state to be running.
740
+ await p2pClient.start();
741
+
742
+ let validatorsSentinel: Awaited<ReturnType<typeof createSentinel>> | undefined;
743
+ let dataWithholdingWatcher: DataWithholdingWatcher | undefined;
744
+ let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
745
+ let attestedInvalidProposalWatcher: AttestedInvalidProposalWatcher | undefined;
746
+ let broadcastedInvalidCheckpointProposalWatcher: BroadcastedInvalidCheckpointProposalWatcher | undefined;
747
+ let checkpointEquivocationWatcher: CheckpointEquivocationWatcher | undefined;
748
+
749
+ if (!proverOnly) {
750
+ validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, reexecutionTracker, config);
751
+ if (validatorsSentinel) {
752
+ watchers.push(validatorsSentinel);
753
+ }
754
+
755
+ dataWithholdingWatcher = new DataWithholdingWatcher(
756
+ epochCache,
432
757
  archiver,
758
+ p2pClient.getTxProvider(),
759
+ p2pClient,
760
+ reexecutionTracker,
761
+ { chainId: config.l1ChainId, rollupAddress: config.rollupAddress },
762
+ config,
763
+ );
764
+ watchers.push(dataWithholdingWatcher);
765
+
766
+ broadcastedInvalidCheckpointProposalWatcher = new BroadcastedInvalidCheckpointProposalWatcher(
767
+ p2pClient,
433
768
  archiver,
434
769
  epochCache,
435
- p2pClient.getTxProvider(),
436
- validatorCheckpointsBuilder,
437
770
  config,
438
771
  );
439
- watchers.push(epochPruneWatcher);
440
- }
772
+ watchers.push(broadcastedInvalidCheckpointProposalWatcher);
773
+
774
+ if (validatorClient) {
775
+ attestedInvalidProposalWatcher = new AttestedInvalidProposalWatcher(
776
+ p2pClient,
777
+ validatorClient,
778
+ archiver,
779
+ epochCache,
780
+ config,
781
+ { log: log.createChild('attested-invalid-proposal-watcher') },
782
+ );
783
+ watchers.push(attestedInvalidProposalWatcher);
784
+ }
785
+
786
+ checkpointEquivocationWatcher = new CheckpointEquivocationWatcher(archiver, epochCache, config);
787
+ watchers.push(checkpointEquivocationWatcher);
441
788
 
442
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
443
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
444
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
789
+ attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config, log.getBindings());
445
790
  watchers.push(attestationsBlockWatcher);
446
791
  }
447
- }
448
792
 
449
- // Start p2p-related services once the archiver has completed sync
450
- void archiver
451
- .waitForInitialSync()
452
- .then(async () => {
453
- await p2pClient.start();
454
- await validatorsSentinel?.start();
455
- await epochPruneWatcher?.start();
456
- await attestationsBlockWatcher?.start();
457
- log.info(`All p2p services started`);
458
- })
459
- .catch(err => log.error('Failed to start p2p services after archiver sync', err));
460
-
461
- // Validator enabled, create/start relevant service
462
- let sequencer: SequencerClient | undefined;
463
- let slasherClient: SlasherClientInterface | undefined;
464
- if (!config.disableValidator && validatorClient) {
465
- // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
466
- // as they are executed when the node is selected as proposer.
467
- const validatorAddresses = keyStoreManager
468
- ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses()
469
- : [];
470
-
471
- slasherClient = await createSlasher(
472
- config,
473
- config.l1Contracts,
474
- getPublicClient(config),
475
- watchers,
476
- dateProvider,
477
- epochCache,
478
- validatorAddresses,
479
- undefined, // logger
480
- );
481
- await slasherClient.start();
793
+ const watchersToStart = compactArray([
794
+ validatorsSentinel,
795
+ dataWithholdingWatcher,
796
+ attestationsBlockWatcher,
797
+ broadcastedInvalidCheckpointProposalWatcher,
798
+ attestedInvalidProposalWatcher,
799
+ checkpointEquivocationWatcher,
800
+ ]);
801
+ const startedWatchers: Watcher[] = [];
802
+ const stopStartedWatchers = async () => {
803
+ for (const watcher of startedWatchers) {
804
+ await tryStop(watcher);
805
+ }
806
+ };
482
807
 
483
- const l1TxUtils = config.sequencerPublisherForwarderAddress
484
- ? await createForwarderL1TxUtilsFromSigners(
485
- publicClient,
486
- keyStoreManager!.createAllValidatorPublisherSigners(),
487
- config.sequencerPublisherForwarderAddress,
488
- { ...config, scope: 'sequencer' },
489
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
490
- )
491
- : await createL1TxUtilsFromSigners(
808
+ // Start p2p-related services once the archiver has completed sync
809
+ void archiver
810
+ .waitForInitialSync()
811
+ .then(async () => {
812
+ for (const watcher of watchersToStart) {
813
+ await watcher.start();
814
+ startedWatchers.push(watcher);
815
+ }
816
+ log.info(`All p2p services started`);
817
+ })
818
+ .catch(err => log.error('Failed to start p2p services after archiver sync', err));
819
+ started.push({ stop: stopStartedWatchers });
820
+
821
+ // Validator enabled, create/start relevant service
822
+ let sequencer: SequencerClient | undefined;
823
+ let automineSequencer: AutomineSequencer | undefined;
824
+ let slasherClient: SlasherClientInterface | undefined;
825
+ if (!config.disableValidator && validatorClient) {
826
+ // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
827
+ // as they are executed when the node is selected as proposer.
828
+ const validatorAddresses = keyStoreManager
829
+ ? NodeKeystoreAdapter.fromKeyStoreManager(keyStoreManager).getAddresses()
830
+ : [];
831
+
832
+ slasherClient = await createSlasher(
833
+ config,
834
+ pickL1ContractAddresses(config),
835
+ getPublicClient(config),
836
+ watchers,
837
+ dateProvider,
838
+ epochCache,
839
+ validatorAddresses,
840
+ undefined, // logger
841
+ );
842
+ await slasherClient.start();
843
+ started.push(slasherClient);
844
+
845
+ const l1TxUtils = config.sequencerPublisherForwarderAddress
846
+ ? await createForwarderL1TxUtilsFromSigners(
847
+ publicClient,
848
+ keyStoreManager!.createAllValidatorPublisherSigners(),
849
+ config.sequencerPublisherForwarderAddress,
850
+ { ...config, scope: 'sequencer' },
851
+ { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
852
+ )
853
+ : await createL1TxUtilsFromSigners(
854
+ publicClient,
855
+ keyStoreManager!.createAllValidatorPublisherSigners(),
856
+ { ...config, scope: 'sequencer' },
857
+ { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
858
+ );
859
+
860
+ // Create a funder L1TxUtils from the keystore funding account (if configured)
861
+ const fundingSigner = keyStoreManager?.createFundingSigner();
862
+ let funderL1TxUtils: L1TxUtils | undefined;
863
+ if (fundingSigner) {
864
+ const [funder] = await createL1TxUtilsFromSigners(
492
865
  publicClient,
493
- keyStoreManager!.createAllValidatorPublisherSigners(),
866
+ [fundingSigner],
494
867
  { ...config, scope: 'sequencer' },
495
- { telemetry, logger: log.createChild('l1-tx-utils'), dateProvider, kzg: Blob.getViemKzgInstance() },
868
+ { telemetry, logger: log.createChild('l1-tx-utils:funder'), dateProvider },
496
869
  );
870
+ funderL1TxUtils = funder;
871
+ }
497
872
 
498
- // Create and start the sequencer client
499
- const checkpointsBuilder = new CheckpointsBuilder(
500
- { ...config, l1GenesisTime, slotDuration: Number(slotDuration), rollupManaLimit },
501
- worldStateSynchronizer,
502
- archiver,
503
- dateProvider,
504
- telemetry,
505
- debugLogStore,
506
- );
873
+ // Create and start the sequencer client
874
+ const checkpointsBuilder = new CheckpointsBuilder(
875
+ { ...config, l1GenesisTime, slotDuration: Number(slotDuration), rollupManaLimit },
876
+ worldStateSynchronizer,
877
+ archiver,
878
+ dateProvider,
879
+ telemetry,
880
+ debugLogStore,
881
+ );
507
882
 
508
- sequencer = await SequencerClient.new(config, {
509
- ...deps,
510
- epochCache,
511
- l1TxUtils,
512
- validatorClient,
513
- p2pClient,
514
- worldStateSynchronizer,
515
- slasherClient,
516
- checkpointsBuilder,
517
- l2BlockSource: archiver,
518
- l1ToL2MessageSource: archiver,
519
- telemetry,
520
- dateProvider,
521
- blobClient,
522
- nodeKeyStore: keyStoreManager!,
523
- });
524
- }
883
+ if (config.useAutomineSequencer) {
884
+ // Test-only path: deterministic, queue-driven sequencer for non-block-building e2e tests.
885
+ // See `AUTOMINE_E2E_OPTS` in `end-to-end/src/fixtures/fixtures.ts`.
886
+ automineSequencer = await createAutomineSequencer({
887
+ config,
888
+ l1TxUtils,
889
+ funderL1TxUtils,
890
+ publicClient,
891
+ rollupContract,
892
+ epochCache,
893
+ blobClient,
894
+ telemetry,
895
+ dateProvider,
896
+ keyStoreManager: keyStoreManager!,
897
+ validatorClient,
898
+ checkpointsBuilder,
899
+ globalVariableBuilder,
900
+ worldStateSynchronizer,
901
+ archiver,
902
+ p2pClient,
903
+ l1Constants: {
904
+ l1GenesisTime,
905
+ slotDuration: Number(slotDuration),
906
+ ethereumSlotDuration: config.ethereumSlotDuration,
907
+ rollupManaLimit,
908
+ },
909
+ log,
910
+ });
911
+ } else {
912
+ sequencer = await SequencerClient.new(config, {
913
+ ...deps,
914
+ epochCache,
915
+ l1TxUtils,
916
+ funderL1TxUtils,
917
+ validatorClient,
918
+ p2pClient,
919
+ worldStateSynchronizer,
920
+ slasherClient,
921
+ checkpointsBuilder,
922
+ l2BlockSource: archiver,
923
+ l1ToL2MessageSource: archiver,
924
+ telemetry,
925
+ dateProvider,
926
+ blobClient,
927
+ nodeKeyStore: keyStoreManager!,
928
+ globalVariableBuilder,
929
+ });
930
+ }
931
+ }
525
932
 
526
- if (!options.dontStartSequencer && sequencer) {
527
- await sequencer.start();
528
- log.verbose(`Sequencer started`);
529
- } else if (sequencer) {
530
- log.warn(`Sequencer created but not started`);
531
- }
933
+ if (!options.dontStartSequencer && sequencer) {
934
+ await sequencer.start();
935
+ started.push(sequencer);
936
+ log.verbose(`Sequencer started`);
937
+ } else if (sequencer) {
938
+ log.warn(`Sequencer created but not started`);
939
+ }
532
940
 
533
- // Create prover node subsystem if enabled
534
- let proverNode: ProverNode | undefined;
535
- if (config.enableProverNode) {
536
- proverNode = await createProverNode(config, {
537
- ...deps.proverNodeDeps,
538
- telemetry,
539
- dateProvider,
941
+ if (!options.dontStartSequencer && automineSequencer) {
942
+ await automineSequencer.start();
943
+ started.push({ stop: () => automineSequencer!.stop() });
944
+ log.verbose(`AutomineSequencer started`);
945
+ } else if (automineSequencer) {
946
+ log.warn(`AutomineSequencer created but not started`);
947
+ }
948
+
949
+ // Create prover node subsystem if enabled
950
+ let proverNode: ProverNode | undefined;
951
+ if (config.enableProverNode) {
952
+ proverNode = await createProverNode(config, {
953
+ ...deps.proverNodeDeps,
954
+ telemetry,
955
+ dateProvider,
956
+ archiver,
957
+ worldStateSynchronizer,
958
+ p2pClient,
959
+ epochCache,
960
+ blobClient,
961
+ keyStoreManager,
962
+ });
963
+
964
+ if (!options.dontStartProverNode) {
965
+ await proverNode.start();
966
+ started.push(proverNode);
967
+ log.info(`Prover node subsystem started`);
968
+ } else {
969
+ log.info(`Prover node subsystem created but not started`);
970
+ }
971
+ }
972
+
973
+ const node = new AztecNodeService(
974
+ config,
975
+ p2pClient,
976
+ archiver,
977
+ archiver,
978
+ archiver,
540
979
  archiver,
541
980
  worldStateSynchronizer,
542
- p2pClient,
981
+ sequencer,
982
+ proverNode,
983
+ slasherClient,
984
+ validatorsSentinel,
985
+ stopStartedWatchers,
986
+ ethereumChain.chainInfo.id,
987
+ config.rollupVersion,
988
+ globalVariableBuilder,
989
+ feeProvider,
543
990
  epochCache,
991
+ packageVersion,
992
+ peerProofVerifier,
993
+ rpcProofVerifier,
994
+ telemetry,
995
+ log,
544
996
  blobClient,
997
+ validatorClient,
545
998
  keyStoreManager,
546
- });
999
+ debugLogStore,
1000
+ automineSequencer,
1001
+ );
547
1002
 
548
- if (!options.dontStartProverNode) {
549
- await proverNode.start();
550
- log.info(`Prover node subsystem started`);
551
- } else {
552
- log.info(`Prover node subsystem created but not started`);
1003
+ return node;
1004
+ } catch (err) {
1005
+ log.error('Failed during node creation, stopping started resources', err);
1006
+ for (const resource of started.reverse()) {
1007
+ await tryStop(resource);
553
1008
  }
1009
+ throw err;
554
1010
  }
555
-
556
- const globalVariableBuilder = new GlobalVariableBuilder({
557
- ...config,
558
- rollupVersion: BigInt(config.rollupVersion),
559
- l1GenesisTime,
560
- slotDuration: Number(slotDuration),
561
- });
562
-
563
- const node = new AztecNodeService(
564
- config,
565
- p2pClient,
566
- archiver,
567
- archiver,
568
- archiver,
569
- archiver,
570
- worldStateSynchronizer,
571
- sequencer,
572
- proverNode,
573
- slasherClient,
574
- validatorsSentinel,
575
- epochPruneWatcher,
576
- ethereumChain.chainInfo.id,
577
- config.rollupVersion,
578
- globalVariableBuilder,
579
- epochCache,
580
- packageVersion,
581
- proofVerifier,
582
- telemetry,
583
- log,
584
- blobClient,
585
- validatorClient,
586
- keyStoreManager,
587
- debugLogStore,
588
- );
589
-
590
- return node;
591
1011
  }
592
1012
 
593
1013
  /**
@@ -598,6 +1018,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
598
1018
  return this.sequencer;
599
1019
  }
600
1020
 
1021
+ /** Test-only: returns the AutomineSequencer when wired via `useAutomineSequencer`. */
1022
+ public getAutomineSequencer(): AutomineSequencer | undefined {
1023
+ return this.automineSequencer;
1024
+ }
1025
+
601
1026
  /** Returns the prover node subsystem, if enabled. */
602
1027
  public getProverNode(): ProverNode | undefined {
603
1028
  return this.proverNode;
@@ -620,7 +1045,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
620
1045
  * @returns - The currently deployed L1 contract addresses.
621
1046
  */
622
1047
  public getL1ContractAddresses(): Promise<L1ContractAddresses> {
623
- return Promise.resolve(this.config.l1Contracts);
1048
+ return Promise.resolve(pickL1ContractAddresses(this.config));
624
1049
  }
625
1050
 
626
1051
  public getEncodedEnr(): Promise<string | undefined> {
@@ -662,77 +1087,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
662
1087
  return nodeInfo;
663
1088
  }
664
1089
 
665
- /**
666
- * Get a block specified by its block number, block hash, or 'latest'.
667
- * @param block - The block parameter (block number, block hash, or 'latest').
668
- * @returns The requested block.
669
- */
670
- public async getBlock(block: BlockParameter): Promise<L2Block | undefined> {
671
- if (BlockHash.isBlockHash(block)) {
672
- return this.getBlockByHash(block);
673
- }
674
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
675
- if (blockNumber === BlockNumber.ZERO) {
676
- return this.buildInitialBlock();
677
- }
678
- return await this.blockSource.getL2Block(blockNumber);
679
- }
680
-
681
- /**
682
- * Get a block specified by its hash.
683
- * @param blockHash - The block hash being requested.
684
- * @returns The requested block.
685
- */
686
- public async getBlockByHash(blockHash: BlockHash): Promise<L2Block | undefined> {
687
- const initialBlockHash = await this.#getInitialHeaderHash();
688
- if (blockHash.equals(initialBlockHash)) {
689
- return this.buildInitialBlock();
690
- }
691
- return await this.blockSource.getL2BlockByHash(blockHash);
692
- }
693
-
694
- private buildInitialBlock(): L2Block {
695
- const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
696
- return L2Block.empty(initialHeader);
697
- }
698
-
699
- /**
700
- * Get a block specified by its archive root.
701
- * @param archive - The archive root being requested.
702
- * @returns The requested block.
703
- */
704
- public async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
705
- return await this.blockSource.getL2BlockByArchive(archive);
706
- }
707
-
708
- /**
709
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
710
- * @param from - The start of the range of blocks to return.
711
- * @param limit - The maximum number of blocks to obtain.
712
- * @returns The blocks requested.
713
- */
714
- public async getBlocks(from: BlockNumber, limit: number): Promise<L2Block[]> {
715
- return (await this.blockSource.getBlocks(from, BlockNumber(limit))) ?? [];
716
- }
717
-
718
- public async getCheckpoints(from: CheckpointNumber, limit: number): Promise<PublishedCheckpoint[]> {
719
- return (await this.blockSource.getCheckpoints(from, limit)) ?? [];
720
- }
721
-
722
- public async getCheckpointedBlocks(from: BlockNumber, limit: number) {
723
- return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
1090
+ public async getCurrentMinFees(): Promise<GasFees> {
1091
+ return await this.feeProvider.getCurrentMinFees();
724
1092
  }
725
1093
 
726
- public getCheckpointsDataForEpoch(epochNumber: EpochNumber) {
727
- return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
728
- }
729
-
730
- /**
731
- * Method to fetch the current min L2 fees.
732
- * @returns The current min L2 fees.
733
- */
734
- public async getCurrentMinFees(): Promise<GasFees> {
735
- return await this.globalVariableBuilder.getCurrentMinFees();
1094
+ /** Returns predicted min fees for the current slot and next N slots. */
1095
+ public async getPredictedMinFees(manaUsage?: ManaUsageEstimate): Promise<GasFees[]> {
1096
+ return await this.feeProvider.getPredictedMinFees(manaUsage);
736
1097
  }
737
1098
 
738
1099
  public async getMaxPriorityFees(): Promise<GasFees> {
@@ -743,26 +1104,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
743
1104
  return GasFees.from({ feePerDaGas: 0n, feePerL2Gas: 0n });
744
1105
  }
745
1106
 
746
- /**
747
- * Method to fetch the latest block number synchronized by the node.
748
- * @returns The block number.
749
- */
750
- public async getBlockNumber(): Promise<BlockNumber> {
751
- return await this.blockSource.getBlockNumber();
752
- }
753
-
754
- public async getProvenBlockNumber(): Promise<BlockNumber> {
755
- return await this.blockSource.getProvenBlockNumber();
756
- }
757
-
758
- public async getCheckpointedBlockNumber(): Promise<BlockNumber> {
759
- return await this.blockSource.getCheckpointedL2BlockNumber();
760
- }
761
-
762
- public getCheckpointNumber(): Promise<CheckpointNumber> {
763
- return this.blockSource.getCheckpointNumber();
764
- }
765
-
766
1107
  /**
767
1108
  * Method to fetch the version of the package.
768
1109
  * @returns The node package version
@@ -795,69 +1136,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
795
1136
  return this.contractDataSource.getContract(address);
796
1137
  }
797
1138
 
798
- public async getPrivateLogsByTags(
799
- tags: SiloedTag[],
800
- page?: number,
801
- referenceBlock?: BlockHash,
802
- ): Promise<TxScopedL2Log[][]> {
803
- let upToBlockNumber: BlockNumber | undefined;
804
- if (referenceBlock) {
805
- const initialBlockHash = await this.#getInitialHeaderHash();
806
- if (referenceBlock.equals(initialBlockHash)) {
807
- upToBlockNumber = BlockNumber(0);
808
- } else {
809
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
810
- if (!header) {
811
- throw new Error(
812
- `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
813
- );
814
- }
815
- upToBlockNumber = header.globalVariables.blockNumber;
816
- }
817
- }
818
- return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
1139
+ public getPrivateLogsByTags(query: PrivateLogsQuery): Promise<LogResult[][]> {
1140
+ return this.logsSource.getPrivateLogsByTags(query);
819
1141
  }
820
1142
 
821
- public async getPublicLogsByTagsFromContract(
822
- contractAddress: AztecAddress,
823
- tags: Tag[],
824
- page?: number,
825
- referenceBlock?: BlockHash,
826
- ): Promise<TxScopedL2Log[][]> {
827
- let upToBlockNumber: BlockNumber | undefined;
828
- if (referenceBlock) {
829
- const initialBlockHash = await this.#getInitialHeaderHash();
830
- if (referenceBlock.equals(initialBlockHash)) {
831
- upToBlockNumber = BlockNumber(0);
832
- } else {
833
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
834
- if (!header) {
835
- throw new Error(
836
- `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
837
- );
838
- }
839
- upToBlockNumber = header.globalVariables.blockNumber;
840
- }
841
- }
842
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
843
- }
844
-
845
- /**
846
- * Gets public logs based on the provided filter.
847
- * @param filter - The filter to apply to the logs.
848
- * @returns The requested logs.
849
- */
850
- getPublicLogs(filter: LogFilter): Promise<GetPublicLogsResponse> {
851
- return this.logsSource.getPublicLogs(filter);
852
- }
853
-
854
- /**
855
- * Gets contract class logs based on the provided filter.
856
- * @param filter - The filter to apply to the logs.
857
- * @returns The requested logs.
858
- */
859
- getContractClassLogs(filter: LogFilter): Promise<GetContractClassLogsResponse> {
860
- return this.logsSource.getContractClassLogs(filter);
1143
+ public getPublicLogsByTags(query: PublicLogsQuery): Promise<LogResult[][]> {
1144
+ return this.logsSource.getPublicLogsByTags(query);
861
1145
  }
862
1146
 
863
1147
  /**
@@ -880,7 +1164,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
880
1164
  throw new Error(`Invalid tx: ${reason}`);
881
1165
  }
882
1166
 
883
- await this.p2pClient!.sendTx(tx);
1167
+ try {
1168
+ await this.p2pClient!.sendTx(tx);
1169
+ } catch (err) {
1170
+ this.metrics.receivedTx(timer.ms(), false);
1171
+ this.log.warn(`Mempool rejected tx ${txHash}: ${(err as Error).message}`, { txHash });
1172
+ throw err;
1173
+ }
884
1174
  const duration = timer.ms();
885
1175
  this.metrics.receivedTx(duration, true);
886
1176
  this.log.info(`Received tx ${txHash} in ${duration}ms`, { txHash });
@@ -902,10 +1192,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
902
1192
  // If the tx is in the pool but not in the archiver, it's pending.
903
1193
  // This handles race conditions between archiver and p2p, where the archiver
904
1194
  // has pruned the block in which a tx was mined, but p2p has not caught up yet.
905
- receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
1195
+ receipt = new TxReceipt(txHash, TxStatus.PENDING, /*executionResult=*/ undefined, /*error=*/ undefined);
906
1196
  } else {
907
1197
  // Otherwise, if we don't know the tx, we consider it dropped.
908
- receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
1198
+ receipt = new TxReceipt(
1199
+ txHash,
1200
+ TxStatus.DROPPED,
1201
+ /*executionResult=*/ undefined,
1202
+ /*error=*/ 'Tx dropped by P2P node',
1203
+ );
909
1204
  }
910
1205
 
911
1206
  this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
@@ -922,11 +1217,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
922
1217
  */
923
1218
  public async stop() {
924
1219
  this.log.info(`Stopping Aztec Node`);
925
- await tryStop(this.validatorsSentinel);
926
- await tryStop(this.epochPruneWatcher);
1220
+ await this.stopStartedWatchers();
927
1221
  await tryStop(this.slasherClient);
928
- await tryStop(this.proofVerifier);
1222
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
929
1223
  await tryStop(this.sequencer);
1224
+ await tryStop(this.automineSequencer);
930
1225
  await tryStop(this.proverNode);
931
1226
  await tryStop(this.p2pClient);
932
1227
  await tryStop(this.worldStateSynchronizer);
@@ -1015,7 +1310,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1015
1310
  );
1016
1311
 
1017
1312
  // Build a map from block number to block hash
1018
- const blockNumberToHash = new Map<BlockNumber, Fr>();
1313
+ const blockNumberToHash = new Map<BlockNumber, BlockHash>();
1019
1314
  for (let i = 0; i < uniqueBlockNumbers.length; i++) {
1020
1315
  const blockHash = blockHashes[i];
1021
1316
  if (blockHash === undefined) {
@@ -1033,13 +1328,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1033
1328
  if (blockNumber === undefined) {
1034
1329
  throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
1035
1330
  }
1036
- const blockHash = blockNumberToHash.get(blockNumber);
1037
- if (blockHash === undefined) {
1331
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
1332
+ if (l2BlockHash === undefined) {
1038
1333
  throw new Error(`Block hash not found for block number ${blockNumber}`);
1039
1334
  }
1040
1335
  return {
1041
1336
  l2BlockNumber: blockNumber,
1042
- l2BlockHash: new BlockHash(blockHash),
1337
+ l2BlockHash,
1043
1338
  data: index,
1044
1339
  };
1045
1340
  });
@@ -1053,6 +1348,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1053
1348
  // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
1054
1349
  // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
1055
1350
  const referenceBlockNumber = await this.resolveBlockNumber(referenceBlock);
1351
+ if (referenceBlockNumber === BlockNumber.ZERO) {
1352
+ // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
1353
+ return undefined;
1354
+ }
1056
1355
  const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
1057
1356
  const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
1058
1357
  return pathAndIndex === undefined
@@ -1090,17 +1389,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1090
1389
 
1091
1390
  public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
1092
1391
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1093
- return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1094
- }
1095
-
1096
- /**
1097
- * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
1098
- * @param l1ToL2Message - The L1 to L2 message to check.
1099
- * @returns Whether the message is synced and ready to be included in a block.
1100
- */
1101
- public async isL1ToL2MessageSynced(l1ToL2Message: Fr): Promise<boolean> {
1102
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1103
- return messageIndex !== undefined;
1392
+ return messageIndex !== undefined ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1104
1393
  }
1105
1394
 
1106
1395
  /**
@@ -1109,13 +1398,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1109
1398
  * @returns The L2 to L1 messages (empty array if the epoch is not found).
1110
1399
  */
1111
1400
  public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
1112
- // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1113
- const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1114
- const blocksInCheckpoints = chunkBy(checkpointedBlocks, cb => cb.block.header.globalVariables.slotNumber).map(
1115
- group => group.map(cb => cb.block),
1116
- );
1117
- return blocksInCheckpoints.map(blocks =>
1118
- blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1401
+ const blocks = await this.blockSource.getBlocks({ epoch, onlyCheckpointed: true });
1402
+ const blocksInCheckpoints = chunkBy(blocks, block => block.header.globalVariables.slotNumber);
1403
+ return blocksInCheckpoints.map(slotBlocks =>
1404
+ slotBlocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1119
1405
  );
1120
1406
  }
1121
1407
 
@@ -1189,49 +1475,20 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1189
1475
  return preimage.leaf.value;
1190
1476
  }
1191
1477
 
1192
- public async getBlockHeader(block: BlockParameter = 'latest'): Promise<BlockHeader | undefined> {
1193
- if (BlockHash.isBlockHash(block)) {
1194
- const initialBlockHash = await this.#getInitialHeaderHash();
1195
- if (block.equals(initialBlockHash)) {
1196
- // Block source doesn't handle initial header so we need to handle the case separately.
1197
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1198
- }
1199
- return this.blockSource.getBlockHeaderByHash(block);
1200
- } else {
1201
- // Block source doesn't handle initial header so we need to handle the case separately.
1202
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
1203
- if (blockNumber === BlockNumber.ZERO) {
1204
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1205
- }
1206
- return this.blockSource.getBlockHeader(block);
1207
- }
1208
- }
1209
-
1210
- /**
1211
- * Get a block header specified by its archive root.
1212
- * @param archive - The archive root being requested.
1213
- * @returns The requested block header.
1214
- */
1215
- public async getBlockHeaderByArchive(archive: Fr): Promise<BlockHeader | undefined> {
1216
- return await this.blockSource.getBlockHeaderByArchive(archive);
1217
- }
1218
-
1219
- public getBlockData(number: BlockNumber): Promise<BlockData | undefined> {
1220
- return this.blockSource.getBlockData(number);
1221
- }
1222
-
1223
- public getBlockDataByArchive(archive: Fr): Promise<BlockData | undefined> {
1224
- return this.blockSource.getBlockDataByArchive(archive);
1225
- }
1226
-
1227
1478
  /**
1228
1479
  * Simulates the public part of a transaction with the current state.
1229
1480
  * @param tx - The transaction to simulate.
1481
+ * @param skipFeeEnforcement - If true, fee enforcement is skipped.
1482
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
1230
1483
  **/
1231
1484
  @trackSpan('AztecNodeService.simulatePublicCalls', (tx: Tx) => ({
1232
1485
  [Attributes.TX_HASH]: tx.getTxHash().toString(),
1233
1486
  }))
1234
- public async simulatePublicCalls(tx: Tx, skipFeeEnforcement = false): Promise<PublicSimulationOutput> {
1487
+ public async simulatePublicCalls(
1488
+ tx: Tx,
1489
+ skipFeeEnforcement = false,
1490
+ overrides?: SimulationOverrides,
1491
+ ): Promise<PublicSimulationOutput> {
1235
1492
  // Check total gas limit for simulation
1236
1493
  const gasSettings = tx.data.constants.txContext.gasSettings;
1237
1494
  const txGasLimit = gasSettings.gasLimits.l2Gas;
@@ -1247,7 +1504,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1247
1504
  }
1248
1505
 
1249
1506
  const txHash = tx.getTxHash();
1250
- const latestBlockNumber = await this.blockSource.getBlockNumber();
1507
+ const l2Tips = await this.blockSource.getL2Tips();
1508
+ const latestBlockNumber = l2Tips.proposed.number;
1251
1509
  const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1252
1510
 
1253
1511
  // If sequencer is not initialized, we just set these values to zero for simulation.
@@ -1259,6 +1517,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1259
1517
  coinbase,
1260
1518
  feeRecipient,
1261
1519
  );
1520
+
1262
1521
  const publicProcessorFactory = new PublicProcessorFactory(
1263
1522
  this.contractDataSource,
1264
1523
  new DateProvider(),
@@ -1274,40 +1533,77 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1274
1533
 
1275
1534
  // Ensure world-state has caught up with the latest block we loaded from the archiver
1276
1535
  await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1277
- const merkleTreeFork = await this.worldStateSynchronizer.fork();
1278
- try {
1279
- const config = PublicSimulatorConfig.from({
1280
- skipFeeEnforcement,
1281
- collectDebugLogs: true,
1282
- collectHints: false,
1283
- collectCallMetadata: true,
1284
- collectStatistics: false,
1285
- collectionLimits: CollectionLimitsConfig.from({
1286
- maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads,
1287
- }),
1288
- });
1289
- const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1290
-
1291
- // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1292
- const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1293
- // REFACTOR: Consider returning the error rather than throwing
1294
- if (failedTxs.length) {
1295
- this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
1296
- throw failedTxs[0].error;
1297
- }
1298
1536
 
1299
- const [processedTx] = processedTxs;
1300
- return new PublicSimulationOutput(
1301
- processedTx.revertReason,
1302
- processedTx.globalVariables,
1303
- processedTx.txEffect,
1304
- returns,
1305
- processedTx.gasUsed,
1306
- debugLogs,
1537
+ // If we detect the next block would start a new checkpoint, then insert L1-to-L2 messages into
1538
+ // the world state tree so simulation can take them into account. We detect if the next block would
1539
+ // start a new checkpoint by checking if the proposed checkpoint's block number matches the latest block number,
1540
+ // which means the next block would be the first block of the next checkpoint.
1541
+ const targetCheckpoint = CheckpointNumber(
1542
+ (l2Tips.proposedCheckpoint.checkpoint.number ?? CheckpointNumber.ZERO) + 1,
1543
+ );
1544
+ const nextCheckpointMessages: Fr[] | undefined =
1545
+ l2Tips.proposedCheckpoint.block.number === l2Tips.proposed.number
1546
+ ? await this.l1ToL2MessageSource.getL1ToL2Messages(targetCheckpoint).catch(err => {
1547
+ if (isErrorClass(err, L1ToL2MessagesNotReadyError)) {
1548
+ this.log.warn(
1549
+ `L1-to-L2 messages for checkpoint ${targetCheckpoint} are not ready yet (simulating without them)`,
1550
+ );
1551
+ } else {
1552
+ this.log.error(
1553
+ `Failed to get L1-to-L2 messages for checkpoint ${targetCheckpoint} (simulating without them)`,
1554
+ err,
1555
+ );
1556
+ }
1557
+ return undefined;
1558
+ })
1559
+ : undefined;
1560
+
1561
+ // Request a new fork of the world state at the latest block number, and apply any overrides and next checkpoint messages to it before simulation
1562
+ await using merkleTreeFork = await this.worldStateSynchronizer.fork(latestBlockNumber);
1563
+
1564
+ if (nextCheckpointMessages !== undefined) {
1565
+ this.log.debug(
1566
+ `Appending ${nextCheckpointMessages.length} L1-to-L2 messages to the world state tree for the next checkpoint`,
1567
+ { checkpointNumber: l2Tips.proposedCheckpoint.checkpoint.number + 1 },
1307
1568
  );
1308
- } finally {
1309
- await merkleTreeFork.close();
1569
+ await appendL1ToL2MessagesToTree(merkleTreeFork, nextCheckpointMessages);
1570
+ }
1571
+ await applyPublicDataOverrides(merkleTreeFork, overrides?.publicStorage);
1572
+
1573
+ const config = PublicSimulatorConfig.from({
1574
+ skipFeeEnforcement,
1575
+ collectDebugLogs: true,
1576
+ collectHints: false,
1577
+ collectCallMetadata: true,
1578
+ collectStatistics: false,
1579
+ collectionLimits: CollectionLimitsConfig.from({
1580
+ maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads,
1581
+ }),
1582
+ });
1583
+
1584
+ const contractsDB = new PublicContractsDB(this.contractDataSource, this.log.getBindings());
1585
+ if (overrides?.contracts) {
1586
+ contractsDB.addContracts(Object.values(overrides.contracts).map(({ instance }) => instance));
1310
1587
  }
1588
+ const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config, contractsDB);
1589
+
1590
+ // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1591
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1592
+ // REFACTOR: Consider returning the error rather than throwing
1593
+ if (failedTxs.length) {
1594
+ this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
1595
+ throw failedTxs[0].error;
1596
+ }
1597
+
1598
+ const [processedTx] = processedTxs;
1599
+ return new PublicSimulationOutput(
1600
+ processedTx.revertReason,
1601
+ processedTx.globalVariables,
1602
+ processedTx.txEffect,
1603
+ returns,
1604
+ processedTx.gasUsed,
1605
+ debugLogs,
1606
+ );
1311
1607
  }
1312
1608
 
1313
1609
  public async isValidTx(
@@ -1315,7 +1611,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1315
1611
  { isSimulation, skipFeeEnforcement }: { isSimulation?: boolean; skipFeeEnforcement?: boolean } = {},
1316
1612
  ): Promise<TxValidationResult> {
1317
1613
  const db = this.worldStateSynchronizer.getCommitted();
1318
- const verifier = isSimulation ? undefined : this.proofVerifier;
1614
+ const verifier = isSimulation ? undefined : this.rpcProofVerifier;
1319
1615
 
1320
1616
  // We accept transactions if they are not expired by the next slot (checked based on the ExpirationTimestamp field)
1321
1617
  const { ts: nextSlotTimestamp } = this.epochCache.getEpochAndSlotInNextL1Slot();
@@ -1355,7 +1651,18 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1355
1651
 
1356
1652
  public async setConfig(config: Partial<AztecNodeAdminConfig>): Promise<void> {
1357
1653
  const newConfig = { ...this.config, ...config };
1358
- this.sequencer?.updateConfig(config);
1654
+ // If the sequencer is currently paused via pauseSequencer(), record the caller's desired
1655
+ // minTxsPerBlock as the restore value (so resumeSequencer applies it) and keep the freeze
1656
+ // (MAX_SAFE_INTEGER) applied to the underlying sequencer. Without this guard, forwarding
1657
+ // the new minTxsPerBlock to the sequencer would silently unpause block production while
1658
+ // pauseSequencer() still considers it paused.
1659
+ const sequencerUpdate = { ...config };
1660
+ if (this.sequencerPausedMinTxsPerBlock !== undefined && sequencerUpdate.minTxsPerBlock !== undefined) {
1661
+ this.sequencerPausedMinTxsPerBlock = sequencerUpdate.minTxsPerBlock;
1662
+ delete sequencerUpdate.minTxsPerBlock;
1663
+ }
1664
+ this.sequencer?.updateConfig(sequencerUpdate);
1665
+ this.automineSequencer?.updateConfig(sequencerUpdate);
1359
1666
  this.slasherClient?.updateConfig(config);
1360
1667
  this.validatorsSentinel?.updateConfig(config);
1361
1668
  await this.p2pClient.updateP2PConfig(config);
@@ -1364,7 +1671,15 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1364
1671
  archiver.updateConfig(config);
1365
1672
  }
1366
1673
  if (newConfig.realProofs !== this.config.realProofs) {
1367
- this.proofVerifier = config.realProofs ? await BBCircuitVerifier.new(newConfig) : new TestCircuitVerifier();
1674
+ await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
1675
+ if (newConfig.realProofs) {
1676
+ this.peerProofVerifier = await BatchChonkVerifier.new(newConfig, newConfig.bbChonkVerifyMaxBatch, 'peer');
1677
+ const rpcVerifier = await BBCircuitVerifier.new(newConfig);
1678
+ this.rpcProofVerifier = new QueuedIVCVerifier(rpcVerifier, newConfig.numConcurrentIVCVerifiers);
1679
+ } else {
1680
+ this.peerProofVerifier = new TestCircuitVerifier();
1681
+ this.rpcProofVerifier = new TestCircuitVerifier();
1682
+ }
1368
1683
  }
1369
1684
 
1370
1685
  this.config = newConfig;
@@ -1375,7 +1690,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1375
1690
  classRegistry: ProtocolContractAddress.ContractClassRegistry,
1376
1691
  feeJuice: ProtocolContractAddress.FeeJuice,
1377
1692
  instanceRegistry: ProtocolContractAddress.ContractInstanceRegistry,
1378
- multiCallEntrypoint: ProtocolContractAddress.MultiCallEntrypoint,
1693
+ multiCallEntrypoint: STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS,
1379
1694
  });
1380
1695
  }
1381
1696
 
@@ -1439,7 +1754,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1439
1754
  return Promise.resolve();
1440
1755
  }
1441
1756
 
1442
- public async rollbackTo(targetBlock: BlockNumber, force?: boolean): Promise<void> {
1757
+ public async rollbackTo(targetBlock: BlockNumber, force?: boolean, resumeSync = true): Promise<void> {
1443
1758
  const archiver = this.blockSource as Archiver;
1444
1759
  if (!('rollbackTo' in archiver)) {
1445
1760
  throw new Error('Archiver implementation does not support rollbacks.');
@@ -1469,9 +1784,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1469
1784
  this.log.error(`Error during rollback`, err);
1470
1785
  throw err;
1471
1786
  } finally {
1472
- this.log.info(`Resuming world state and archiver sync.`);
1473
- this.worldStateSynchronizer.resumeSync();
1474
- archiver.resume();
1787
+ if (resumeSync) {
1788
+ this.log.info(`Resuming world state and archiver sync.`);
1789
+ this.worldStateSynchronizer.resumeSync();
1790
+ archiver.resume();
1791
+ } else {
1792
+ this.log.info(`Sync left paused after rollback (resumeSync=false).`);
1793
+ }
1475
1794
  }
1476
1795
  }
1477
1796
 
@@ -1488,11 +1807,39 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1488
1807
  return Promise.resolve();
1489
1808
  }
1490
1809
 
1491
- public getSlashPayloads(): Promise<SlashPayloadRound[]> {
1492
- if (!this.slasherClient) {
1493
- throw new Error(`Slasher client not enabled`);
1810
+ public pauseSequencer(): Promise<void> {
1811
+ if (this.automineSequencer) {
1812
+ this.automineSequencer.pause();
1813
+ return Promise.resolve();
1814
+ }
1815
+ if (this.sequencer) {
1816
+ if (this.sequencerPausedMinTxsPerBlock === undefined) {
1817
+ this.sequencerPausedMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock ?? 0;
1818
+ this.sequencer.updateConfig({ minTxsPerBlock: Number.MAX_SAFE_INTEGER });
1819
+ this.log.info(`Sequencer paused (minTxsPerBlock set to MAX_SAFE_INTEGER)`, {
1820
+ previousMinTxsPerBlock: this.sequencerPausedMinTxsPerBlock,
1821
+ });
1822
+ }
1823
+ return Promise.resolve();
1494
1824
  }
1495
- return this.slasherClient.getSlashPayloads();
1825
+ throw new BadRequestError('Cannot pause sequencer: no sequencer is running');
1826
+ }
1827
+
1828
+ public resumeSequencer(): Promise<void> {
1829
+ if (this.automineSequencer) {
1830
+ this.automineSequencer.resume();
1831
+ return Promise.resolve();
1832
+ }
1833
+ if (this.sequencer) {
1834
+ if (this.sequencerPausedMinTxsPerBlock !== undefined) {
1835
+ const restored = this.sequencerPausedMinTxsPerBlock;
1836
+ this.sequencerPausedMinTxsPerBlock = undefined;
1837
+ this.sequencer.updateConfig({ minTxsPerBlock: restored });
1838
+ this.log.info(`Sequencer resumed (minTxsPerBlock restored)`, { minTxsPerBlock: restored });
1839
+ }
1840
+ return Promise.resolve();
1841
+ }
1842
+ throw new BadRequestError('Cannot resume sequencer: no sequencer is running');
1496
1843
  }
1497
1844
 
1498
1845
  public getSlashOffenses(round: bigint | 'all' | 'current'): Promise<Offense[]> {
@@ -1500,7 +1847,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1500
1847
  throw new Error(`Slasher client not enabled`);
1501
1848
  }
1502
1849
  if (round === 'all') {
1503
- return this.slasherClient.getPendingOffenses();
1850
+ return this.slasherClient.getOffenses();
1504
1851
  } else {
1505
1852
  return this.slasherClient.gatherOffensesForRound(round === 'current' ? undefined : BigInt(round));
1506
1853
  }
@@ -1594,11 +1941,42 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1594
1941
  this.log.info('Keystore reloaded: coinbase, feeRecipient, and attester keys updated');
1595
1942
  }
1596
1943
 
1597
- #getInitialHeaderHash(): Promise<BlockHash> {
1598
- if (!this.initialHeaderHashPromise) {
1599
- this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
1944
+ public async mineBlock(): Promise<void> {
1945
+ if (this.automineSequencer) {
1946
+ await this.automineSequencer.buildEmptyBlock();
1947
+ return;
1948
+ }
1949
+ if (!this.sequencer) {
1950
+ throw new BadRequestError('Cannot mine block: no sequencer is running');
1951
+ }
1952
+
1953
+ const currentBlockNumber = await this.getBlockNumber();
1954
+
1955
+ // Use slot duration + 50% buffer as the timeout so this works on running networks too
1956
+ const { slotDuration } = await this.blockSource.getL1Constants();
1957
+ const timeoutSeconds = Math.ceil(slotDuration * 1.5);
1958
+
1959
+ // Temporarily set minTxsPerBlock to 0 so the sequencer produces a block even with no txs
1960
+ const originalMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock;
1961
+ this.sequencer.updateConfig({ minTxsPerBlock: 0 });
1962
+
1963
+ try {
1964
+ // Trigger the sequencer to produce a block immediately
1965
+ void this.sequencer.trigger();
1966
+
1967
+ // Wait for the new L2 block to appear
1968
+ await retryUntil(
1969
+ async () => {
1970
+ const newBlockNumber = await this.getBlockNumber();
1971
+ return newBlockNumber > currentBlockNumber ? true : undefined;
1972
+ },
1973
+ 'mineBlock',
1974
+ timeoutSeconds,
1975
+ 0.1,
1976
+ );
1977
+ } finally {
1978
+ this.sequencer.updateConfig({ minTxsPerBlock: originalMinTxsPerBlock });
1600
1979
  }
1601
- return this.initialHeaderHashPromise;
1602
1980
  }
1603
1981
 
1604
1982
  /**
@@ -1607,54 +1985,52 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1607
1985
  * @returns An instance of a committed MerkleTreeOperations
1608
1986
  */
1609
1987
  protected async getWorldState(block: BlockParameter) {
1988
+ const query = this.normalizeBlockParameter(block);
1989
+
1990
+ // When the request anchors on a specific block hash, resolve it against the archiver up front and
1991
+ // drive the world-state sync to that exact block number and hash. Resolving against the archiver
1992
+ // first fails fast with a clear reorg error if the hash is unknown, and passing the hash to the
1993
+ // synchronizer makes the sync reorg-aware: it barriers until the archive-tree commit for that block
1994
+ // has landed and verifies it matches the requested fork, instead of syncing to bare latest height
1995
+ // and then racing the snapshot read below against an in-flight archive-tree write.
1996
+ const requestedHash = 'hash' in query ? query.hash : undefined;
1997
+ const anchorBlockNumber = requestedHash !== undefined ? await this.resolveBlockNumber(query) : undefined;
1998
+
1610
1999
  let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1611
2000
  try {
1612
2001
  // Attempt to sync the world state if necessary
1613
- blockSyncedTo = await this.#syncWorldState();
2002
+ blockSyncedTo = await this.#syncWorldState(anchorBlockNumber, requestedHash);
1614
2003
  } catch (err) {
1615
2004
  this.log.error(`Error getting world state: ${err}`);
1616
2005
  }
1617
2006
 
1618
- if (block === 'latest') {
1619
- this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
2007
+ if ('tag' in query && query.tag === 'proposed') {
2008
+ this.log.debug(`Using committed db for latest block, world state synced upto ${blockSyncedTo}`);
1620
2009
  return this.worldStateSynchronizer.getCommitted();
1621
2010
  }
1622
2011
 
1623
- // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1624
- let blockNumber: BlockNumber;
1625
- if (BlockHash.isBlockHash(block)) {
1626
- const initialBlockHash = await this.#getInitialHeaderHash();
1627
- if (block.equals(initialBlockHash)) {
1628
- // Block source doesn't handle initial header so we need to handle the case separately.
1629
- return this.worldStateSynchronizer.getSnapshot(BlockNumber.ZERO);
1630
- }
1631
-
1632
- const header = await this.blockSource.getBlockHeaderByHash(block);
1633
- if (!header) {
1634
- throw new Error(
1635
- `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.`,
1636
- );
1637
- }
1638
-
1639
- blockNumber = header.getBlockNumber();
1640
- } else {
1641
- blockNumber = block as BlockNumber;
1642
- }
2012
+ const blockNumber = anchorBlockNumber ?? (await this.resolveBlockNumber(query));
1643
2013
 
1644
2014
  // Check it's within world state sync range
1645
2015
  if (blockNumber > blockSyncedTo) {
1646
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
2016
+ throw new Error(
2017
+ `Queried block ${inspectBlockParameter(block)} not yet synced by the node (node is synced upto ${blockSyncedTo}).`,
2018
+ );
1647
2019
  }
1648
2020
  this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1649
2021
 
1650
2022
  const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
1651
2023
 
1652
- // Double-check world-state synced to the same block hash as was requested
1653
- if (BlockHash.isBlockHash(block)) {
2024
+ // Double-check world-state synced to the same block hash as was requested.
2025
+ // Block 0 is skipped: the snapshot returned by `getSnapshot(0)` is the *pre*-genesis archive
2026
+ // (size 0), so leaf 0 is not yet inserted from that snapshot's view even though block 0's hash
2027
+ // does live at archive index 0 in the committed tree. The genesis hash is already validated by
2028
+ // the archiver when it resolves the hash query to block number 0.
2029
+ if (requestedHash !== undefined && blockNumber !== BlockNumber.ZERO) {
1654
2030
  const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1655
- if (!blockHash || !new BlockHash(blockHash).equals(block)) {
2031
+ if (!blockHash || !requestedHash.equals(blockHash)) {
1656
2032
  throw new Error(
1657
- `Block hash ${block.toString()} not found in world state at block number ${blockNumber}. If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
2033
+ `Block hash ${requestedHash.toString()} not found in world state at block number ${blockNumber} (world state has ${blockHash?.toString() ?? 'no hash'} at that index, genesis header hash is ${this.blockSource.getGenesisBlockHash().toString()}). If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
1658
2034
  );
1659
2035
  }
1660
2036
  }
@@ -1662,31 +2038,33 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, Traceable {
1662
2038
  return snapshot;
1663
2039
  }
1664
2040
 
1665
- /** Resolves a block parameter to a block number. */
2041
+ /** Resolves any {@link BlockParameter} variant to a concrete block number. */
1666
2042
  protected async resolveBlockNumber(block: BlockParameter): Promise<BlockNumber> {
1667
- if (block === 'latest') {
1668
- return BlockNumber(await this.blockSource.getBlockNumber());
1669
- }
1670
- if (BlockHash.isBlockHash(block)) {
1671
- const initialBlockHash = await this.#getInitialHeaderHash();
1672
- if (block.equals(initialBlockHash)) {
1673
- return BlockNumber.ZERO;
2043
+ const query = this.normalizeBlockParameter(block);
2044
+ const blockNumber = await this.blockSource.getBlockNumber(query);
2045
+ if (blockNumber === undefined) {
2046
+ if ('hash' in query) {
2047
+ throw new Error(
2048
+ `Block hash ${query.hash.toString()} not found when querying world state. If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
2049
+ );
1674
2050
  }
1675
- const header = await this.blockSource.getBlockHeaderByHash(block);
1676
- if (!header) {
1677
- throw new Error(`Block hash ${block.toString()} not found.`);
2051
+ if ('archive' in query) {
2052
+ throw new Error(`Block with archive ${query.archive.toString()} not found.`);
1678
2053
  }
1679
- return header.getBlockNumber();
2054
+ throw new Error(`Block not found for ${inspectBlockParameter(block)}.`);
1680
2055
  }
1681
- return block as BlockNumber;
2056
+ return blockNumber;
1682
2057
  }
1683
2058
 
1684
2059
  /**
1685
- * Ensure we fully sync the world state
2060
+ * Ensure the world state is synced.
2061
+ * @param targetBlockNumber - Block to sync up to. Defaults to the latest block known to the archiver.
2062
+ * @param blockHash - If provided, the synchronizer verifies the block at `targetBlockNumber` matches this
2063
+ * hash, resyncing (and so detecting reorgs) if it does not yet match or has been reorged away.
1686
2064
  * @returns A promise that fulfils once the world state is synced
1687
2065
  */
1688
- async #syncWorldState(): Promise<BlockNumber> {
1689
- const blockSourceHeight = await this.blockSource.getBlockNumber();
1690
- return await this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
2066
+ async #syncWorldState(targetBlockNumber?: BlockNumber, blockHash?: BlockHash): Promise<BlockNumber> {
2067
+ const target = targetBlockNumber ?? (await this.blockSource.getBlockNumber());
2068
+ return await this.worldStateSynchronizer.syncImmediate(target, blockHash);
1691
2069
  }
1692
2070
  }