@aztec/aztec-node 0.0.1-commit.b2a5d0dd1 → 0.0.1-commit.b3d3157a

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 +51 -83
  11. package/dest/aztec-node/server.d.ts.map +1 -1
  12. package/dest/aztec-node/server.js +690 -315
  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 +210 -68
  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 +717 -373
  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 +265 -80
  36. package/src/sentinel/store.ts +26 -18
  37. package/src/test/index.ts +2 -2
@@ -1,4 +1,4 @@
1
- import { Archiver, createArchiver } from '@aztec/archiver';
1
+ import { Archiver, L1ToL2MessagesNotReadyError, createArchiver } from '@aztec/archiver';
2
2
  import { BBCircuitVerifier, BatchChonkVerifier, QueuedIVCVerifier } from '@aztec/bb-prover';
3
3
  import { TestCircuitVerifier } from '@aztec/bb-prover/test';
4
4
  import { type BlobClientInterface, createBlobClientWithFileStores } from '@aztec/blob-client/client';
@@ -8,7 +8,7 @@ import { EpochCache, type EpochCacheInterface } from '@aztec/epoch-cache';
8
8
  import { createEthereumChain } from '@aztec/ethereum/chain';
9
9
  import { getPublicClient, makeL1HttpTransport } from '@aztec/ethereum/client';
10
10
  import { RegistryContract, RollupContract } from '@aztec/ethereum/contracts';
