@aztec-labs/validator-client 6.0.0-nightly.20260829

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 (62) hide show
  1. package/README.md +327 -0
  2. package/dest/checkpoint_builder.d.ts +92 -0
  3. package/dest/checkpoint_builder.d.ts.map +1 -0
  4. package/dest/checkpoint_builder.js +272 -0
  5. package/dest/config.d.ts +17 -0
  6. package/dest/config.d.ts.map +1 -0
  7. package/dest/config.js +102 -0
  8. package/dest/duties/validation_service.d.ts +65 -0
  9. package/dest/duties/validation_service.d.ts.map +1 -0
  10. package/dest/duties/validation_service.js +128 -0
  11. package/dest/factory.d.ts +41 -0
  12. package/dest/factory.d.ts.map +1 -0
  13. package/dest/factory.js +19 -0
  14. package/dest/index.d.ts +7 -0
  15. package/dest/index.d.ts.map +1 -0
  16. package/dest/index.js +6 -0
  17. package/dest/key_store/ha_key_store.d.ts +99 -0
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  19. package/dest/key_store/ha_key_store.js +208 -0
  20. package/dest/key_store/index.d.ts +6 -0
  21. package/dest/key_store/index.d.ts.map +1 -0
  22. package/dest/key_store/index.js +5 -0
  23. package/dest/key_store/interface.d.ts +104 -0
  24. package/dest/key_store/interface.d.ts.map +1 -0
  25. package/dest/key_store/interface.js +4 -0
  26. package/dest/key_store/local_key_store.d.ts +63 -0
  27. package/dest/key_store/local_key_store.d.ts.map +1 -0
  28. package/dest/key_store/local_key_store.js +83 -0
  29. package/dest/key_store/node_keystore_adapter.d.ts +151 -0
  30. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -0
  31. package/dest/key_store/node_keystore_adapter.js +330 -0
  32. package/dest/key_store/web3signer_key_store.d.ts +74 -0
  33. package/dest/key_store/web3signer_key_store.d.ts.map +1 -0
  34. package/dest/key_store/web3signer_key_store.js +147 -0
  35. package/dest/metrics.d.ts +31 -0
  36. package/dest/metrics.d.ts.map +1 -0
  37. package/dest/metrics.js +101 -0
  38. package/dest/proposal_handler.d.ts +188 -0
  39. package/dest/proposal_handler.d.ts.map +1 -0
  40. package/dest/proposal_handler.js +1438 -0
  41. package/dest/streaming_inbox_checks.d.ts +103 -0
  42. package/dest/streaming_inbox_checks.d.ts.map +1 -0
  43. package/dest/streaming_inbox_checks.js +112 -0
  44. package/dest/validator.d.ts +137 -0
  45. package/dest/validator.d.ts.map +1 -0
  46. package/dest/validator.js +771 -0
  47. package/package.json +110 -0
  48. package/src/checkpoint_builder.ts +449 -0
  49. package/src/config.ts +130 -0
  50. package/src/duties/validation_service.ts +224 -0
  51. package/src/factory.ts +95 -0
  52. package/src/index.ts +6 -0
  53. package/src/key_store/ha_key_store.ts +268 -0
  54. package/src/key_store/index.ts +5 -0
  55. package/src/key_store/interface.ts +120 -0
  56. package/src/key_store/local_key_store.ts +104 -0
  57. package/src/key_store/node_keystore_adapter.ts +397 -0
  58. package/src/key_store/web3signer_key_store.ts +188 -0
  59. package/src/metrics.ts +150 -0
  60. package/src/proposal_handler.ts +1598 -0
  61. package/src/streaming_inbox_checks.ts +198 -0
  62. package/src/validator.ts +1125 -0
package/package.json ADDED
@@ -0,0 +1,110 @@
1
+ {
2
+ "name": "@aztec-labs/validator-client",
3
+ "version": "6.0.0-nightly.20260829",
4
+ "main": "dest/index.js",
5
+ "type": "module",
6
+ "exports": {
7
+ ".": "./dest/index.js",
8
+ "./config": "./dest/config.js",
9
+ "./errors": "./dest/errors/index.js"
10
+ },
11
+ "bin": "./dest/bin/index.js",
12
+ "typedocOptions": {
13
+ "entryPoints": [
14
+ "./src/index.ts"
15
+ ],
16
+ "name": "Aztec validator",
17
+ "tsconfig": "./tsconfig.json"
18
+ },
19
+ "scripts": {
20
+ "start": "node --no-warnings ./dest/bin",
21
+ "build": "yarn clean && ../scripts/tsc.sh",
22
+ "build:dev": "../scripts/tsc.sh --watch",
23
+ "clean": "rm -rf ./dest .tsbuildinfo",
24
+ "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}"
25
+ },
26
+ "inherits": [
27
+ "../package.common.json"
28
+ ],
29
+ "jest": {
30
+ "moduleNameMapper": {
31
+ "^(\\.{1,2}/.*)\\.[cm]?js$": "$1"
32
+ },
33
+ "testRegex": "./src/.*\\.test\\.(js|mjs|ts)$",
34
+ "rootDir": "./src",
35
+ "transform": {
36
+ "^.+\\.tsx?$": [
37
+ "@swc/jest",
38
+ {
39
+ "jsc": {
40
+ "parser": {
41
+ "syntax": "typescript",
42
+ "decorators": true
43
+ },
44
+ "transform": {
45
+ "decoratorVersion": "2022-03"
46
+ }
47
+ }
48
+ }
49
+ ]
50
+ },
51
+ "extensionsToTreatAsEsm": [
52
+ ".ts"
53
+ ],
54
+ "reporters": [
55
+ "default"
56
+ ],
57
+ "testTimeout": 120000,
58
+ "setupFiles": [
59
+ "../../foundation/src/jest/setup.mjs"
60
+ ],
61
+ "testEnvironment": "../../foundation/src/jest/env.mjs",
62
+ "setupFilesAfterEnv": [
63
+ "../../foundation/src/jest/setupAfterEnv.mjs"
64
+ ]
65
+ },
66
+ "dependencies": {
67
+ "@aztec-labs/archiver": "6.0.0-nightly.20260829",
68
+ "@aztec-labs/blob-client": "6.0.0-nightly.20260829",
69
+ "@aztec-labs/blob-lib": "6.0.0-nightly.20260829",
70
+ "@aztec-labs/constants": "6.0.0-nightly.20260829",
71
+ "@aztec-labs/epoch-cache": "6.0.0-nightly.20260829",
72
+ "@aztec-labs/ethereum": "6.0.0-nightly.20260829",
73
+ "@aztec-labs/foundation": "6.0.0-nightly.20260829",
74
+ "@aztec-labs/node-keystore": "6.0.0-nightly.20260829",
75
+ "@aztec-labs/p2p": "6.0.0-nightly.20260829",
76
+ "@aztec-labs/prover-client": "6.0.0-nightly.20260829",
77
+ "@aztec-labs/simulator": "6.0.0-nightly.20260829",
78
+ "@aztec-labs/slasher": "6.0.0-nightly.20260829",
79
+ "@aztec-labs/stdlib": "6.0.0-nightly.20260829",
80
+ "@aztec-labs/telemetry-client": "6.0.0-nightly.20260829",
81
+ "@aztec-labs/validator-ha-signer": "6.0.0-nightly.20260829",
82
+ "@aztec-labs/world-state": "6.0.0-nightly.20260829",
83
+ "koa": "^2.16.1",
84
+ "koa-router": "^13.1.1",
85
+ "tslib": "^2.4.0",
86
+ "viem": "npm:@aztec/viem@2.38.2"
87
+ },
88
+ "devDependencies": {
89
+ "@aztec-labs/noir-protocol-circuits-types": "6.0.0-nightly.20260829",
90
+ "@aztec-labs/protocol-contracts": "6.0.0-nightly.20260829",
91
+ "@electric-sql/pglite": "^0.3.14",
92
+ "@jest/globals": "^30.0.0",
93
+ "@types/jest": "^30.0.0",
94
+ "@types/node": "^22.15.17",
95
+ "@typescript/native-preview": "7.0.0-dev.20260113.1",
96
+ "jest": "^30.0.0",
97
+ "jest-mock-extended": "^4.0.0",
98
+ "ts-node": "^10.9.1",
99
+ "typescript": "^5.3.3"
100
+ },
101
+ "files": [
102
+ "dest",
103
+ "src",
104
+ "!*.test.*"
105
+ ],
106
+ "types": "./dest/index.d.ts",
107
+ "engines": {
108
+ "node": ">=20.10"
109
+ }
110
+ }
@@ -0,0 +1,449 @@
1
+ import { NUM_CHECKPOINT_END_MARKER_FIELDS, getNumBlockEndBlobFields } from '@aztec-labs/blob-lib/encoding';
2
+ import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB, MAX_PROCESSABLE_DA_GAS_PER_CHECKPOINT } from '@aztec-labs/constants';
3
+ import { BlockNumber, CheckpointNumber } from '@aztec-labs/foundation/branded-types';
4
+ import { merge, pick, sum } from '@aztec-labs/foundation/collection';
5
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
6
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec-labs/foundation/log';
7
+ import { bufferToHex } from '@aztec-labs/foundation/string';
8
+ import { DateProvider, elapsed } from '@aztec-labs/foundation/timer';
9
+ import { createTxValidatorForBlockBuilding, getDefaultAllowedSetupFunctions } from '@aztec-labs/p2p/msg_validators';
10
+ import { LightweightCheckpointBuilder } from '@aztec-labs/prover-client/light';
11
+ import {
12
+ type AvmSimulator,
13
+ GuardedMerkleTreeOperations,
14
+ PublicContractsDB,
15
+ PublicProcessor,
16
+ createPublicTxSimulatorForBlockBuilding,
17
+ } from '@aztec-labs/simulator/server';
18
+ import { type BlockHash, L2Block } from '@aztec-labs/stdlib/block';
19
+ import { Checkpoint } from '@aztec-labs/stdlib/checkpoint';
20
+ import type { ContractDataSource } from '@aztec-labs/stdlib/contract';
21
+ import type { L1RollupConstants } from '@aztec-labs/stdlib/epoch-helpers';
22
+ import { Gas } from '@aztec-labs/stdlib/gas';
23
+ import {
24
+ type BlockBuilderOptions,
25
+ type BuildBlockInCheckpointResult,
26
+ type FullNodeBlockBuilderConfig,
27
+ FullNodeBlockBuilderConfigKeys,
28
+ type ICheckpointBlockBuilder,
29
+ type ICheckpointsBuilder,
30
+ InsufficientValidTxsError,
31
+ type MerkleTreeWriteOperations,
32
+ type PublicProcessorLimits,
33
+ type WorldStateSynchronizer,
34
+ } from '@aztec-labs/stdlib/interfaces/server';
35
+ import { type DebugLogStore, NullDebugLogStore } from '@aztec-labs/stdlib/logs';
36
+ import { MerkleTreeId } from '@aztec-labs/stdlib/trees';
37
+ import { type CheckpointGlobalVariables, GlobalVariables, StateReference, Tx } from '@aztec-labs/stdlib/tx';
38
+ import { type TelemetryClient, getTelemetryClient } from '@aztec-labs/telemetry-client';
39
+ import { ForkCheckpoint } from '@aztec-labs/world-state';
40
+
41
+ // Re-export for backward compatibility
42
+ export type { BuildBlockInCheckpointResult } from '@aztec-labs/stdlib/interfaces/server';
43
+
44
+ /**
45
+ * Builder for a single checkpoint. Handles building blocks within the checkpoint
46
+ * and completing it.
47
+ */
48
+ export class CheckpointBuilder implements ICheckpointBlockBuilder {
49
+ private log: Logger;
50
+
51
+ /** Persistent contracts DB shared across all blocks in this checkpoint. */
52
+ protected contractsDB: PublicContractsDB;
53
+
54
+ constructor(
55
+ private checkpointBuilder: LightweightCheckpointBuilder,
56
+ private fork: MerkleTreeWriteOperations,
57
+ private config: FullNodeBlockBuilderConfig,
58
+ private contractDataSource: ContractDataSource,
59
+ private dateProvider: DateProvider,
60
+ private telemetryClient: TelemetryClient,
61
+ private avmSimulator: AvmSimulator,
62
+ bindings?: LoggerBindings,
63
+ private debugLogStore: DebugLogStore = new NullDebugLogStore(),
64
+ ) {
65
+ this.log = createLogger('checkpoint-builder', {
66
+ ...bindings,
67
+ instanceId: `checkpoint-${checkpointBuilder.checkpointNumber}`,
68
+ });
69
+ this.contractsDB = new PublicContractsDB(this.contractDataSource, this.log.getBindings());
70
+ }
71
+
72
+ getConstantData(): CheckpointGlobalVariables {
73
+ return this.checkpointBuilder.constants;
74
+ }
75
+
76
+ /**
77
+ * Builds a single block within this checkpoint.
78
+ * Automatically caps gas and blob field limits based on checkpoint-level budgets and prior blocks.
79
+ */
80
+ async buildBlock(
81
+ pendingTxs: Iterable<Tx> | AsyncIterable<Tx>,
82
+ blockNumber: BlockNumber,
83
+ timestamp: bigint,
84
+ opts: BlockBuilderOptions & { expectedEndState?: StateReference },
85
+ ): Promise<BuildBlockInCheckpointResult> {
86
+ const slot = this.checkpointBuilder.constants.slotNumber;
87
+
88
+ this.log.verbose(`Building block ${blockNumber} for slot ${slot} within checkpoint`, {
89
+ slot,
90
+ blockNumber,
91
+ ...opts,
92
+ currentTime: new Date(this.dateProvider.now()),
93
+ });
94
+
95
+ const constants = this.checkpointBuilder.constants;
96
+ const globalVariables = GlobalVariables.from({
97
+ chainId: constants.chainId,
98
+ version: constants.version,
99
+ blockNumber,
100
+ slotNumber: constants.slotNumber,
101
+ timestamp,
102
+ coinbase: constants.coinbase,
103
+ feeRecipient: constants.feeRecipient,
104
+ gasFees: constants.gasFees,
105
+ });
106
+ const { processor, validator } = await this.makeBlockBuilderDeps(globalVariables, this.fork);
107
+
108
+ // Cap gas limits amd available blob fields by remaining checkpoint-level budgets
109
+ const cappedOpts: PublicProcessorLimits & { expectedEndState?: StateReference } = {
110
+ ...opts,
111
+ ...this.capLimitsByCheckpointBudgets(opts),
112
+ };
113
+
114
+ // Create a block-level checkpoint on the contracts DB so we can roll back on failure
115
+ this.contractsDB.createCheckpoint();
116
+ // We execute all merkle tree operations on a world state fork checkpoint
117
+ // This enables us to discard all modifications in the event that we fail to successfully process sufficient transactions
118
+ const forkCheckpoint = await ForkCheckpoint.new(this.fork);
119
+
120
+ try {
121
+ const [publicProcessorDuration, [processedTxs, failedTxs, usedTxs]] = await elapsed(() =>
122
+ processor.process(pendingTxs, cappedOpts, validator),
123
+ );
124
+
125
+ // Throw before updating state if we don't have enough valid txs
126
+ const minValidTxs = opts.minValidTxs ?? 0;
127
+ if (processedTxs.length < minValidTxs) {
128
+ throw new InsufficientValidTxsError(processedTxs.length, minValidTxs, failedTxs);
129
+ }
130
+
131
+ // Commit the fork checkpoint
132
+ await forkCheckpoint.commit();
133
+
134
+ // Add block to checkpoint, inserting this block's streaming L1-to-L2 message bundle (if any) into the fork.
135
+ const { block } = await this.checkpointBuilder.addBlock(
136
+ globalVariables,
137
+ processedTxs,
138
+ opts.l1ToL2Messages ?? [],
139
+ {
140
+ expectedEndState: opts.expectedEndState,
141
+ },
142
+ );
143
+
144
+ this.contractsDB.commitCheckpoint();
145
+
146
+ this.log.debug('Built block within checkpoint', {
147
+ header: block.header.toInspect(),
148
+ processedTxs: processedTxs.map(tx => tx.hash.toString()),
149
+ failedTxs: failedTxs.map(tx => tx.tx.txHash.toString()),
150
+ });
151
+
152
+ return {
153
+ block,
154
+ publicProcessorDuration,
155
+ numTxs: processedTxs.length,
156
+ failedTxs,
157
+ usedTxs,
158
+ };
159
+ } catch (err) {
160
+ // Revert all changes to contracts db
161
+ this.contractsDB.revertCheckpoint();
162
+ // If we reached the point of committing the checkpoint, this does nothing
163
+ // Otherwise it reverts any changes made to the fork for this failed block
164
+ await forkCheckpoint.revert();
165
+ throw err;
166
+ }
167
+ }
168
+
169
+ /** Completes the checkpoint and returns it. */
170
+ async completeCheckpoint(): Promise<Checkpoint> {
171
+ const checkpoint = await this.checkpointBuilder.completeCheckpoint();
172
+
173
+ this.log.verbose(`Completed checkpoint ${checkpoint.number}`, {
174
+ checkpointNumber: checkpoint.number,
175
+ numBlocks: checkpoint.blocks.length,
176
+ archiveRoot: checkpoint.archive.root.toString(),
177
+ });
178
+
179
+ return checkpoint;
180
+ }
181
+
182
+ /** Gets the checkpoint currently in progress. */
183
+ getCheckpoint(): Promise<Checkpoint> {
184
+ return this.checkpointBuilder.clone().completeCheckpoint();
185
+ }
186
+
187
+ /**
188
+ * Caps per-block gas and blob field limits by remaining checkpoint-level budgets.
189
+ * When building a proposal (isBuildingProposal=true), computes a fair share of remaining budget
190
+ * across remaining blocks scaled by the multiplier. When validating, only caps by per-block limit
191
+ * and remaining checkpoint budget (no redistribution or multiplier).
192
+ */
193
+ protected capLimitsByCheckpointBudgets(
194
+ opts: BlockBuilderOptions,
195
+ ): Pick<PublicProcessorLimits, 'maxBlockGas' | 'maxBlobFields' | 'maxTransactions'> {
196
+ const existingBlocks = this.checkpointBuilder.getBlocks();
197
+
198
+ // Remaining L2 gas (mana)
199
+ // IMPORTANT: This assumes mana is computed solely based on L2 gas used in transactions.
200
+ // This may change in the future.
201
+ const usedMana = sum(existingBlocks.map(b => b.header.totalManaUsed.toNumber()));
202
+ const remainingMana = this.config.rollupManaLimit - usedMana;
203
+
204
+ // Remaining DA gas
205
+ const usedDAGas = sum(existingBlocks.map(b => b.computeDAGasUsed())) ?? 0;
206
+ const remainingDAGas = MAX_PROCESSABLE_DA_GAS_PER_CHECKPOINT - usedDAGas;
207
+
208
+ // Remaining blob fields (block blob fields include both tx data and block-end overhead)
209
+ const usedBlobFields = sum(existingBlocks.map(b => b.toBlobFields().length));
210
+ const totalBlobCapacity = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
211
+ const blockEndOverhead = getNumBlockEndBlobFields();
212
+ const maxBlobFieldsForTxs = totalBlobCapacity - usedBlobFields - blockEndOverhead;
213
+
214
+ // Remaining txs
215
+ const usedTxs = sum(existingBlocks.map(b => b.body.txEffects.length));
216
+ const remainingTxs = Math.max(0, (this.config.maxTxsPerCheckpoint ?? Infinity) - usedTxs);
217
+
218
+ // Cap by per-block limit + remaining checkpoint budget
219
+ let cappedL2Gas = Math.min(opts.maxBlockGas?.l2Gas ?? Infinity, remainingMana);
220
+ let cappedDAGas = Math.min(opts.maxBlockGas?.daGas ?? Infinity, remainingDAGas);
221
+ let cappedBlobFields = Math.min(opts.maxBlobFields ?? Infinity, maxBlobFieldsForTxs);
222
+ let cappedMaxTransactions = Math.min(opts.maxTransactions ?? Infinity, remainingTxs);
223
+
224
+ // Proposer mode: further cap by fair share of remaining budget across remaining blocks
225
+ if (opts.isBuildingProposal) {
226
+ const remainingBlocks = Math.max(1, opts.maxBlocksPerCheckpoint - existingBlocks.length);
227
+ const multiplier = opts.perBlockAllocationMultiplier;
228
+ // DA gas and blob fields use a higher multiplier so the largest contract class deploy fits a block.
229
+ const daMultiplier = opts.perBlockDAAllocationMultiplier ?? multiplier;
230
+
231
+ cappedL2Gas = Math.min(cappedL2Gas, Math.ceil((remainingMana / remainingBlocks) * multiplier));
232
+ cappedDAGas = Math.min(cappedDAGas, Math.ceil((remainingDAGas / remainingBlocks) * daMultiplier));
233
+ cappedBlobFields = Math.min(cappedBlobFields, Math.ceil((maxBlobFieldsForTxs / remainingBlocks) * daMultiplier));
234
+ cappedMaxTransactions = Math.min(cappedMaxTransactions, Math.ceil((remainingTxs / remainingBlocks) * multiplier));
235
+ }
236
+
237
+ return {
238
+ maxBlockGas: new Gas(cappedDAGas, cappedL2Gas),
239
+ maxBlobFields: cappedBlobFields,
240
+ maxTransactions: Number.isFinite(cappedMaxTransactions) ? cappedMaxTransactions : undefined,
241
+ };
242
+ }
243
+
244
+ protected async makeBlockBuilderDeps(globalVariables: GlobalVariables, fork: MerkleTreeWriteOperations) {
245
+ const txPublicSetupAllowList = [
246
+ ...(await getDefaultAllowedSetupFunctions()),
247
+ ...(this.config.txPublicSetupAllowListExtend ?? []),
248
+ ];
249
+ const contractsDB = this.contractsDB;
250
+ const guardedFork = new GuardedMerkleTreeOperations(fork);
251
+
252
+ const bindings = this.log.getBindings();
253
+ // Extract the WSDB fork ID so the C++ AVM can modify the same fork in-place; the simulator reads
254
+ // contract data from `contractsDB`, scoped to this fork for the duration of each simulation.
255
+ const wsdbForkId = fork.getRevision().forkId;
256
+ const publicTxSimulator = createPublicTxSimulatorForBlockBuilding(
257
+ this.avmSimulator,
258
+ globalVariables,
259
+ contractsDB,
260
+ wsdbForkId,
261
+ this.telemetryClient,
262
+ bindings,
263
+ this.debugLogStore?.isEnabled ?? false,
264
+ );
265
+
266
+ const processor = new PublicProcessor(
267
+ globalVariables,
268
+ guardedFork,
269
+ contractsDB,
270
+ publicTxSimulator,
271
+ this.dateProvider,
272
+ this.telemetryClient,
273
+ createLogger('simulator:public-processor', bindings),
274
+ this.config,
275
+ this.debugLogStore,
276
+ );
277
+
278
+ const validator = createTxValidatorForBlockBuilding(
279
+ fork,
280
+ this.contractDataSource,
281
+ globalVariables,
282
+ txPublicSetupAllowList,
283
+ this.log.getBindings(),
284
+ );
285
+
286
+ return {
287
+ processor,
288
+ validator,
289
+ };
290
+ }
291
+ }
292
+
293
+ /** Factory for creating checkpoint builders. */
294
+ export class FullNodeCheckpointsBuilder implements ICheckpointsBuilder {
295
+ private log: Logger;
296
+
297
+ constructor(
298
+ private config: FullNodeBlockBuilderConfig & Pick<L1RollupConstants, 'l1GenesisTime' | 'slotDuration'>,
299
+ private worldState: WorldStateSynchronizer,
300
+ private contractDataSource: ContractDataSource,
301
+ private dateProvider: DateProvider,
302
+ private avmSimulator: AvmSimulator,
303
+ private telemetryClient: TelemetryClient = getTelemetryClient(),
304
+ private debugLogStore: DebugLogStore = new NullDebugLogStore(),
305
+ ) {
306
+ this.log = createLogger('checkpoint-builder');
307
+ }
308
+
309
+ public getConfig(): FullNodeBlockBuilderConfig {
310
+ return this.config;
311
+ }
312
+
313
+ public updateConfig(config: Partial<FullNodeBlockBuilderConfig>) {
314
+ this.config = merge(this.config, pick(config, ...FullNodeBlockBuilderConfigKeys));
315
+ }
316
+
317
+ /**
318
+ * Starts a new checkpoint and returns a CheckpointBuilder to build blocks within it.
319
+ */
320
+ async startCheckpoint(
321
+ checkpointNumber: CheckpointNumber,
322
+ constants: CheckpointGlobalVariables,
323
+ feeAssetPriceModifier: bigint,
324
+ previousCheckpointOutHashes: Fr[],
325
+ previousInboxRollingHash: Fr,
326
+ fork: MerkleTreeWriteOperations,
327
+ bindings?: LoggerBindings,
328
+ ): Promise<CheckpointBuilder> {
329
+ const stateReference = await fork.getStateReference();
330
+ const archiveTree = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
331
+
332
+ this.log.verbose(`Building new checkpoint ${checkpointNumber}`, {
333
+ checkpointNumber,
334
+ initialStateReference: stateReference.toInspect(),
335
+ initialArchiveRoot: bufferToHex(archiveTree.root),
336
+ constants,
337
+ feeAssetPriceModifier,
338
+ });
339
+
340
+ const lightweightBuilder = LightweightCheckpointBuilder.startNewCheckpoint(
341
+ checkpointNumber,
342
+ constants,
343
+ previousCheckpointOutHashes,
344
+ previousInboxRollingHash,
345
+ fork,
346
+ bindings,
347
+ feeAssetPriceModifier,
348
+ );
349
+
350
+ return new CheckpointBuilder(
351
+ lightweightBuilder,
352
+ fork,
353
+ this.config,
354
+ this.contractDataSource,
355
+ this.dateProvider,
356
+ this.telemetryClient,
357
+ this.avmSimulator,
358
+ bindings,
359
+ this.debugLogStore,
360
+ );
361
+ }
362
+
363
+ /**
364
+ * Opens a checkpoint, either starting fresh or resuming from existing blocks.
365
+ * @param l1ToL2Messages - Messages the existing blocks already consumed, which seed the resumed checkpoint's
366
+ * rolling hash. Must be empty when starting fresh: a fresh checkpoint takes its messages per block, via
367
+ * `buildBlock`.
368
+ */
369
+ async openCheckpoint(
370
+ checkpointNumber: CheckpointNumber,
371
+ constants: CheckpointGlobalVariables,
372
+ feeAssetPriceModifier: bigint,
373
+ l1ToL2Messages: Fr[],
374
+ previousCheckpointOutHashes: Fr[],
375
+ previousInboxRollingHash: Fr,
376
+ fork: MerkleTreeWriteOperations,
377
+ existingBlocks: L2Block[] = [],
378
+ bindings?: LoggerBindings,
379
+ ): Promise<CheckpointBuilder> {
380
+ const stateReference = await fork.getStateReference();
381
+ const archiveTree = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
382
+
383
+ if (existingBlocks.length === 0) {
384
+ if (l1ToL2Messages.length > 0) {
385
+ throw new Error(
386
+ `Cannot open checkpoint ${checkpointNumber} with ${l1ToL2Messages.length} messages and no existing blocks: ` +
387
+ `a fresh checkpoint consumes its messages per block`,
388
+ );
389
+ }
390
+ return this.startCheckpoint(
391
+ checkpointNumber,
392
+ constants,
393
+ feeAssetPriceModifier,
394
+ previousCheckpointOutHashes,
395
+ previousInboxRollingHash,
396
+ fork,
397
+ bindings,
398
+ );
399
+ }
400
+
401
+ this.log.verbose(`Resuming checkpoint ${checkpointNumber} with ${existingBlocks.length} existing blocks`, {
402
+ checkpointNumber,
403
+ msgCount: l1ToL2Messages.length,
404
+ existingBlockCount: existingBlocks.length,
405
+ initialStateReference: stateReference.toInspect(),
406
+ initialArchiveRoot: bufferToHex(archiveTree.root),
407
+ constants,
408
+ feeAssetPriceModifier,
409
+ });
410
+
411
+ const lightweightBuilder = await LightweightCheckpointBuilder.resumeCheckpoint(
412
+ checkpointNumber,
413
+ constants,
414
+ feeAssetPriceModifier,
415
+ l1ToL2Messages,
416
+ previousCheckpointOutHashes,
417
+ previousInboxRollingHash,
418
+ fork,
419
+ existingBlocks,
420
+ bindings,
421
+ );
422
+
423
+ return new CheckpointBuilder(
424
+ lightweightBuilder,
425
+ fork,
426
+ this.config,
427
+ this.contractDataSource,
428
+ this.dateProvider,
429
+ this.telemetryClient,
430
+ this.avmSimulator,
431
+ bindings,
432
+ this.debugLogStore,
433
+ );
434
+ }
435
+
436
+ /**
437
+ * Syncs world state to the given block number and returns a fork of it at that block.
438
+ *
439
+ * Syncing first is required: the block source (archiver) can already hold a block while world state
440
+ * still trails it, and forking a not-yet-applied block throws a raw "initialize from future block"
441
+ * tree error. syncImmediate blocks until world state reaches the block, or throws a typed error if it
442
+ * genuinely cannot. When `blockHash` is provided it is verified against the synced block, triggering a
443
+ * resync on mismatch (reorg detection).
444
+ */
445
+ async getFork(blockNumber: BlockNumber, blockHash?: BlockHash): Promise<MerkleTreeWriteOperations> {
446
+ await this.worldState.syncImmediate(blockNumber, blockHash);
447
+ return this.worldState.fork(blockNumber);
448
+ }
449
+ }
package/src/config.ts ADDED
@@ -0,0 +1,130 @@
1
+ import {
2
+ type ConfigMappingsType,
3
+ booleanConfigHelper,
4
+ getConfigFromMappings,
5
+ numberConfigHelper,
6
+ optionalNumberConfigHelper,
7
+ pickConfigMappings,
8
+ secretValueConfigHelper,
9
+ } from '@aztec-labs/foundation/config';
10
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
11
+ import { type SequencerConfig, sharedSequencerConfigMappings } from '@aztec-labs/stdlib/config';
12
+ import { localSignerConfigMappings, validatorHASignerConfigMappings } from '@aztec-labs/stdlib/ha-signing';
13
+ import type { ValidatorClientConfig } from '@aztec-labs/stdlib/interfaces/server';
14
+
15
+ export type { ValidatorClientConfig };
16
+
17
+ /**
18
+ * Default clock-disparity tolerance (ms) for proposal/attestation receive windows, mirroring the p2p config
19
+ * default. Used by the validator-client validators when the merged node config does not carry the value.
20
+ */
21
+ export const DEFAULT_MAX_GOSSIP_CLOCK_DISPARITY_MS = 500;
22
+
23
+ export const validatorClientConfigMappings: ConfigMappingsType<
24
+ ValidatorClientConfig & Pick<SequencerConfig, 'blockDurationMs'>
25
+ > = {
26
+ ...pickConfigMappings(sharedSequencerConfigMappings, ['blockDurationMs']),
27
+ validatorPrivateKeys: {
28
+ env: 'VALIDATOR_PRIVATE_KEYS',
29
+ description: 'List of private keys of the validators participating in attestation duties',
30
+ ...secretValueConfigHelper<`0x${string}`[]>(val =>
31
+ val ? val.split(',').map<`0x${string}`>(key => `0x${key.replace('0x', '')}`) : [],
32
+ ),
33
+ fallback: ['VALIDATOR_PRIVATE_KEY'],
34
+ },
35
+ validatorAddresses: {
36
+ env: 'VALIDATOR_ADDRESSES',
37
+ description: 'List of addresses of the validators to use with remote signers',
38
+ parseEnv: (val: string) =>
39
+ val
40
+ .split(',')
41
+ .filter(address => address && address.trim().length > 0)
42
+ .map(address => EthAddress.fromString(address.trim())),
43
+ defaultValue: [],
44
+ },
45
+ l1ChainId: {
46
+ env: 'L1_CHAIN_ID',
47
+ description: 'The chain ID of the ethereum host.',
48
+ parseEnv: (val: string) => +val,
49
+ defaultValue: 31337,
50
+ },
51
+ disableValidator: {
52
+ env: 'VALIDATOR_DISABLED',
53
+ description: 'Do not run the validator',
54
+ ...booleanConfigHelper(false),
55
+ },
56
+ disabledValidators: {
57
+ description: 'Temporarily disable these specific validator addresses',
58
+ parseEnv: (val: string) =>
59
+ val
60
+ .split(',')
61
+ .filter(address => address && address.trim().length > 0)
62
+ .map(address => EthAddress.fromString(address.trim())),
63
+ defaultValue: [],
64
+ },
65
+ attestationPollingIntervalMs: {
66
+ env: 'VALIDATOR_ATTESTATIONS_POLLING_INTERVAL_MS',
67
+ description: 'Interval between polling for new attestations',
68
+ ...numberConfigHelper(200),
69
+ },
70
+ alwaysReexecuteBlockProposals: {
71
+ description:
72
+ 'Whether to always reexecute block proposals, even for non-validator nodes (useful for monitoring network status).',
73
+ defaultValue: true,
74
+ },
75
+ fishermanMode: {
76
+ env: 'FISHERMAN_MODE',
77
+ description:
78
+ 'Whether to run in fisherman mode: validates all proposals and attestations but does not broadcast attestations or participate in consensus.',
79
+ ...booleanConfigHelper(false),
80
+ },
81
+ skipCheckpointProposalValidation: {
82
+ description: 'Skip checkpoint proposal validation and always attest (default: false)',
83
+ defaultValue: false,
84
+ },
85
+ skipPushProposedBlocksToArchiver: {
86
+ description: 'Skip pushing re-executed blocks to archiver (default: false)',
87
+ defaultValue: false,
88
+ },
89
+ attestToEquivocatedProposals: {
90
+ description: 'Agree to attest to equivocated checkpoint proposals (for testing purposes only)',
91
+ ...booleanConfigHelper(false),
92
+ },
93
+ skipProposalSlotValidation: {
94
+ description: 'Accept proposal validation regardless of slot timing (for testing only)',
95
+ ...booleanConfigHelper(false),
96
+ },
97
+ validateMaxL2BlockGas: {
98
+ env: 'VALIDATOR_MAX_L2_BLOCK_GAS',
99
+ description: 'Maximum L2 block gas for validation. Proposals exceeding this limit are rejected.',
100
+ ...optionalNumberConfigHelper(),
101
+ },
102
+ validateMaxDABlockGas: {
103
+ env: 'VALIDATOR_MAX_DA_BLOCK_GAS',
104
+ description: 'Maximum DA block gas for validation. Proposals exceeding this limit are rejected.',
105
+ ...optionalNumberConfigHelper(),
106
+ },
107
+ validateMaxTxsPerBlock: {
108
+ env: 'VALIDATOR_MAX_TX_PER_BLOCK',
109
+ description: 'Maximum transactions per block for validation. Proposals exceeding this limit are rejected.',
110
+ ...optionalNumberConfigHelper(),
111
+ },
112
+ validateMaxTxsPerCheckpoint: {
113
+ env: 'VALIDATOR_MAX_TX_PER_CHECKPOINT',
114
+ description: 'Maximum transactions per checkpoint for validation. Proposals exceeding this limit are rejected.',
115
+ ...optionalNumberConfigHelper(),
116
+ },
117
+ ...localSignerConfigMappings,
118
+ ...validatorHASignerConfigMappings,
119
+ };
120
+
121
+ /**
122
+ * Returns the prover configuration from the environment variables.
123
+ * Note: If an environment variable is not set, the default value is used.
124
+ * @returns The validator configuration.
125
+ */
126
+ export function getProverEnvVars(): ValidatorClientConfig & Pick<SequencerConfig, 'blockDurationMs'> {
127
+ return getConfigFromMappings<ValidatorClientConfig & Pick<SequencerConfig, 'blockDurationMs'>>(
128
+ validatorClientConfigMappings,
129
+ );
130
+ }