11
- import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
11
+ import { type L1ContractAddresses, pickL1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
12
12
  import type { L1TxUtils } from '@aztec/ethereum/l1-tx-utils';
13
13
  import { BlockNumber, CheckpointNumber, EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
14
14
  import { chunkBy, compactArray, pick, unique } from '@aztec/foundation/collection';
@@ -20,6 +20,7 @@ import { retryUntil } from '@aztec/foundation/retry';
20
20
  import { count } from '@aztec/foundation/string';
21
21
  import { DateProvider, Timer } from '@aztec/foundation/timer';
22
22
  import { MembershipWitness, SiblingPath } from '@aztec/foundation/trees';
23
+ import { isErrorClass } from '@aztec/foundation/types';
23
24
  import { type KeyStore, KeystoreManager, loadKeystores, mergeKeystores } from '@aztec/node-keystore';
24
25
  import { trySnapshotSync, uploadSnapshot } from '@aztec/node-lib/actions';
25
26
  import { createForwarderL1TxUtilsFromSigners, createL1TxUtilsFromSigners } from '@aztec/node-lib/factories';
@@ -34,30 +35,46 @@ import { ProtocolContractAddress } from '@aztec/protocol-contracts';
34
35
  import { type ProverNode, type ProverNodeDeps, createProverNode } from '@aztec/prover-node';
35
36
  import { createKeyStoreForProver } from '@aztec/prover-node/config';
36
37
  import {
38
+ AutomineSequencer,
37
39
  FeeProviderImpl,
38
40
  GlobalVariableBuilder,
39
41
  SequencerClient,
40
42
  type SequencerPublisher,
43
+ createAutomineSequencer,
41
44
  } from '@aztec/sequencer-client';
42
- import { PublicProcessorFactory } from '@aztec/simulator/server';
45
+ import { PublicContractsDB, PublicProcessorFactory } from '@aztec/simulator/server';
43
46
  import {
44
47
  AttestationsBlockWatcher,
45
- EpochPruneWatcher,
48
+ AttestedInvalidProposalWatcher,
49
+ BroadcastedInvalidCheckpointProposalWatcher,
50
+ CheckpointEquivocationWatcher,
51
+ DataWithholdingWatcher,
46
52
  type SlasherClientInterface,
47
53
  type Watcher,
48
54
  createSlasher,
49
55
  } from '@aztec/slasher';
56
+ import { STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS } from '@aztec/standard-contracts/multi-call-entrypoint';
50
57
  import { CollectionLimitsConfig, PublicSimulatorConfig } from '@aztec/stdlib/avm';
51
58
  import { AztecAddress } from '@aztec/stdlib/aztec-address';
52
59
  import {
53
60
  type BlockData,
54
61
  BlockHash,
55
62
  type BlockParameter,
63
+ BlockTag,
64
+ type CheckpointsQuery,
65
+ type CommitteeAttestation,
56
66
  type DataInBlock,
57
- L2Block,
58
67
  type L2BlockSource,
68
+ type L2Tips,
69
+ type NormalizedBlockParameter,
70
+ inspectBlockParameter,
59
71
  } from '@aztec/stdlib/block';
60
- import type { PublishedCheckpoint } from '@aztec/stdlib/checkpoint';
72
+ import {
73
+ type CheckpointData,
74
+ CheckpointReexecutionTracker,
75
+ L1PublishedData,
76
+ type PublishedCheckpoint,
77
+ } from '@aztec/stdlib/checkpoint';
61
78
  import type {
62
79
  ContractClassPublic,
63
80
  ContractDataSource,
@@ -65,17 +82,24 @@ import type {
65
82
  NodeInfo,
66
83
  ProtocolContractAddresses,
67
84
  } from '@aztec/stdlib/contract';
85
+ import { getEpochAtSlot } from '@aztec/stdlib/epoch-helpers';
68
86
  import { GasFees, type ManaUsageEstimate } from '@aztec/stdlib/gas';
69
87
  import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
70
- import {
71
- type AztecNode,
72
- type AztecNodeAdmin,
73
- type AztecNodeAdminConfig,
74
- AztecNodeAdminConfigSchema,
75
- type AztecNodeDebug,
76
- type GetContractClassLogsResponse,
77
- type GetPublicLogsResponse,
88
+ import type {
89
+ AztecNode,
90
+ AztecNodeAdmin,
91
+ AztecNodeAdminConfig,
92
+ AztecNodeDebug,
93
+ BlockIncludeOptions,
94
+ BlockResponse,
95
+ BlocksIncludeOptions,
96
+ ChainTip,
97
+ ChainTips,
98
+ CheckpointIncludeOptions,
99
+ CheckpointParameter,
100
+ CheckpointResponse,
78
101
  } from '@aztec/stdlib/interfaces/client';
102
+ import { AztecNodeAdminConfigSchema } from '@aztec/stdlib/interfaces/client';
79
103
  import {
80
104
  type AllowedElement,
81
105
  type ClientProtocolCircuitVerifier,
@@ -85,21 +109,32 @@ import {
85
109
  type WorldStateSynchronizer,
86
110
  tryStop,
87
111
  } from '@aztec/stdlib/interfaces/server';
88
- import type { DebugLogStore, LogFilter, SiloedTag, Tag, TxScopedL2Log } from '@aztec/stdlib/logs';
112
+ import type { DebugLogStore, LogResult, PrivateLogsQuery, PublicLogsQuery } from '@aztec/stdlib/logs';
89
113
  import { InMemoryDebugLogStore, NullDebugLogStore } from '@aztec/stdlib/logs';
90
- import { InboxLeaf, type L1ToL2MessageSource } from '@aztec/stdlib/messaging';
114
+ import {
115
+ InboxLeaf,
116
+ type L1ToL2MessageSource,
117
+ type L2ToL1MembershipWitness,
118
+ appendL1ToL2MessagesToTree,
119
+ } from '@aztec/stdlib/messaging';
91
120
  import type { Offense } from '@aztec/stdlib/slashing';
121
+ import { MIN_EXECUTION_TIME } from '@aztec/stdlib/timetable';
92
122
  import type { NullifierLeafPreimage, PublicDataTreeLeafPreimage } from '@aztec/stdlib/trees';
93
123
  import { MerkleTreeId, NullifierMembershipWitness, PublicDataWitness } from '@aztec/stdlib/trees';
94
124
  import {
95
- type BlockHeader,
125
+ DroppedTxReceipt,
96
126
  type FeeProvider,
127
+ type GetTxReceiptOptions,
97
128
  type GlobalVariableBuilder as GlobalVariableBuilderInterface,
98
129
  type IndexedTxEffect,
130
+ MinedTxReceipt,
131
+ type MinedTxStatus,
132
+ PendingTxReceipt,
99
133
  PublicSimulationOutput,
134
+ type SimulationOverrides,
100
135
  Tx,
101
136
  type TxHash,
102
- TxReceipt,
137
+ type TxReceipt,
103
138
  TxStatus,
104
139
  type TxValidationResult,
105
140
  } from '@aztec/stdlib/tx';
@@ -123,24 +158,32 @@ import {
123
158
  createValidatorClient,
124
159
  } from '@aztec/validator-client';
125
160
  import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
126
- import { createWorldStateSynchronizer } from '@aztec/world-state';
161
+ import { createWorldState, createWorldStateSynchronizer } from '@aztec/world-state';
127
162
 
128
163
  import { createPublicClient } from 'viem';
129
164
 
130
165
  import { createSentinel } from '../sentinel/factory.js';
131
166
  import { Sentinel } from '../sentinel/sentinel.js';
167
+ import {
168
+ blockResponseFromBlockData,
169
+ blockResponseFromL2Block,
170
+ checkpointResponseFromCheckpointData,
171
+ checkpointResponseFromPublishedCheckpoint,
172
+ projectProposedToCheckpointResponse,
173
+ } from './block_response_helpers.js';
132
174
  import { type AztecNodeConfig, createKeyStoreForValidator } from './config.js';
133
175
  import { NodeMetrics } from './node_metrics.js';
176
+ import { applyPublicDataOverrides } from './public_data_overrides.js';
134
177
 
135
178
  /**
136
179
  * The aztec node.
137
180
  */
138
181
  export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDebug, Traceable {
139
182
  private metrics: NodeMetrics;
140
- private initialHeaderHashPromise: Promise<BlockHash> | undefined = undefined;
141
-
142
183
  // Prevent two snapshot operations to happen simultaneously
143
184
  private isUploadingSnapshot = false;
185
+ // Saved minTxsPerBlock used by `pauseSequencer` to restore production-sequencer config on resume.
186
+ private sequencerPausedMinTxsPerBlock: number | undefined;
144
187
 
145
188
  public readonly tracer: Tracer;
146
189
 
@@ -156,7 +199,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
156
199
  protected readonly proverNode: ProverNode | undefined,
157
200
  protected readonly slasherClient: SlasherClientInterface | undefined,
158
201
  protected readonly validatorsSentinel: Sentinel | undefined,
159
- protected readonly epochPruneWatcher: EpochPruneWatcher | undefined,
202
+ private readonly stopStartedWatchers: () => Promise<void>,
160
203
  protected readonly l1ChainId: number,
161
204
  protected readonly version: number,
162
205
  protected readonly globalVariableBuilder: GlobalVariableBuilderInterface,
@@ -171,12 +214,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
171
214
  private validatorClient?: ValidatorClient,
172
215
  private keyStoreManager?: KeystoreManager,
173
216
  private debugLogStore: DebugLogStore = new NullDebugLogStore(),
217
+ private readonly automineSequencer?: AutomineSequencer,
174
218
  ) {
175
219
  this.metrics = new NodeMetrics(telemetry, 'AztecNodeService');
176
220
  this.tracer = telemetry.getTracer('AztecNodeService');
177
221
 
178
222
  this.log.info(`Aztec Node version: ${this.packageVersion}`);
179
- this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, config.l1Contracts);
223
+ this.log.info(`Aztec Node started on chain 0x${l1ChainId.toString(16)}`, pickL1ContractAddresses(config));
180
224
 
181
225
  // A defensive check that protects us against introducing a bug in the complex `createAndSync` function. We must
182
226
  // never have debugLogStore enabled when not in test mode because then we would be accumulating debug logs in
@@ -196,8 +240,238 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
196
240
  return status.syncSummary;
197
241
  }
198
242
 
199
- public getL2Tips() {
200
- return this.blockSource.getL2Tips();
243
+ public async getChainTips(): Promise<ChainTips> {
244
+ const { proposed, checkpointed, proven, finalized } = await this.blockSource.getL2Tips();
245
+ return { proposed, checkpointed, proven, finalized };
246
+ }
247
+
248
+ public getCheckpointsData(query: CheckpointsQuery) {
249
+ return this.blockSource.getCheckpointsData(query);
250
+ }
251
+
252
+ public async getBlockNumber(tip?: ChainTip): Promise<BlockNumber> {
253
+ if (tip === undefined || tip === 'proposed') {
254
+ return this.blockSource.getBlockNumber();
255
+ }
256
+ return (await this.blockSource.getBlockNumber({ tag: tip })) ?? BlockNumber.ZERO;
257
+ }
258
+
259
+ public async getCheckpointNumber(tip?: ChainTip): Promise<CheckpointNumber> {
260
+ const tips = await this.blockSource.getL2Tips();
261
+ switch (tip) {
262
+ case undefined:
263
+ case 'checkpointed':
264
+ return tips.checkpointed.checkpoint.number;
265
+ case 'proposed':
266
+ return tips.proposedCheckpoint.checkpoint.number;
267
+ case 'proven':
268
+ return tips.proven.checkpoint.number;
269
+ case 'finalized':
270
+ return tips.finalized.checkpoint.number;
271
+ }
272
+ }
273
+
274
+ private isChainTip(value: unknown): value is ChainTip {
275
+ return value === 'proposed' || value === 'checkpointed' || value === 'proven' || value === 'finalized';
276
+ }
277
+
278
+ /**
279
+ * Normalizes a {@link BlockParameter} (which may be a bare value) into a
280
+ * {@link NormalizedBlockParameter} object form. Performs no chain-tip resolution — tag
281
+ * lookups are deferred to the underlying block source.
282
+ */
283
+ private normalizeBlockParameter(param: BlockParameter): NormalizedBlockParameter {
284
+ if (BlockHash.isBlockHash(param)) {
285
+ return { hash: param };
286
+ }
287
+ if (typeof param === 'number') {
288
+ return { number: param as BlockNumber };
289
+ }
290
+ if (typeof param === 'string') {
291
+ if (this.isBlockTag(param)) {
292
+ return { tag: param === 'latest' ? 'proposed' : param };
293
+ }
294
+ throw new BadRequestError(`Invalid BlockParameter tag: ${param}`);
295
+ }
296
+ if (typeof param === 'object' && param !== null) {
297
+ if ('number' in param) {
298
+ return { number: param.number };
299
+ }
300
+ if ('hash' in param) {
301
+ return { hash: param.hash };
302
+ }
303
+ if ('archive' in param) {
304
+ return { archive: param.archive };
305
+ }
306
+ if ('tag' in param) {
307
+ if (this.isBlockTag(param.tag)) {
308
+ return { tag: param.tag };
309
+ }
310
+ throw new BadRequestError(`Invalid BlockParameter tag: ${param.tag}`);
311
+ }
312
+ }
313
+ throw new BadRequestError(`Invalid BlockParameter: ${JSON.stringify(param)}`);
314
+ }
315
+
316
+ private isBlockTag(value: string): value is BlockTag {
317
+ return BlockTag.includes(value as BlockTag);
318
+ }
319
+
320
+ /**
321
+ * Resolves a {@link CheckpointParameter} into a concrete `{ number }` or `{ slot }` query.
322
+ *
323
+ * Tag-based parameters (`'proposed'`, `'checkpointed'`, `'proven'`, `'finalized'`) are
324
+ * translated up-front to the corresponding tip's checkpoint number via {@link L2BlockSource.getL2Tips}.
325
+ * After resolution the unified {@link getCheckpoint} flow can perform a single
326
+ * confirmed→proposed lookup against either store.
327
+ */
328
+ private async resolveCheckpointParameter(
329
+ param: CheckpointParameter,
330
+ ): Promise<{ number: CheckpointNumber } | { slot: SlotNumber }> {
331
+ if (typeof param === 'number') {
332
+ return { number: param as CheckpointNumber };
333
+ }
334
+ if (this.isChainTip(param)) {
335
+ const tips = await this.blockSource.getL2Tips();
336
+ switch (param) {
337
+ case 'proposed':
338
+ return { number: tips.proposedCheckpoint.checkpoint.number };
339
+ case 'checkpointed':
340
+ return { number: tips.checkpointed.checkpoint.number };
341
+ case 'proven':
342
+ return { number: tips.proven.checkpoint.number };
343
+ case 'finalized':
344
+ return { number: tips.finalized.checkpoint.number };
345
+ }
346
+ }
347
+ if (typeof param === 'object' && param !== null) {
348
+ if ('number' in param) {
349
+ return { number: param.number };
350
+ }
351
+ if ('slot' in param) {
352
+ return { slot: param.slot };
353
+ }
354
+ }
355
+ throw new BadRequestError(`Invalid CheckpointParameter: ${JSON.stringify(param)}`);
356
+ }
357
+
358
+ /** Fetches checkpoint-level L1 and attestation data for use as block response context. */
359
+ async #getCheckpointContext(
360
+ checkpointNumber: CheckpointNumber,
361
+ ): Promise<{ l1?: L1PublishedData; attestations?: CommitteeAttestation[] } | undefined> {
362
+ const checkpoint = await this.blockSource.getCheckpointData({ number: checkpointNumber });
363
+ if (!checkpoint) {
364
+ return undefined;
365
+ }
366
+ return { l1: checkpoint.l1, attestations: checkpoint.attestations };
367
+ }
368
+
369
+ public async getBlock<Opts extends BlockIncludeOptions = {}>(
370
+ param: BlockParameter,
371
+ options: Opts = {} as Opts,
372
+ ): Promise<BlockResponse<Opts> | undefined> {
373
+ const query = this.normalizeBlockParameter(param);
374
+ const wantTxs = !!options.includeTransactions;
375
+ const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
376
+
377
+ if (wantTxs) {
378
+ const block = await this.blockSource.getBlock(query);
379
+ if (!block) {
380
+ return undefined;
381
+ }
382
+ const ctx = wantContext ? await this.#getCheckpointContext(block.checkpointNumber) : undefined;
383
+ return (await blockResponseFromL2Block(block, options, ctx)) as BlockResponse<Opts>;
384
+ }
385
+ const data = await this.blockSource.getBlockData(query);
386
+ if (!data) {
387
+ return undefined;
388
+ }
389
+ const ctx = wantContext ? await this.#getCheckpointContext(data.checkpointNumber) : undefined;
390
+ return blockResponseFromBlockData(data, options, ctx) as BlockResponse<Opts>;
391
+ }
392
+
393
+ public getBlockData(param: BlockParameter): Promise<BlockData | undefined> {
394
+ const query = this.normalizeBlockParameter(param);
395
+ return this.blockSource.getBlockData(query);
396
+ }
397
+
398
+ public async getBlocks<Opts extends BlocksIncludeOptions = {}>(
399
+ from: BlockNumber,
400
+ limit: number,
401
+ options: Opts = {} as Opts,
402
+ ): Promise<BlockResponse<Opts>[]> {
403
+ const wantTxs = !!options.includeTransactions;
404
+ const wantContext = !!options.includeL1PublishInfo || !!options.includeAttestations;
405
+ const onlyCheckpointed = !!options.onlyCheckpointed;
406
+ if (wantTxs) {
407
+ const blocks = await this.blockSource.getBlocks({ from, limit, onlyCheckpointed });
408
+ const ctxByCheckpoint = await this.#getCheckpointContextsForBlocks(wantContext ? blocks : []);
409
+ return (await Promise.all(
410
+ blocks.map(block => blockResponseFromL2Block(block, options, ctxByCheckpoint.get(block.checkpointNumber))),
411
+ )) as BlockResponse<Opts>[];
412
+ }
413
+ const dataItems = await this.blockSource.getBlocksData({ from, limit, onlyCheckpointed });
414
+ const ctxByCheckpoint = await this.#getCheckpointContextsForBlocks(wantContext ? dataItems : []);
415
+ return (await Promise.all(
416
+ dataItems.map(data => blockResponseFromBlockData(data, options, ctxByCheckpoint.get(data.checkpointNumber))),
417
+ )) as BlockResponse<Opts>[];
418
+ }
419
+
420
+ /** Fetches checkpoint context for a set of blocks, deduplicating shared checkpoints. */
421
+ async #getCheckpointContextsForBlocks(
422
+ blocks: { checkpointNumber: CheckpointNumber }[],
423
+ ): Promise<Map<CheckpointNumber, { l1?: L1PublishedData; attestations?: CommitteeAttestation[] } | undefined>> {
424
+ const unique = Array.from(new Set(blocks.map(b => b.checkpointNumber)));
425
+ const entries = await Promise.all(unique.map(async n => [n, await this.#getCheckpointContext(n)] as const));
426
+ return new Map(entries);
427
+ }
428
+
429
+ public async getCheckpoint<Opts extends CheckpointIncludeOptions = {}>(
430
+ param: CheckpointParameter,
431
+ options: Opts = {} as Opts,
432
+ ): Promise<CheckpointResponse<Opts> | undefined> {
433
+ const query = await this.resolveCheckpointParameter(param);
434
+
435
+ // Try the confirmed store first.
436
+ const confirmed = options.includeBlocks
437
+ ? await this.blockSource.getCheckpoint(query)
438
+ : await this.blockSource.getCheckpointData(query);
439
+ if (confirmed) {
440
+ return (await (options.includeBlocks
441
+ ? checkpointResponseFromPublishedCheckpoint(confirmed as PublishedCheckpoint, options)
442
+ : checkpointResponseFromCheckpointData(confirmed as CheckpointData, options))) as CheckpointResponse<Opts>;
443
+ }
444
+
445
+ // Fall back to the proposed store.
446
+ const proposed = await this.blockSource.getProposedCheckpointData(query);
447
+ if (proposed) {
448
+ if (options.includeAttestations || options.includeL1PublishInfo) {
449
+ throw new BadRequestError(
450
+ `Options includeL1PublishInfo or includeAttestations cannot be satisfied for a proposed checkpoint`,
451
+ );
452
+ }
453
+ const blocks = options.includeBlocks
454
+ ? await this.blockSource.getBlocks({ from: proposed.startBlock, limit: proposed.blockCount })
455
+ : undefined;
456
+ return (await projectProposedToCheckpointResponse(proposed, options, blocks)) as CheckpointResponse<Opts>;
457
+ }
458
+
459
+ return undefined;
460
+ }
461
+
462
+ public async getCheckpoints<Opts extends CheckpointIncludeOptions = {}>(
463
+ from: CheckpointNumber,
464
+ limit: number,
465
+ options: Opts = {} as Opts,
466
+ ): Promise<CheckpointResponse<Opts>[]> {
467
+ if (options.includeBlocks) {
468
+ const checkpoints = await this.blockSource.getCheckpoints({ from, limit });
469
+ return (await Promise.all(
470
+ checkpoints.map(cp => checkpointResponseFromPublishedCheckpoint(cp, options)),
471
+ )) as CheckpointResponse<Opts>[];
472
+ }
473
+ const datas = await this.blockSource.getCheckpointsData({ from, limit });
474
+ return datas.map(d => checkpointResponseFromCheckpointData(d, options)) as CheckpointResponse<Opts>[];
201
475
  }
202
476
 
203
477
  /**
@@ -224,7 +498,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
224
498
  ): Promise<AztecNodeService> {
225
499
  const config = { ...inputConfig }; // Copy the config so we dont mutate the input object
226
500
  const log = deps.logger ?? createLogger('node');
227
- const packageVersion = getPackageVersion() ?? '';
501
+ const packageVersion = getPackageVersion();
228
502
  const telemetry = deps.telemetry ?? getTelemetryClient();
229
503
  const dateProvider = deps.dateProvider ?? new DateProvider();
230
504
  const ethereumChain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
@@ -283,14 +557,13 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
283
557
 
284
558
  const l1ContractsAddresses = await RegistryContract.collectAddresses(
285
559
  publicClient,
286
- config.l1Contracts.registryAddress,
560
+ config.registryAddress,
287
561
  config.rollupVersion ?? 'canonical',
288
562
  );
289
563
 
290
- // Overwrite the passed in vars.
291
- config.l1Contracts = { ...config.l1Contracts, ...l1ContractsAddresses };
564
+ Object.assign(config, l1ContractsAddresses);
292
565
 
293
- const rollupContract = new RollupContract(publicClient, config.l1Contracts.rollupAddress.toString());
566
+ const rollupContract = new RollupContract(publicClient, config.rollupAddress.toString());
294
567
  const [l1GenesisTime, slotDuration, rollupVersionFromRollup, rollupManaLimit] = await Promise.all([
295
568
  rollupContract.getL1GenesisTime(),
296
569
  rollupContract.getSlotDuration(),
@@ -311,20 +584,36 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
311
584
  // attempt snapshot sync if possible
312
585
  await trySnapshotSync(config, log);
313
586
 
314
- const epochCache = await EpochCache.create(config.l1Contracts.rollupAddress, config, { dateProvider });
587
+ const epochCache = await EpochCache.create(config.rollupAddress, config, { dateProvider });
315
588
 
316
589
  // Track started resources so we can clean up on partial failure during node creation.
317
590
  const started: { stop?(): Promise<void> | void }[] = [];
318
591
  try {
592
+ // Default the orphan-prune grace window from the block build duration when unset, so the archiver
593
+ // waits roughly one build slot for a proposed checkpoint to arrive before pruning a block-only tip.
594
+ config.orphanProposedBlockPruneGraceSeconds ??=
595
+ config.blockDurationMs !== undefined ? Math.ceil(config.blockDurationMs / 1000) : MIN_EXECUTION_TIME;
596
+
597
+ // Create world-state first so we can retrieve the initial header before constructing the archiver.
598
+ const nativeWs = await createWorldState(config, options.genesis);
599
+ const initialHeader = nativeWs.getInitialHeader();
600
+ const initialBlockHash = await initialHeader.hash();
319
601
  const archiver = await createArchiver(
320
602
  config,
321
603
  { blobClient, epochCache, telemetry, dateProvider },
322
- { blockUntilSync: !config.skipArchiverInitialSync },
604
+ {
605
+ blockUntilSync: !config.skipArchiverInitialSync,
606
+ // The non-pipelined automine sequencer publishes each checkpoint in-slot, so it never
607
+ // leaves orphan proposed blocks; pruning would race its local push. See pruneOrphanProposedBlocks.
608
+ enableOrphanProposedBlockPruning: !config.useAutomineSequencer,
609
+ },
610
+ initialHeader,
611
+ initialBlockHash,
323
612
  );
324
613
  started.push(archiver);
325
614
 
326
- // now create the merkle trees and the world state synchronizer
327
- const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, options.genesis, telemetry);
615
+ // The synchronizer takes ownership of the native world-state from here
616
+ const worldStateSynchronizer = await createWorldStateSynchronizer(config, archiver, nativeWs, telemetry);
328
617
  started.push(worldStateSynchronizer);
329
618
  const useRealVerifiers = config.realProofs || config.debugForceTxProofVerification;
330
619
  let peerProofVerifier: ClientProtocolCircuitVerifier;
@@ -352,7 +641,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
352
641
  }
353
642
 
354
643
  const globalVariableBuilderConfig = {
355
- l1Contracts: config.l1Contracts,
644
+ rollupAddress: config.rollupAddress,
356
645
  ethereumSlotDuration: config.ethereumSlotDuration,
357
646
  rollupVersion: BigInt(config.rollupVersion),
358
647
  l1GenesisTime,
@@ -379,6 +668,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
379
668
  dateProvider,
380
669
  telemetry,
381
670
  deps.p2pClientDeps,
671
+ initialBlockHash,
382
672
  );
383
673
  started.push(p2pClient);
384
674
 
@@ -403,7 +693,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
403
693
 
404
694
  let validatorClient: ValidatorClient | undefined;
405
695
 
406
- if (!proverOnly) {
696
+ // Tracks successful checkpoint re-execution by a checkpoint proposal handler.
697
+ const reexecutionTracker = new CheckpointReexecutionTracker();
698
+
699
+ if (!config.disableValidator) {
407
700
  // Create validator client if required
408
701
  validatorClient = await createValidatorClient(config, {
409
702
  checkpointsBuilder: validatorCheckpointsBuilder,
@@ -416,6 +709,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
416
709
  l1ToL2MessageSource: archiver,
417
710
  keyStoreManager,
418
711
  blobClient,
712
+ reexecutionTracker,
419
713
  slashingProtectionDb: deps.slashingProtectionDb,
420
714
  });
421
715
 
@@ -452,6 +746,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
452
746
  blobClient,
453
747
  dateProvider,
454
748
  telemetry,
749
+ reexecutionTracker,
455
750
  }).register(p2pClient, reexecute, archiver);
456
751
  }
457
752
 
@@ -462,47 +757,87 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
462
757
  await p2pClient.start();
463
758
 
464
759
  let validatorsSentinel: Awaited<ReturnType<typeof createSentinel>> | undefined;
465
- let epochPruneWatcher: EpochPruneWatcher | undefined;
760
+ let dataWithholdingWatcher: DataWithholdingWatcher | undefined;
466
761
  let attestationsBlockWatcher: AttestationsBlockWatcher | undefined;
762
+ let attestedInvalidProposalWatcher: AttestedInvalidProposalWatcher | undefined;
763
+ let broadcastedInvalidCheckpointProposalWatcher: BroadcastedInvalidCheckpointProposalWatcher | undefined;
764
+ let checkpointEquivocationWatcher: CheckpointEquivocationWatcher | undefined;
467
765
 
468
766
  if (!proverOnly) {
469
- validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, config);
470
- if (validatorsSentinel && config.slashInactivityPenalty > 0n) {
767
+ validatorsSentinel = await createSentinel(epochCache, archiver, p2pClient, reexecutionTracker, config);
768
+ if (validatorsSentinel) {
471
769
  watchers.push(validatorsSentinel);
472
770
  }
473
771
 
474
- if (config.slashPrunePenalty > 0n || config.slashDataWithholdingPenalty > 0n) {
475
- epochPruneWatcher = new EpochPruneWatcher(
476
- archiver,
772
+ dataWithholdingWatcher = new DataWithholdingWatcher(
773
+ epochCache,
774
+ archiver,
775
+ p2pClient.getTxProvider(),
776
+ p2pClient,
777
+ reexecutionTracker,
778
+ { chainId: config.l1ChainId, rollupAddress: config.rollupAddress },
779
+ config,
780
+ );
781
+ watchers.push(dataWithholdingWatcher);
782
+
783
+ broadcastedInvalidCheckpointProposalWatcher = new BroadcastedInvalidCheckpointProposalWatcher(
784
+ p2pClient,
785
+ archiver,
786
+ epochCache,
787
+ config,
788
+ );
789
+ watchers.push(broadcastedInvalidCheckpointProposalWatcher);
790
+
791
+ if (validatorClient) {
792
+ attestedInvalidProposalWatcher = new AttestedInvalidProposalWatcher(
793
+ p2pClient,
794
+ validatorClient,
477
795
  archiver,
478
796
  epochCache,
479
- p2pClient.getTxProvider(),
480
- validatorCheckpointsBuilder,
481
797
  config,
798
+ { log: log.createChild('attested-invalid-proposal-watcher') },
482
799
  );
483
- watchers.push(epochPruneWatcher);
800
+ watchers.push(attestedInvalidProposalWatcher);
484
801
  }
485
802
 
486
- // We assume we want to slash for invalid attestations unless all max penalties are set to 0
487
- if (config.slashProposeInvalidAttestationsPenalty > 0n || config.slashAttestDescendantOfInvalidPenalty > 0n) {
488
- attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config);
489
- watchers.push(attestationsBlockWatcher);
490
- }
803
+ checkpointEquivocationWatcher = new CheckpointEquivocationWatcher(archiver, epochCache, config);
804
+ watchers.push(checkpointEquivocationWatcher);
805
+
806
+ attestationsBlockWatcher = new AttestationsBlockWatcher(archiver, epochCache, config, log.getBindings());
807
+ watchers.push(attestationsBlockWatcher);
491
808
  }
492
809
 
810
+ const watchersToStart = compactArray([
811
+ validatorsSentinel,
812
+ dataWithholdingWatcher,
813
+ attestationsBlockWatcher,
814
+ broadcastedInvalidCheckpointProposalWatcher,
815
+ attestedInvalidProposalWatcher,
816
+ checkpointEquivocationWatcher,
817
+ ]);
818
+ const startedWatchers: Watcher[] = [];
819
+ const stopStartedWatchers = async () => {
820
+ for (const watcher of startedWatchers) {
821
+ await tryStop(watcher);
822
+ }
823
+ };
824
+
493
825
  // Start p2p-related services once the archiver has completed sync
494
826
  void archiver
495
827
  .waitForInitialSync()
496
828
  .then(async () => {
497
- await validatorsSentinel?.start();
498
- await epochPruneWatcher?.start();
499
- await attestationsBlockWatcher?.start();
829
+ for (const watcher of watchersToStart) {
830
+ await watcher.start();
831
+ startedWatchers.push(watcher);
832
+ }
500
833
  log.info(`All p2p services started`);
501
834
  })
502
835
  .catch(err => log.error('Failed to start p2p services after archiver sync', err));
836
+ started.push({ stop: stopStartedWatchers });
503
837
 
504
838
  // Validator enabled, create/start relevant service
505
839
  let sequencer: SequencerClient | undefined;
840
+ let automineSequencer: AutomineSequencer | undefined;
506
841
  let slasherClient: SlasherClientInterface | undefined;
507
842
  if (!config.disableValidator && validatorClient) {
508
843
  // We create a slasher only if we have a sequencer, since all slashing actions go through the sequencer publisher
@@ -513,7 +848,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
513
848
 
514
849
  slasherClient = await createSlasher(
515
850
  config,
516
- config.l1Contracts,
851
+ pickL1ContractAddresses(config),
517
852
  getPublicClient(config),
518
853
  watchers,
519
854
  dateProvider,
@@ -562,24 +897,54 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
562
897
  debugLogStore,
563
898
  );
564
899
 
565
- sequencer = await SequencerClient.new(config, {
566
- ...deps,
567
- epochCache,
568
- l1TxUtils,
569
- funderL1TxUtils,
570
- validatorClient,
571
- p2pClient,
572
- worldStateSynchronizer,
573
- slasherClient,
574
- checkpointsBuilder,
575
- l2BlockSource: archiver,
576
- l1ToL2MessageSource: archiver,
577
- telemetry,
578
- dateProvider,
579
- blobClient,
580
- nodeKeyStore: keyStoreManager!,
581
- globalVariableBuilder,
582
- });
900
+ if (config.useAutomineSequencer) {
901
+ // Test-only path: deterministic, queue-driven sequencer for non-block-building e2e tests.
902
+ // See `AUTOMINE_E2E_OPTS` in `end-to-end/src/fixtures/fixtures.ts`.
903
+ automineSequencer = await createAutomineSequencer({
904
+ config,
905
+ l1TxUtils,
906
+ funderL1TxUtils,
907
+ publicClient,
908
+ rollupContract,
909
+ epochCache,
910
+ blobClient,
911
+ telemetry,
912
+ dateProvider,
913
+ keyStoreManager: keyStoreManager!,
914
+ validatorClient,
915
+ checkpointsBuilder,
916
+ globalVariableBuilder,
917
+ worldStateSynchronizer,
918
+ archiver,
919
+ p2pClient,
920
+ l1Constants: {
921
+ l1GenesisTime,
922
+ slotDuration: Number(slotDuration),
923
+ ethereumSlotDuration: config.ethereumSlotDuration,
924
+ rollupManaLimit,
925
+ },
926
+ log,
927
+ });
928
+ } else {
929
+ sequencer = await SequencerClient.new(config, {
930
+ ...deps,
931
+ epochCache,
932
+ l1TxUtils,
933
+ funderL1TxUtils,
934
+ validatorClient,
935
+ p2pClient,
936
+ worldStateSynchronizer,
937
+ slasherClient,
938
+ checkpointsBuilder,
939
+ l2BlockSource: archiver,
940
+ l1ToL2MessageSource: archiver,
941
+ telemetry,
942
+ dateProvider,
943
+ blobClient,
944
+ nodeKeyStore: keyStoreManager!,
945
+ globalVariableBuilder,
946
+ });
947
+ }
583
948
  }
584
949
 
585
950
  if (!options.dontStartSequencer && sequencer) {
@@ -590,6 +955,14 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
590
955
  log.warn(`Sequencer created but not started`);
591
956
  }
592
957
 
958
+ if (!options.dontStartSequencer && automineSequencer) {
959
+ await automineSequencer.start();
960
+ started.push({ stop: () => automineSequencer!.stop() });
961
+ log.verbose(`AutomineSequencer started`);
962
+ } else if (automineSequencer) {
963
+ log.warn(`AutomineSequencer created but not started`);
964
+ }
965
+
593
966
  // Create prover node subsystem if enabled
594
967
  let proverNode: ProverNode | undefined;
595
968
  if (config.enableProverNode) {
@@ -626,7 +999,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
626
999
  proverNode,
627
1000
  slasherClient,
628
1001
  validatorsSentinel,
629
- epochPruneWatcher,
1002
+ stopStartedWatchers,
630
1003
  ethereumChain.chainInfo.id,
631
1004
  config.rollupVersion,
632
1005
  globalVariableBuilder,
@@ -641,6 +1014,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
641
1014
  validatorClient,
642
1015
  keyStoreManager,
643
1016
  debugLogStore,
1017
+ automineSequencer,
644
1018
  );
645
1019
 
646
1020
  return node;
@@ -661,6 +1035,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
661
1035
  return this.sequencer;
662
1036
  }
663
1037
 
1038
+ /** Test-only: returns the AutomineSequencer when wired via `useAutomineSequencer`. */
1039
+ public getAutomineSequencer(): AutomineSequencer | undefined {
1040
+ return this.automineSequencer;
1041
+ }
1042
+
664
1043
  /** Returns the prover node subsystem, if enabled. */
665
1044
  public getProverNode(): ProverNode | undefined {
666
1045
  return this.proverNode;
@@ -683,7 +1062,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
683
1062
  * @returns - The currently deployed L1 contract addresses.
684
1063
  */
685
1064
  public getL1ContractAddresses(): Promise<L1ContractAddresses> {
686
- return Promise.resolve(this.config.l1Contracts);
1065
+ return Promise.resolve(pickL1ContractAddresses(this.config));
687
1066
  }
688
1067
 
689
1068
  public getEncodedEnr(): Promise<string | undefined> {
@@ -725,71 +1104,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
725
1104
  return nodeInfo;
726
1105
  }
727
1106
 
728
- /**
729
- * Get a block specified by its block number, block hash, or 'latest'.
730
- * @param block - The block parameter (block number, block hash, or 'latest').
731
- * @returns The requested block.
732
- */
733
- public async getBlock(block: BlockParameter): Promise<L2Block | undefined> {
734
- if (BlockHash.isBlockHash(block)) {
735
- return this.getBlockByHash(block);
736
- }
737
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
738
- if (blockNumber === BlockNumber.ZERO) {
739
- return this.buildInitialBlock();
740
- }
741
- return await this.blockSource.getL2Block(blockNumber);
742
- }
743
-
744
- /**
745
- * Get a block specified by its hash.
746
- * @param blockHash - The block hash being requested.
747
- * @returns The requested block.
748
- */
749
- public async getBlockByHash(blockHash: BlockHash): Promise<L2Block | undefined> {
750
- const initialBlockHash = await this.#getInitialHeaderHash();
751
- if (blockHash.equals(initialBlockHash)) {
752
- return this.buildInitialBlock();
753
- }
754
- return await this.blockSource.getL2BlockByHash(blockHash);
755
- }
756
-
757
- private buildInitialBlock(): L2Block {
758
- const initialHeader = this.worldStateSynchronizer.getCommitted().getInitialHeader();
759
- return L2Block.empty(initialHeader);
760
- }
761
-
762
- /**
763
- * Get a block specified by its archive root.
764
- * @param archive - The archive root being requested.
765
- * @returns The requested block.
766
- */
767
- public async getBlockByArchive(archive: Fr): Promise<L2Block | undefined> {
768
- return await this.blockSource.getL2BlockByArchive(archive);
769
- }
770
-
771
- /**
772
- * Method to request blocks. Will attempt to return all requested blocks but will return only those available.
773
- * @param from - The start of the range of blocks to return.
774
- * @param limit - The maximum number of blocks to obtain.
775
- * @returns The blocks requested.
776
- */
777
- public async getBlocks(from: BlockNumber, limit: number): Promise<L2Block[]> {
778
- return (await this.blockSource.getBlocks(from, BlockNumber(limit))) ?? [];
779
- }
780
-
781
- public async getCheckpoints(from: CheckpointNumber, limit: number): Promise<PublishedCheckpoint[]> {
782
- return (await this.blockSource.getCheckpoints(from, limit)) ?? [];
783
- }
784
-
785
- public async getCheckpointedBlocks(from: BlockNumber, limit: number) {
786
- return (await this.blockSource.getCheckpointedBlocks(from, limit)) ?? [];
787
- }
788
-
789
- public getCheckpointsDataForEpoch(epochNumber: EpochNumber) {
790
- return this.blockSource.getCheckpointsDataForEpoch(epochNumber);
791
- }
792
-
793
1107
  public async getCurrentMinFees(): Promise<GasFees> {
794
1108
  return await this.feeProvider.getCurrentMinFees();
795
1109
  }
@@ -807,26 +1121,6 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
807
1121
  return GasFees.from({ feePerDaGas: 0n, feePerL2Gas: 0n });
808
1122
  }
809
1123
 
810
- /**
811
- * Method to fetch the latest block number synchronized by the node.
812
- * @returns The block number.
813
- */
814
- public async getBlockNumber(): Promise<BlockNumber> {
815
- return await this.blockSource.getBlockNumber();
816
- }
817
-
818
- public async getProvenBlockNumber(): Promise<BlockNumber> {
819
- return await this.blockSource.getProvenBlockNumber();
820
- }
821
-
822
- public async getCheckpointedBlockNumber(): Promise<BlockNumber> {
823
- return await this.blockSource.getCheckpointedL2BlockNumber();
824
- }
825
-
826
- public getCheckpointNumber(): Promise<CheckpointNumber> {
827
- return this.blockSource.getCheckpointNumber();
828
- }
829
-
830
1124
  /**
831
1125
  * Method to fetch the version of the package.
832
1126
  * @returns The node package version
@@ -859,69 +1153,12 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
859
1153
  return this.contractDataSource.getContract(address);
860
1154
  }
861
1155
 
862
- public async getPrivateLogsByTags(
863
- tags: SiloedTag[],
864
- page?: number,
865
- referenceBlock?: BlockHash,
866
- ): Promise<TxScopedL2Log[][]> {
867
- let upToBlockNumber: BlockNumber | undefined;
868
- if (referenceBlock) {
869
- const initialBlockHash = await this.#getInitialHeaderHash();
870
- if (referenceBlock.equals(initialBlockHash)) {
871
- upToBlockNumber = BlockNumber(0);
872
- } else {
873
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
874
- if (!header) {
875
- throw new Error(
876
- `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
877
- );
878
- }
879
- upToBlockNumber = header.globalVariables.blockNumber;
880
- }
881
- }
882
- return this.logsSource.getPrivateLogsByTags(tags, page, upToBlockNumber);
883
- }
884
-
885
- public async getPublicLogsByTagsFromContract(
886
- contractAddress: AztecAddress,
887
- tags: Tag[],
888
- page?: number,
889
- referenceBlock?: BlockHash,
890
- ): Promise<TxScopedL2Log[][]> {
891
- let upToBlockNumber: BlockNumber | undefined;
892
- if (referenceBlock) {
893
- const initialBlockHash = await this.#getInitialHeaderHash();
894
- if (referenceBlock.equals(initialBlockHash)) {
895
- upToBlockNumber = BlockNumber(0);
896
- } else {
897
- const header = await this.blockSource.getBlockHeaderByHash(referenceBlock);
898
- if (!header) {
899
- throw new Error(
900
- `Block ${referenceBlock.toString()} not found in the node. This might indicate a reorg has occurred.`,
901
- );
902
- }
903
- upToBlockNumber = header.globalVariables.blockNumber;
904
- }
905
- }
906
- return this.logsSource.getPublicLogsByTagsFromContract(contractAddress, tags, page, upToBlockNumber);
907
- }
908
-
909
- /**
910
- * Gets public logs based on the provided filter.
911
- * @param filter - The filter to apply to the logs.
912
- * @returns The requested logs.
913
- */
914
- getPublicLogs(filter: LogFilter): Promise<GetPublicLogsResponse> {
915
- return this.logsSource.getPublicLogs(filter);
1156
+ public getPrivateLogsByTags(query: PrivateLogsQuery): Promise<LogResult[][]> {
1157
+ return this.logsSource.getPrivateLogsByTags(query);
916
1158
  }
917
1159
 
918
- /**
919
- * Gets contract class logs based on the provided filter.
920
- * @param filter - The filter to apply to the logs.
921
- * @returns The requested logs.
922
- */
923
- getContractClassLogs(filter: LogFilter): Promise<GetContractClassLogsResponse> {
924
- return this.logsSource.getContractClassLogs(filter);
1160
+ public getPublicLogsByTags(query: PublicLogsQuery): Promise<LogResult[][]> {
1161
+ return this.logsSource.getPublicLogsByTags(query);
925
1162
  }
926
1163
 
927
1164
  /**
@@ -944,32 +1181,48 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
944
1181
  throw new Error(`Invalid tx: ${reason}`);
945
1182
  }
946
1183
 
947
- await this.p2pClient!.sendTx(tx);
1184
+ try {
1185
+ await this.p2pClient!.sendTx(tx);
1186
+ } catch (err) {
1187
+ this.metrics.receivedTx(timer.ms(), false);
1188
+ this.log.warn(`Mempool rejected tx ${txHash}: ${(err as Error).message}`, { txHash });
1189
+ throw err;
1190
+ }
948
1191
  const duration = timer.ms();
949
1192
  this.metrics.receivedTx(duration, true);
950
1193
  this.log.info(`Received tx ${txHash} in ${duration}ms`, { txHash });
951
1194
  }
952
1195
 
953
- public async getTxReceipt(txHash: TxHash): Promise<TxReceipt> {
1196
+ public async getTxReceipt<TGetTxReceiptOptions extends GetTxReceiptOptions = {}>(
1197
+ txHash: TxHash,
1198
+ options?: TGetTxReceiptOptions,
1199
+ ): Promise<TxReceipt<TGetTxReceiptOptions>> {
954
1200
  // Check the tx pool status first. If the tx is known to the pool (pending or mined), we'll use that
955
- // as a fallback if we don't find a settled receipt in the archiver.
1201
+ // as a fallback if we don't find a mined tx effect in the archiver.
956
1202
  const txPoolStatus = await this.p2pClient.getTxStatus(txHash);
957
1203
  const isKnownToPool = txPoolStatus === 'pending' || txPoolStatus === 'mined';
958
1204
 
959
- // Then get the actual tx from the archiver, which tracks every tx in a mined block.
960
- const settledTxReceipt = await this.blockSource.getSettledTxReceipt(txHash);
1205
+ // Then get the raw tx effect from the archiver, which tracks every tx in a mined block.
1206
+ const indexed = await this.blockSource.getTxEffect(txHash);
961
1207
 
962
1208
  let receipt: TxReceipt;
963
- if (settledTxReceipt) {
964
- receipt = settledTxReceipt;
1209
+ if (indexed) {
1210
+ receipt = await this.#assembleMinedReceipt(indexed, options);
965
1211
  } else if (isKnownToPool) {
966
1212
  // If the tx is in the pool but not in the archiver, it's pending.
967
1213
  // This handles race conditions between archiver and p2p, where the archiver
968
1214
  // has pruned the block in which a tx was mined, but p2p has not caught up yet.
969
- receipt = new TxReceipt(txHash, TxStatus.PENDING, undefined, undefined);
1215
+ let tx: Tx | undefined;
1216
+ if (options?.includePendingTx) {
1217
+ // The tx may have left the pool since we checked its status (mined or dropped); in that case we
1218
+ // leave `tx` unset and still return a pending receipt.
1219
+ const pendingTx = await this.p2pClient.getTxByHashFromPool(txHash);
1220
+ tx = pendingTx && !options.includeProof ? pendingTx.withoutProof() : pendingTx;
1221
+ }
1222
+ receipt = new PendingTxReceipt(txHash, tx);
970
1223
  } else {
971
1224
  // Otherwise, if we don't know the tx, we consider it dropped.
972
- receipt = new TxReceipt(txHash, TxStatus.DROPPED, undefined, 'Tx dropped by P2P node');
1225
+ receipt = new DroppedTxReceipt(txHash, 'Tx dropped by P2P node');
973
1226
  }
974
1227
 
975
1228
  this.debugLogStore.decorateReceiptWithLogs(txHash.toString(), receipt);
@@ -977,6 +1230,44 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
977
1230
  return receipt;
978
1231
  }
979
1232
 
1233
+ /**
1234
+ * Assembles a {@link MinedTxReceipt} from a raw {@link IndexedTxEffect}, deriving the finalization status from the
1235
+ * cached L2 tips and the epoch from the block's slot number.
1236
+ */
1237
+ async #assembleMinedReceipt(indexed: IndexedTxEffect, options?: GetTxReceiptOptions): Promise<MinedTxReceipt> {
1238
+ const blockNumber = indexed.l2BlockNumber;
1239
+ const [tips, l1Constants] = await Promise.all([this.blockSource.getL2Tips(), this.blockSource.getL1Constants()]);
1240
+
1241
+ const status = this.#deriveMinedStatus(blockNumber, tips);
1242
+ const epochNumber = getEpochAtSlot(indexed.slotNumber, l1Constants);
1243
+
1244
+ return new MinedTxReceipt(
1245
+ indexed.data.txHash,
1246
+ status,
1247
+ MinedTxReceipt.executionResultFromRevertCode(indexed.data.revertCode),
1248
+ indexed.data.transactionFee.toBigInt(),
1249
+ indexed.l2BlockHash,
1250
+ blockNumber,
1251
+ indexed.slotNumber,
1252
+ indexed.txIndexInBlock,
1253
+ epochNumber,
1254
+ options?.includeTxEffect ? indexed.data : undefined,
1255
+ /*debugLogs=*/ undefined,
1256
+ );
1257
+ }
1258
+
1259
+ #deriveMinedStatus(blockNumber: BlockNumber, tips: L2Tips): MinedTxStatus {
1260
+ if (blockNumber <= tips.finalized.block.number) {
1261
+ return TxStatus.FINALIZED;
1262
+ } else if (blockNumber <= tips.proven.block.number) {
1263
+ return TxStatus.PROVEN;
1264
+ } else if (blockNumber <= tips.checkpointed.block.number) {
1265
+ return TxStatus.CHECKPOINTED;
1266
+ } else {
1267
+ return TxStatus.PROPOSED;
1268
+ }
1269
+ }
1270
+
980
1271
  public getTxEffect(txHash: TxHash): Promise<IndexedTxEffect | undefined> {
981
1272
  return this.blockSource.getTxEffect(txHash);
982
1273
  }
@@ -986,11 +1277,11 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
986
1277
  */
987
1278
  public async stop() {
988
1279
  this.log.info(`Stopping Aztec Node`);
989
- await tryStop(this.validatorsSentinel);
990
- await tryStop(this.epochPruneWatcher);
1280
+ await this.stopStartedWatchers();
991
1281
  await tryStop(this.slasherClient);
992
1282
  await Promise.all([tryStop(this.peerProofVerifier), tryStop(this.rpcProofVerifier)]);
993
1283
  await tryStop(this.sequencer);
1284
+ await tryStop(this.automineSequencer);
994
1285
  await tryStop(this.proverNode);
995
1286
  await tryStop(this.p2pClient);
996
1287
  await tryStop(this.worldStateSynchronizer);
@@ -1158,35 +1449,37 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1158
1449
 
1159
1450
  public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
1160
1451
  const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1161
- return messageIndex ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1162
- }
1163
-
1164
- /**
1165
- * Returns whether an L1 to L2 message is synced by archiver and if it's ready to be included in a block.
1166
- * @param l1ToL2Message - The L1 to L2 message to check.
1167
- * @returns Whether the message is synced and ready to be included in a block.
1168
- */
1169
- public async isL1ToL2MessageSynced(l1ToL2Message: Fr): Promise<boolean> {
1170
- const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
1171
- return messageIndex !== undefined;
1452
+ return messageIndex !== undefined ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
1172
1453
  }
1173
1454
 
1174
1455
  /**
1175
1456
  * Returns all the L2 to L1 messages in an epoch.
1457
+ *
1458
+ * @deprecated Use {@link getL2ToL1MembershipWitness} to get an L2-to-L1 message witness directly.
1459
+ *
1176
1460
  * @param epoch - The epoch at which to get the data.
1177
1461
  * @returns The L2 to L1 messages (empty array if the epoch is not found).
1178
1462
  */
1179
1463
  public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
1180
- // Assumes `getCheckpointedBlocksForEpoch` returns blocks in ascending order of block number.
1181
- const checkpointedBlocks = await this.blockSource.getCheckpointedBlocksForEpoch(epoch);
1182
- const blocksInCheckpoints = chunkBy(checkpointedBlocks, cb => cb.block.header.globalVariables.slotNumber).map(
1183
- group => group.map(cb => cb.block),
1184
- );
1185
- return blocksInCheckpoints.map(blocks =>
1186
- blocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1464
+ const blocks = await this.blockSource.getBlocks({ epoch, onlyCheckpointed: true });
1465
+ const blocksInCheckpoints = chunkBy(blocks, block => block.header.globalVariables.slotNumber);
1466
+ return blocksInCheckpoints.map(slotBlocks =>
1467
+ slotBlocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
1187
1468
  );
1188
1469
  }
1189
1470
 
1471
+ /**
1472
+ * Returns the L2-to-L1 membership witness for a message in `txHash`. Passthrough to the
1473
+ * archiver's locally-cached resolver — see {@link Archiver.getL2ToL1MembershipWitness}.
1474
+ */
1475
+ public getL2ToL1MembershipWitness(
1476
+ txHash: TxHash,
1477
+ message: Fr,
1478
+ messageIndexInTx?: number,
1479
+ ): Promise<L2ToL1MembershipWitness | undefined> {
1480
+ return this.blockSource.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
1481
+ }
1482
+
1190
1483
  public async getNullifierMembershipWitness(
1191
1484
  referenceBlock: BlockParameter,
1192
1485
  nullifier: Fr,
@@ -1257,49 +1550,20 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1257
1550
  return preimage.leaf.value;
1258
1551
  }
1259
1552
 
1260
- public async getBlockHeader(block: BlockParameter = 'latest'): Promise<BlockHeader | undefined> {
1261
- if (BlockHash.isBlockHash(block)) {
1262
- const initialBlockHash = await this.#getInitialHeaderHash();
1263
- if (block.equals(initialBlockHash)) {
1264
- // Block source doesn't handle initial header so we need to handle the case separately.
1265
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1266
- }
1267
- return this.blockSource.getBlockHeaderByHash(block);
1268
- } else {
1269
- // Block source doesn't handle initial header so we need to handle the case separately.
1270
- const blockNumber = block === 'latest' ? await this.getBlockNumber() : (block as BlockNumber);
1271
- if (blockNumber === BlockNumber.ZERO) {
1272
- return this.worldStateSynchronizer.getCommitted().getInitialHeader();
1273
- }
1274
- return this.blockSource.getBlockHeader(block);
1275
- }
1276
- }
1277
-
1278
- /**
1279
- * Get a block header specified by its archive root.
1280
- * @param archive - The archive root being requested.
1281
- * @returns The requested block header.
1282
- */
1283
- public async getBlockHeaderByArchive(archive: Fr): Promise<BlockHeader | undefined> {
1284
- return await this.blockSource.getBlockHeaderByArchive(archive);
1285
- }
1286
-
1287
- public getBlockData(number: BlockNumber): Promise<BlockData | undefined> {
1288
- return this.blockSource.getBlockData(number);
1289
- }
1290
-
1291
- public getBlockDataByArchive(archive: Fr): Promise<BlockData | undefined> {
1292
- return this.blockSource.getBlockDataByArchive(archive);
1293
- }
1294
-
1295
1553
  /**
1296
1554
  * Simulates the public part of a transaction with the current state.
1297
1555
  * @param tx - The transaction to simulate.
1556
+ * @param skipFeeEnforcement - If true, fee enforcement is skipped.
1557
+ * @param overrides - Optional pre-simulation overrides applied to the ephemeral fork and contract DB.
1298
1558
  **/
1299
1559
  @trackSpan('AztecNodeService.simulatePublicCalls', (tx: Tx) => ({
1300
1560
  [Attributes.TX_HASH]: tx.getTxHash().toString(),
1301
1561
  }))
1302
- public async simulatePublicCalls(tx: Tx, skipFeeEnforcement = false): Promise<PublicSimulationOutput> {
1562
+ public async simulatePublicCalls(
1563
+ tx: Tx,
1564
+ skipFeeEnforcement = false,
1565
+ overrides?: SimulationOverrides,
1566
+ ): Promise<PublicSimulationOutput> {
1303
1567
  // Check total gas limit for simulation
1304
1568
  const gasSettings = tx.data.constants.txContext.gasSettings;
1305
1569
  const txGasLimit = gasSettings.gasLimits.l2Gas;
@@ -1315,7 +1579,8 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1315
1579
  }
1316
1580
 
1317
1581
  const txHash = tx.getTxHash();
1318
- const latestBlockNumber = await this.blockSource.getBlockNumber();
1582
+ const l2Tips = await this.blockSource.getL2Tips();
1583
+ const latestBlockNumber = l2Tips.proposed.number;
1319
1584
  const blockNumber = BlockNumber.add(latestBlockNumber, 1);
1320
1585
 
1321
1586
  // If sequencer is not initialized, we just set these values to zero for simulation.
@@ -1327,6 +1592,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1327
1592
  coinbase,
1328
1593
  feeRecipient,
1329
1594
  );
1595
+
1330
1596
  const publicProcessorFactory = new PublicProcessorFactory(
1331
1597
  this.contractDataSource,
1332
1598
  new DateProvider(),
@@ -1342,40 +1608,77 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1342
1608
 
1343
1609
  // Ensure world-state has caught up with the latest block we loaded from the archiver
1344
1610
  await this.worldStateSynchronizer.syncImmediate(latestBlockNumber);
1345
- const merkleTreeFork = await this.worldStateSynchronizer.fork();
1346
- try {
1347
- const config = PublicSimulatorConfig.from({
1348
- skipFeeEnforcement,
1349
- collectDebugLogs: true,
1350
- collectHints: false,
1351
- collectCallMetadata: true,
1352
- collectStatistics: false,
1353
- collectionLimits: CollectionLimitsConfig.from({
1354
- maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads,
1355
- }),
1356
- });
1357
- const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config);
1358
-
1359
- // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1360
- const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1361
- // REFACTOR: Consider returning the error rather than throwing
1362
- if (failedTxs.length) {
1363
- this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
1364
- throw failedTxs[0].error;
1365
- }
1366
1611
 
1367
- const [processedTx] = processedTxs;
1368
- return new PublicSimulationOutput(
1369
- processedTx.revertReason,
1370
- processedTx.globalVariables,
1371
- processedTx.txEffect,
1372
- returns,
1373
- processedTx.gasUsed,
1374
- debugLogs,
1612
+ // If we detect the next block would start a new checkpoint, then insert L1-to-L2 messages into
1613
+ // the world state tree so simulation can take them into account. We detect if the next block would
1614
+ // start a new checkpoint by checking if the proposed checkpoint's block number matches the latest block number,
1615
+ // which means the next block would be the first block of the next checkpoint.
1616
+ const targetCheckpoint = CheckpointNumber(
1617
+ (l2Tips.proposedCheckpoint.checkpoint.number ?? CheckpointNumber.ZERO) + 1,
1618
+ );
1619
+ const nextCheckpointMessages: Fr[] | undefined =
1620
+ l2Tips.proposedCheckpoint.block.number === l2Tips.proposed.number
1621
+ ? await this.l1ToL2MessageSource.getL1ToL2Messages(targetCheckpoint).catch(err => {
1622
+ if (isErrorClass(err, L1ToL2MessagesNotReadyError)) {
1623
+ this.log.warn(
1624
+ `L1-to-L2 messages for checkpoint ${targetCheckpoint} are not ready yet (simulating without them)`,
1625
+ );
1626
+ } else {
1627
+ this.log.error(
1628
+ `Failed to get L1-to-L2 messages for checkpoint ${targetCheckpoint} (simulating without them)`,
1629
+ err,
1630
+ );
1631
+ }
1632
+ return undefined;
1633
+ })
1634
+ : undefined;
1635
+
1636
+ // 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
1637
+ await using merkleTreeFork = await this.worldStateSynchronizer.fork(latestBlockNumber);
1638
+
1639
+ if (nextCheckpointMessages !== undefined) {
1640
+ this.log.debug(
1641
+ `Appending ${nextCheckpointMessages.length} L1-to-L2 messages to the world state tree for the next checkpoint`,
1642
+ { checkpointNumber: l2Tips.proposedCheckpoint.checkpoint.number + 1 },
1375
1643
  );
1376
- } finally {
1377
- await merkleTreeFork.close();
1644
+ await appendL1ToL2MessagesToTree(merkleTreeFork, nextCheckpointMessages);
1378
1645
  }
1646
+ await applyPublicDataOverrides(merkleTreeFork, overrides?.publicStorage);
1647
+
1648
+ const config = PublicSimulatorConfig.from({
1649
+ skipFeeEnforcement,
1650
+ collectDebugLogs: true,
1651
+ collectHints: false,
1652
+ collectCallMetadata: true,
1653
+ collectStatistics: false,
1654
+ collectionLimits: CollectionLimitsConfig.from({
1655
+ maxDebugLogMemoryReads: this.config.rpcSimulatePublicMaxDebugLogMemoryReads,
1656
+ }),
1657
+ });
1658
+
1659
+ const contractsDB = new PublicContractsDB(this.contractDataSource, this.log.getBindings());
1660
+ if (overrides?.contracts) {
1661
+ contractsDB.addContracts(Object.values(overrides.contracts).map(({ instance }) => instance));
1662
+ }
1663
+ const processor = publicProcessorFactory.create(merkleTreeFork, newGlobalVariables, config, contractsDB);
1664
+
1665
+ // REFACTOR: Consider merging ProcessReturnValues into ProcessedTx
1666
+ const [processedTxs, failedTxs, _usedTxs, returns, debugLogs] = await processor.process([tx]);
1667
+ // REFACTOR: Consider returning the error rather than throwing
1668
+ if (failedTxs.length) {
1669
+ this.log.warn(`Simulated tx ${txHash} fails: ${failedTxs[0].error}`, { txHash });
1670
+ throw failedTxs[0].error;
1671
+ }
1672
+
1673
+ const [processedTx] = processedTxs;
1674
+ return new PublicSimulationOutput(
1675
+ processedTx.revertReason,
1676
+ processedTx.globalVariables,
1677
+ processedTx.txEffect,
1678
+ returns,
1679
+ processedTx.gasUsed,
1680
+ debugLogs,
1681
+ );
1379
1682
  }
1380
1683
 
1381
1684
  public async isValidTx(
@@ -1423,7 +1726,18 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1423
1726
 
1424
1727
  public async setConfig(config: Partial<AztecNodeAdminConfig>): Promise<void> {
1425
1728
  const newConfig = { ...this.config, ...config };
1426
- this.sequencer?.updateConfig(config);
1729
+ // If the sequencer is currently paused via pauseSequencer(), record the caller's desired
1730
+ // minTxsPerBlock as the restore value (so resumeSequencer applies it) and keep the freeze
1731
+ // (MAX_SAFE_INTEGER) applied to the underlying sequencer. Without this guard, forwarding
1732
+ // the new minTxsPerBlock to the sequencer would silently unpause block production while
1733
+ // pauseSequencer() still considers it paused.
1734
+ const sequencerUpdate = { ...config };
1735
+ if (this.sequencerPausedMinTxsPerBlock !== undefined && sequencerUpdate.minTxsPerBlock !== undefined) {
1736
+ this.sequencerPausedMinTxsPerBlock = sequencerUpdate.minTxsPerBlock;
1737
+ delete sequencerUpdate.minTxsPerBlock;
1738
+ }
1739
+ this.sequencer?.updateConfig(sequencerUpdate);
1740
+ this.automineSequencer?.updateConfig(sequencerUpdate);
1427
1741
  this.slasherClient?.updateConfig(config);
1428
1742
  this.validatorsSentinel?.updateConfig(config);
1429
1743
  await this.p2pClient.updateP2PConfig(config);
@@ -1451,7 +1765,7 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1451
1765
  classRegistry: ProtocolContractAddress.ContractClassRegistry,
1452
1766
  feeJuice: ProtocolContractAddress.FeeJuice,
1453
1767
  instanceRegistry: ProtocolContractAddress.ContractInstanceRegistry,
1454
- multiCallEntrypoint: ProtocolContractAddress.MultiCallEntrypoint,
1768
+ multiCallEntrypoint: STANDARD_MULTI_CALL_ENTRYPOINT_ADDRESS,
1455
1769
  });
1456
1770
  }
1457
1771
 
@@ -1568,6 +1882,41 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1568
1882
  return Promise.resolve();
1569
1883
  }
1570
1884
 
1885
+ public pauseSequencer(): Promise<void> {
1886
+ if (this.automineSequencer) {
1887
+ this.automineSequencer.pause();
1888
+ return Promise.resolve();
1889
+ }
1890
+ if (this.sequencer) {
1891
+ if (this.sequencerPausedMinTxsPerBlock === undefined) {
1892
+ this.sequencerPausedMinTxsPerBlock = this.sequencer.getSequencer().getConfig().minTxsPerBlock ?? 0;
1893
+ this.sequencer.updateConfig({ minTxsPerBlock: Number.MAX_SAFE_INTEGER });
1894
+ this.log.info(`Sequencer paused (minTxsPerBlock set to MAX_SAFE_INTEGER)`, {
1895
+ previousMinTxsPerBlock: this.sequencerPausedMinTxsPerBlock,
1896
+ });
1897
+ }
1898
+ return Promise.resolve();
1899
+ }
1900
+ throw new BadRequestError('Cannot pause sequencer: no sequencer is running');
1901
+ }
1902
+
1903
+ public resumeSequencer(): Promise<void> {
1904
+ if (this.automineSequencer) {
1905
+ this.automineSequencer.resume();
1906
+ return Promise.resolve();
1907
+ }
1908
+ if (this.sequencer) {
1909
+ if (this.sequencerPausedMinTxsPerBlock !== undefined) {
1910
+ const restored = this.sequencerPausedMinTxsPerBlock;
1911
+ this.sequencerPausedMinTxsPerBlock = undefined;
1912
+ this.sequencer.updateConfig({ minTxsPerBlock: restored });
1913
+ this.log.info(`Sequencer resumed (minTxsPerBlock restored)`, { minTxsPerBlock: restored });
1914
+ }
1915
+ return Promise.resolve();
1916
+ }
1917
+ throw new BadRequestError('Cannot resume sequencer: no sequencer is running');
1918
+ }
1919
+
1571
1920
  public getSlashOffenses(round: bigint | 'all' | 'current'): Promise<Offense[]> {
1572
1921
  if (!this.slasherClient) {
1573
1922
  throw new Error(`Slasher client not enabled`);
@@ -1668,6 +2017,10 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1668
2017
  }
1669
2018
 
1670
2019
  public async mineBlock(): Promise<void> {
2020
+ if (this.automineSequencer) {
2021
+ await this.automineSequencer.buildEmptyBlock();
2022
+ return;
2023
+ }
1671
2024
  if (!this.sequencer) {
1672
2025
  throw new BadRequestError('Cannot mine block: no sequencer is running');
1673
2026
  }
@@ -1701,69 +2054,58 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1701
2054
  }
1702
2055
  }
1703
2056
 
1704
- #getInitialHeaderHash(): Promise<BlockHash> {
1705
- if (!this.initialHeaderHashPromise) {
1706
- this.initialHeaderHashPromise = this.worldStateSynchronizer.getCommitted().getInitialHeader().hash();
1707
- }
1708
- return this.initialHeaderHashPromise;
1709
- }
1710
-
1711
2057
  /**
1712
2058
  * Returns an instance of MerkleTreeOperations having first ensured the world state is fully synched
1713
2059
  * @param block - The block parameter (block number, block hash, or 'latest') at which to get the data.
1714
2060
  * @returns An instance of a committed MerkleTreeOperations
1715
2061
  */
1716
2062
  protected async getWorldState(block: BlockParameter) {
2063
+ const query = this.normalizeBlockParameter(block);
2064
+
2065
+ // When the request anchors on a specific block hash, resolve it against the archiver up front and
2066
+ // drive the world-state sync to that exact block number and hash. Resolving against the archiver
2067
+ // first fails fast with a clear reorg error if the hash is unknown, and passing the hash to the
2068
+ // synchronizer makes the sync reorg-aware: it barriers until the archive-tree commit for that block
2069
+ // has landed and verifies it matches the requested fork, instead of syncing to bare latest height
2070
+ // and then racing the snapshot read below against an in-flight archive-tree write.
2071
+ const requestedHash = 'hash' in query ? query.hash : undefined;
2072
+ const anchorBlockNumber = requestedHash !== undefined ? await this.resolveBlockNumber(query) : undefined;
2073
+
1717
2074
  let blockSyncedTo: BlockNumber = BlockNumber.ZERO;
1718
2075
  try {
1719
2076
  // Attempt to sync the world state if necessary
1720
- blockSyncedTo = await this.#syncWorldState();
2077
+ blockSyncedTo = await this.#syncWorldState(anchorBlockNumber, requestedHash);
1721
2078
  } catch (err) {
1722
2079
  this.log.error(`Error getting world state: ${err}`);
1723
2080
  }
1724
2081
 
1725
- if (block === 'latest') {
1726
- this.log.debug(`Using committed db for block 'latest', world state synced upto ${blockSyncedTo}`);
2082
+ if ('tag' in query && query.tag === 'proposed') {
2083
+ this.log.debug(`Using committed db for latest block, world state synced upto ${blockSyncedTo}`);
1727
2084
  return this.worldStateSynchronizer.getCommitted();
1728
2085
  }
1729
2086
 
1730
- // Get the block number, either directly from the parameter or by quering the archiver with the block hash
1731
- let blockNumber: BlockNumber;
1732
- if (BlockHash.isBlockHash(block)) {
1733
- const initialBlockHash = await this.#getInitialHeaderHash();
1734
- if (block.equals(initialBlockHash)) {
1735
- // Block 0 is a first-class historical block: its state lives in the trees' persisted
1736
- // block-0 payload. Resolving the genesis hash to block number 0 lets the snapshot path
1737
- // pin reads to genesis state even after the node has advanced past it.
1738
- blockNumber = BlockNumber.ZERO;
1739
- } else {
1740
- const header = await this.blockSource.getBlockHeaderByHash(block);
1741
- if (!header) {
1742
- throw new Error(
1743
- `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.`,
1744
- );
1745
- }
1746
- blockNumber = header.getBlockNumber();
1747
- }
1748
- } else {
1749
- blockNumber = block as BlockNumber;
1750
- }
2087
+ const blockNumber = anchorBlockNumber ?? (await this.resolveBlockNumber(query));
1751
2088
 
1752
2089
  // Check it's within world state sync range
1753
2090
  if (blockNumber > blockSyncedTo) {
1754
- throw new Error(`Queried block ${block} not yet synced by the node (node is synced upto ${blockSyncedTo}).`);
2091
+ throw new Error(
2092
+ `Queried block ${inspectBlockParameter(block)} not yet synced by the node (node is synced upto ${blockSyncedTo}).`,
2093
+ );
1755
2094
  }
1756
2095
  this.log.debug(`Using snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
1757
2096
 
1758
2097
  const snapshot = this.worldStateSynchronizer.getSnapshot(blockNumber);
1759
2098
 
1760
- // Double-check world-state synced to the same block hash as was requested
1761
- if (BlockHash.isBlockHash(block)) {
2099
+ // Double-check world-state synced to the same block hash as was requested.
2100
+ // Block 0 is skipped: the snapshot returned by `getSnapshot(0)` is the *pre*-genesis archive
2101
+ // (size 0), so leaf 0 is not yet inserted from that snapshot's view even though block 0's hash
2102
+ // does live at archive index 0 in the committed tree. The genesis hash is already validated by
2103
+ // the archiver when it resolves the hash query to block number 0.
2104
+ if (requestedHash !== undefined && blockNumber !== BlockNumber.ZERO) {
1762
2105
  const blockHash = await snapshot.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
1763
- if (!blockHash || !block.equals(blockHash)) {
1764
- const initialBlockHash = await this.#getInitialHeaderHash();
2106
+ if (!blockHash || !requestedHash.equals(blockHash)) {
1765
2107
  throw new Error(
1766
- `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.`,
2108
+ `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.`,
1767
2109
  );
1768
2110
  }
1769
2111
  }
@@ -1771,31 +2113,33 @@ export class AztecNodeService implements AztecNode, AztecNodeAdmin, AztecNodeDeb
1771
2113
  return snapshot;
1772
2114
  }
1773
2115
 
1774
- /** Resolves a block parameter to a block number. */
2116
+ /** Resolves any {@link BlockParameter} variant to a concrete block number. */
1775
2117
  protected async resolveBlockNumber(block: BlockParameter): Promise<BlockNumber> {
1776
- if (block === 'latest') {
1777
- return BlockNumber(await this.blockSource.getBlockNumber());
1778
- }
1779
- if (BlockHash.isBlockHash(block)) {
1780
- const initialBlockHash = await this.#getInitialHeaderHash();
1781
- if (block.equals(initialBlockHash)) {
1782
- return BlockNumber.ZERO;
2118
+ const query = this.normalizeBlockParameter(block);
2119
+ const blockNumber = await this.blockSource.getBlockNumber(query);
2120
+ if (blockNumber === undefined) {
2121
+ if ('hash' in query) {
2122
+ throw new Error(
2123
+ `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.`,
2124
+ );
1783
2125
  }
1784
- const header = await this.blockSource.getBlockHeaderByHash(block);
1785
- if (!header) {
1786
- throw new Error(`Block hash ${block.toString()} not found.`);
2126
+ if ('archive' in query) {
2127
+ throw new Error(`Block with archive ${query.archive.toString()} not found.`);
1787
2128
  }
1788
- return header.getBlockNumber();
2129
+ throw new Error(`Block not found for ${inspectBlockParameter(block)}.`);
1789
2130
  }
1790
- return block as BlockNumber;
2131
+ return blockNumber;
1791
2132
  }
1792
2133
 
1793
2134
  /**
1794
- * Ensure we fully sync the world state
2135
+ * Ensure the world state is synced.
2136
+ * @param targetBlockNumber - Block to sync up to. Defaults to the latest block known to the archiver.
2137
+ * @param blockHash - If provided, the synchronizer verifies the block at `targetBlockNumber` matches this
2138
+ * hash, resyncing (and so detecting reorgs) if it does not yet match or has been reorged away.
1795
2139
  * @returns A promise that fulfils once the world state is synced
1796
2140
  */
1797
- async #syncWorldState(): Promise<BlockNumber> {
1798
- const blockSourceHeight = await this.blockSource.getBlockNumber();
1799
- return await this.worldStateSynchronizer.syncImmediate(blockSourceHeight);
2141
+ async #syncWorldState(targetBlockNumber?: BlockNumber, blockHash?: BlockHash): Promise<BlockNumber> {
2142
+ const target = targetBlockNumber ?? (await this.blockSource.getBlockNumber());
2143
+ return await this.worldStateSynchronizer.syncImmediate(target, blockHash);
1800
2144
  }
1801
2145
  }