@aztec/cli 0.0.1-commit.3469e52 → 0.0.1-commit.350e0a4d

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 (87) hide show
  1. package/dest/cmds/aztec_node/block_number.js +1 -1
  2. package/dest/cmds/aztec_node/get_logs.d.ts +30 -4
  3. package/dest/cmds/aztec_node/get_logs.d.ts.map +1 -1
  4. package/dest/cmds/aztec_node/get_logs.js +39 -29
  5. package/dest/cmds/aztec_node/get_node_info.d.ts +1 -1
  6. package/dest/cmds/aztec_node/get_node_info.d.ts.map +1 -1
  7. package/dest/cmds/aztec_node/get_node_info.js +0 -2
  8. package/dest/cmds/aztec_node/index.d.ts +1 -1
  9. package/dest/cmds/aztec_node/index.d.ts.map +1 -1
  10. package/dest/cmds/aztec_node/index.js +13 -3
  11. package/dest/cmds/infrastructure/setup_l2_contract.d.ts +1 -1
  12. package/dest/cmds/infrastructure/setup_l2_contract.d.ts.map +1 -1
  13. package/dest/cmds/infrastructure/setup_l2_contract.js +12 -7
  14. package/dest/cmds/l1/assume_proven_through.d.ts +3 -2
  15. package/dest/cmds/l1/assume_proven_through.d.ts.map +1 -1
  16. package/dest/cmds/l1/assume_proven_through.js +3 -5
  17. package/dest/cmds/l1/compute_genesis_values.d.ts +4 -0
  18. package/dest/cmds/l1/compute_genesis_values.d.ts.map +1 -0
  19. package/dest/cmds/l1/compute_genesis_values.js +17 -0
  20. package/dest/cmds/l1/deploy_l1_contracts_cmd.d.ts +1 -1
  21. package/dest/cmds/l1/deploy_l1_contracts_cmd.d.ts.map +1 -1
  22. package/dest/cmds/l1/deploy_l1_contracts_cmd.js +0 -1
  23. package/dest/cmds/l1/deploy_new_rollup.d.ts +1 -1
  24. package/dest/cmds/l1/deploy_new_rollup.d.ts.map +1 -1
  25. package/dest/cmds/l1/deploy_new_rollup.js +2 -4
  26. package/dest/cmds/l1/index.d.ts +1 -1
  27. package/dest/cmds/l1/index.d.ts.map +1 -1
  28. package/dest/cmds/l1/index.js +7 -2
  29. package/dest/cmds/l1/update_l1_validators.d.ts +1 -1
  30. package/dest/cmds/l1/update_l1_validators.d.ts.map +1 -1
  31. package/dest/cmds/l1/update_l1_validators.js +5 -6
  32. package/dest/cmds/validator_keys/eth_json_v3_worker.d.ts +2 -0
  33. package/dest/cmds/validator_keys/eth_json_v3_worker.d.ts.map +1 -0
  34. package/dest/cmds/validator_keys/eth_json_v3_worker.js +27 -0
  35. package/dest/cmds/validator_keys/index.d.ts +1 -1
  36. package/dest/cmds/validator_keys/index.d.ts.map +1 -1
  37. package/dest/cmds/validator_keys/index.js +2 -1
  38. package/dest/cmds/validator_keys/new.d.ts +6 -1
  39. package/dest/cmds/validator_keys/new.d.ts.map +1 -1
  40. package/dest/cmds/validator_keys/new.js +78 -8
  41. package/dest/cmds/validator_keys/shared.d.ts +1 -1
  42. package/dest/cmds/validator_keys/shared.d.ts.map +1 -1
  43. package/dest/cmds/validator_keys/shared.js +66 -23
  44. package/dest/config/cached_fetch.d.ts +19 -10
  45. package/dest/config/cached_fetch.d.ts.map +1 -1
  46. package/dest/config/cached_fetch.js +110 -32
  47. package/dest/config/chain_l2_config.d.ts +7 -2
  48. package/dest/config/chain_l2_config.d.ts.map +1 -1
  49. package/dest/config/chain_l2_config.js +17 -2
  50. package/dest/config/generated/networks.d.ts +93 -56
  51. package/dest/config/generated/networks.d.ts.map +1 -1
  52. package/dest/config/generated/networks.js +94 -57
  53. package/dest/config/network_config.d.ts +1 -1
  54. package/dest/config/network_config.d.ts.map +1 -1
  55. package/dest/config/network_config.js +6 -2
  56. package/dest/utils/aztec.d.ts +1 -2
  57. package/dest/utils/aztec.d.ts.map +1 -1
  58. package/dest/utils/aztec.js +2 -3
  59. package/dest/utils/commands.d.ts +14 -6
  60. package/dest/utils/commands.d.ts.map +1 -1
  61. package/dest/utils/commands.js +21 -11
  62. package/dest/utils/inspect.d.ts +1 -1
  63. package/dest/utils/inspect.d.ts.map +1 -1
  64. package/dest/utils/inspect.js +15 -12
  65. package/package.json +30 -30
  66. package/src/cmds/aztec_node/block_number.ts +1 -1
  67. package/src/cmds/aztec_node/get_logs.ts +70 -38
  68. package/src/cmds/aztec_node/get_node_info.ts +0 -2
  69. package/src/cmds/aztec_node/index.ts +13 -8
  70. package/src/cmds/infrastructure/setup_l2_contract.ts +12 -7
  71. package/src/cmds/l1/assume_proven_through.ts +4 -7
  72. package/src/cmds/l1/compute_genesis_values.ts +29 -0
  73. package/src/cmds/l1/deploy_l1_contracts_cmd.ts +0 -1
  74. package/src/cmds/l1/deploy_new_rollup.ts +1 -3
  75. package/src/cmds/l1/index.ts +23 -4
  76. package/src/cmds/l1/update_l1_validators.ts +5 -6
  77. package/src/cmds/validator_keys/eth_json_v3_worker.ts +30 -0
  78. package/src/cmds/validator_keys/index.ts +18 -4
  79. package/src/cmds/validator_keys/new.ts +107 -8
  80. package/src/cmds/validator_keys/shared.ts +86 -34
  81. package/src/config/cached_fetch.ts +119 -31
  82. package/src/config/chain_l2_config.ts +17 -2
  83. package/src/config/generated/networks.ts +92 -55
  84. package/src/config/network_config.ts +6 -2
  85. package/src/utils/aztec.ts +12 -18
  86. package/src/utils/commands.ts +24 -11
  87. package/src/utils/inspect.ts +11 -9
@@ -1,4 +1,5 @@
1
1
  import { prettyPrintJSON } from '@aztec/cli/utils';
2
+ import { asyncPool } from '@aztec/foundation/async-pool';
2
3
  import { deriveBlsPrivateKey } from '@aztec/foundation/crypto/bls';
3
4
  import { createBn254Keystore } from '@aztec/foundation/crypto/bls/bn254_keystore';
4
5
  import { computeBn254G1PublicKeyCompressed } from '@aztec/foundation/crypto/bn254';
@@ -10,12 +11,60 @@ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
10
11
  import { Wallet } from '@ethersproject/wallet';
11
12
  import { constants as fsConstants, mkdirSync } from 'fs';
12
13
  import { access, writeFile } from 'fs/promises';
13
- import { homedir } from 'os';
14
+ import { availableParallelism, homedir } from 'os';
14
15
  import { dirname, isAbsolute, join } from 'path';
15
16
  import { mnemonicToAccount } from 'viem/accounts';
17
+ import { Worker } from 'worker_threads';
16
18
 
17
19
  import { defaultBlsPath } from './utils.js';
18
20
 
21
+ type EthJsonV3WorkerResult = { json: string } | { error: { message: string; name?: string; stack?: string } };
22
+
23
+ // ethers' default scrypt parameters use substantial memory, so keep worker fan-out bounded.
24
+ const maxEthKeystoreWorkers = Math.max(1, Math.min(4, availableParallelism()));
25
+
26
+ function deserializeWorkerError(error: { message: string; name?: string; stack?: string }) {
27
+ const result = new Error(error.message);
28
+ result.name = error.name ?? result.name;
29
+ result.stack = error.stack;
30
+ return result;
31
+ }
32
+
33
+ function encryptEthJsonV3InWorker(privateKeyHex: string, password: string): Promise<string> {
34
+ return new Promise<string>((resolve, reject) => {
35
+ const worker = new Worker(new URL('./eth_json_v3_worker.js', import.meta.url), {
36
+ workerData: { privateKeyHex, password },
37
+ });
38
+ let settled = false;
39
+
40
+ worker.once('message', (result: EthJsonV3WorkerResult) => {
41
+ settled = true;
42
+
43
+ if ('json' in result) {
44
+ resolve(result.json);
45
+ } else {
46
+ reject(deserializeWorkerError(result.error));
47
+ }
48
+ });
49
+ worker.once('error', error => {
50
+ settled = true;
51
+ reject(error);
52
+ });
53
+ worker.once('exit', code => {
54
+ if (!settled) {
55
+ reject(new Error(`ETH JSON V3 worker stopped with exit code ${code}`));
56
+ }
57
+ });
58
+ });
59
+ }
60
+
61
+ async function encryptEthJsonV3(privateKeyHex: string, password: string): Promise<string> {
62
+ if (process.env.JEST_WORKER_ID !== undefined) {
63
+ return await new Wallet(privateKeyHex).encrypt(password);
64
+ }
65
+ return await encryptEthJsonV3InWorker(privateKeyHex, password);
66
+ }
67
+
19
68
  export type ValidatorSummary = { attesterEth?: string; attesterBls?: string; publisherEth?: string[] };
20
69
 
21
70
  export type BuildValidatorsInput = {
@@ -228,7 +277,7 @@ export async function writeBn254BlsKeystore(
228
277
  ): Promise<string> {
229
278
  mkdirSync(outDir, { recursive: true });
230
279
 
231
- const keystore = createBn254Keystore(password, privateKeyHex, pubkeyHex, derivationPath);
280
+ const keystore = await createBn254Keystore(password, privateKeyHex, pubkeyHex, derivationPath);
232
281
 
233
282
  const safeBase = fileNameBase.replace(/[^a-zA-Z0-9_-]/g, '_');
234
283
  const outPath = join(outDir, `keystore-${safeBase}.json`);
@@ -241,28 +290,29 @@ export async function writeBlsBn254ToFile(
241
290
  validators: ValidatorKeyStore[],
242
291
  options: { outDir: string; password: string; blsPath?: string },
243
292
  ): Promise<void> {
244
- for (let i = 0; i < validators.length; i++) {
245
- const v = validators[i];
246
- if (!v || typeof v !== 'object' || !('attester' in v)) {
247
- continue;
248
- }
249
- const att = (v as any).attester;
293
+ await Promise.all(
294
+ validators.map(async (v, i) => {
295
+ if (!v || typeof v !== 'object' || !('attester' in v)) {
296
+ return;
297
+ }
298
+ const att = (v as any).attester;
250
299
 
251
- // Shapes: { bls: <hex> } or { eth: <ethAccount>, bls?: <hex> } or plain EthAccount
252
- const blsKey: string | undefined = typeof att === 'object' && 'bls' in att ? (att as any).bls : undefined;
253
- if (!blsKey || typeof blsKey !== 'string') {
254
- continue;
255
- }
300
+ // Shapes: { bls: <hex> } or { eth: <ethAccount>, bls?: <hex> } or plain EthAccount
301
+ const blsKey: string | undefined = typeof att === 'object' && 'bls' in att ? (att as any).bls : undefined;
302
+ if (!blsKey || typeof blsKey !== 'string') {
303
+ return;
304
+ }
256
305
 
257
- const pub = await computeBlsPublicKeyCompressed(blsKey);
258
- const path = options.blsPath ?? defaultBlsPath;
259
- const fileBase = `${String(i + 1)}_${pub.slice(2, 18)}`;
260
- const keystorePath = await writeBn254BlsKeystore(options.outDir, fileBase, options.password, blsKey, pub, path);
306
+ const pub = await computeBlsPublicKeyCompressed(blsKey);
307
+ const path = options.blsPath ?? defaultBlsPath;
308
+ const fileBase = `${String(i + 1)}_${pub.slice(2, 18)}`;
309
+ const keystorePath = await writeBn254BlsKeystore(options.outDir, fileBase, options.password, blsKey, pub, path);
261
310
 
262
- if (typeof att === 'object') {
263
- (att as any).bls = { path: keystorePath, password: options.password };
264
- }
265
- }
311
+ if (typeof att === 'object') {
312
+ (att as any).bls = { path: keystorePath, password: options.password };
313
+ }
314
+ }),
315
+ );
266
316
  }
267
317
 
268
318
  /** Writes an Ethereum JSON V3 keystore using ethers, returns absolute path */
@@ -274,8 +324,7 @@ export async function writeEthJsonV3Keystore(
274
324
  ): Promise<string> {
275
325
  const safeBase = fileNameBase.replace(/[^a-zA-Z0-9_-]/g, '_');
276
326
  mkdirSync(outDir, { recursive: true });
277
- const wallet = new Wallet(privateKeyHex);
278
- const json = await wallet.encrypt(password);
327
+ const json = await encryptEthJsonV3(privateKeyHex, password);
279
328
  const outPath = join(outDir, `keystore-eth-${safeBase}.json`);
280
329
  await writeFile(outPath, json, { encoding: 'utf-8' });
281
330
  return outPath;
@@ -286,13 +335,16 @@ export async function writeEthJsonV3ToFile(
286
335
  validators: ValidatorKeyStore[],
287
336
  options: { outDir: string; password: string },
288
337
  ): Promise<void> {
289
- const maybeEncryptEth = async (account: any, label: string) => {
338
+ const tasks: (() => Promise<void>)[] = [];
339
+
340
+ const maybeQueueEncryptEth = (account: any, label: string, setEncryptedAccount: (account: any) => void) => {
290
341
  if (typeof account === 'string' && account.startsWith('0x') && account.length === 66) {
291
- const fileBase = `${label}_${account.slice(2, 10)}`;
292
- const p = await writeEthJsonV3Keystore(options.outDir, fileBase, options.password, account);
293
- return { path: p, password: options.password };
342
+ tasks.push(async () => {
343
+ const fileBase = `${label}_${account.slice(2, 10)}`;
344
+ const path = await writeEthJsonV3Keystore(options.outDir, fileBase, options.password, account);
345
+ setEncryptedAccount({ path, password: options.password });
346
+ });
294
347
  }
295
- return account;
296
348
  };
297
349
 
298
350
  for (let i = 0; i < validators.length; i++) {
@@ -304,23 +356,23 @@ export async function writeEthJsonV3ToFile(
304
356
  // attester may be string (eth), object with eth, or remote signer
305
357
  const att = (v as any).attester;
306
358
  if (typeof att === 'string') {
307
- (v as any).attester = await maybeEncryptEth(att, `attester_${i + 1}`);
359
+ maybeQueueEncryptEth(att, `attester_${i + 1}`, account => ((v as any).attester = account));
308
360
  } else if (att && typeof att === 'object' && 'eth' in att) {
309
- (att as any).eth = await maybeEncryptEth((att as any).eth, `attester_${i + 1}`);
361
+ maybeQueueEncryptEth((att as any).eth, `attester_${i + 1}`, account => ((att as any).eth = account));
310
362
  }
311
363
 
312
364
  // publisher can be single or array
313
365
  if ('publisher' in v) {
314
366
  const pub = (v as any).publisher;
315
367
  if (Array.isArray(pub)) {
316
- const out: any[] = [];
317
368
  for (let j = 0; j < pub.length; j++) {
318
- out.push(await maybeEncryptEth(pub[j], `publisher_${i + 1}_${j + 1}`));
369
+ maybeQueueEncryptEth(pub[j], `publisher_${i + 1}_${j + 1}`, account => (pub[j] = account));
319
370
  }
320
- (v as any).publisher = out;
321
371
  } else if (pub !== undefined) {
322
- (v as any).publisher = await maybeEncryptEth(pub, `publisher_${i + 1}`);
372
+ maybeQueueEncryptEth(pub, `publisher_${i + 1}`, account => ((v as any).publisher = account));
323
373
  }
324
374
  }
325
375
  }
376
+
377
+ await asyncPool(maxEthKeystoreWorkers, tasks, task => task());
326
378
  }
@@ -1,24 +1,48 @@
1
1
  import { createLogger } from '@aztec/aztec.js/log';
2
2
 
3
- import { mkdir, readFile, stat, writeFile } from 'fs/promises';
3
+ import { mkdir, readFile, writeFile } from 'fs/promises';
4
4
  import { dirname } from 'path';
5
5
 
6
6
  export interface CachedFetchOptions {
7
- /** Cache duration in milliseconds */
8
- cacheDurationMs: number;
9
- /** The cache file */
7
+ /** The cache file path for storing data. If not provided, no caching is performed. */
10
8
  cacheFile?: string;
9
+ /** Fallback max-age in milliseconds when server sends no Cache-Control header. Defaults to 5 minutes. */
10
+ defaultMaxAgeMs?: number;
11
+ }
12
+
13
+ /** Cache metadata stored in a sidecar .meta file alongside the data file. */
14
+ interface CacheMeta {
15
+ etag?: string;
16
+ expiresAt: number;
17
+ }
18
+
19
+ const DEFAULT_MAX_AGE_MS = 5 * 60 * 1000; // 5 minutes
20
+
21
+ /** Extracts max-age value in milliseconds from a Response's Cache-Control header. Returns undefined if not present. */
22
+ export function parseMaxAge(response: { headers: { get(name: string): string | null } }): number | undefined {
23
+ const cacheControl = response.headers.get('cache-control');
24
+ if (!cacheControl) {
25
+ return undefined;
26
+ }
27
+ const match = cacheControl.match(/max-age=(\d+)/);
28
+ if (!match) {
29
+ return undefined;
30
+ }
31
+ return parseInt(match[1], 10) * 1000;
11
32
  }
12
33
 
13
34
  /**
14
- * Fetches data from a URL with file-based caching support.
15
- * This utility can be used by both remote config and bootnodes fetching.
35
+ * Fetches data from a URL with file-based HTTP conditional caching.
36
+ *
37
+ * Data is stored as raw JSON in the cache file (same format as the server returns).
38
+ * Caching metadata (ETag, expiry) is stored in a separate sidecar `.meta` file.
39
+ * This keeps the data file human-readable and backward-compatible with older code.
16
40
  *
17
41
  * @param url - The URL to fetch from
18
- * @param networkName - Network name for cache directory structure
19
- * @param options - Caching and error handling options
20
- * @param cacheDir - Optional cache directory (defaults to no caching)
21
- * @returns The fetched and parsed JSON data, or undefined if fetch fails and throwOnError is false
42
+ * @param options - Caching options
43
+ * @param fetch - Fetch implementation (defaults to globalThis.fetch)
44
+ * @param log - Logger instance
45
+ * @returns The fetched and parsed JSON data, or undefined if fetch fails
22
46
  */
23
47
  export async function cachedFetch<T = any>(
24
48
  url: string,
@@ -26,42 +50,106 @@ export async function cachedFetch<T = any>(
26
50
  fetch = globalThis.fetch,
27
51
  log = createLogger('cached_fetch'),
28
52
  ): Promise<T | undefined> {
29
- const { cacheDurationMs, cacheFile } = options;
53
+ const { cacheFile, defaultMaxAgeMs = DEFAULT_MAX_AGE_MS } = options;
54
+
55
+ // If no cacheFile, just fetch normally without caching
56
+ if (!cacheFile) {
57
+ return fetchAndParse<T>(url, fetch, log);
58
+ }
59
+
60
+ const metaFile = cacheFile + '.meta';
30
61
 
31
- // Try to read from cache first
62
+ // Try to read metadata
63
+ let meta: CacheMeta | undefined;
32
64
  try {
33
- if (cacheFile) {
34
- const info = await stat(cacheFile);
35
- if (info.mtimeMs + cacheDurationMs > Date.now()) {
36
- const cachedData = JSON.parse(await readFile(cacheFile, 'utf-8'));
37
- return cachedData;
38
- }
39
- }
65
+ meta = JSON.parse(await readFile(metaFile, 'utf-8'));
40
66
  } catch {
41
- log.trace('Failed to read data from cache');
67
+ log.trace('No usable cache metadata found');
42
68
  }
43
69
 
70
+ // Try to read cached data
71
+ let cachedData: T | undefined;
44
72
  try {
45
- const response = await fetch(url);
73
+ cachedData = JSON.parse(await readFile(cacheFile, 'utf-8'));
74
+ } catch {
75
+ log.trace('No usable cached data found');
76
+ }
77
+
78
+ // If metadata and data exist and cache is fresh, return directly
79
+ if (meta && cachedData !== undefined && meta.expiresAt > Date.now()) {
80
+ return cachedData;
81
+ }
82
+
83
+ // Cache is stale or missing — make a (possibly conditional) request
84
+ try {
85
+ const headers: Record<string, string> = {};
86
+ if (meta?.etag && cachedData !== undefined) {
87
+ headers['If-None-Match'] = meta.etag;
88
+ }
89
+
90
+ const response = await fetch(url, { headers });
91
+
92
+ if (response.status === 304 && cachedData !== undefined) {
93
+ // Not modified — recompute expiry from new response headers and return cached data
94
+ const maxAgeMs = parseMaxAge(response) ?? defaultMaxAgeMs;
95
+ await writeMetaFile(metaFile, { etag: meta?.etag, expiresAt: Date.now() + maxAgeMs }, log);
96
+ return cachedData;
97
+ }
98
+
46
99
  if (!response.ok) {
47
100
  log.warn(`Failed to fetch from ${url}: ${response.status} ${response.statusText}`);
48
- return undefined;
101
+ return cachedData;
49
102
  }
50
103
 
51
- const data = await response.json();
104
+ // 200 — parse new data and cache it
105
+ const data = (await response.json()) as T;
106
+ const maxAgeMs = parseMaxAge(response) ?? defaultMaxAgeMs;
107
+ const etag = response.headers.get('etag') ?? undefined;
52
108
 
53
- try {
54
- if (cacheFile) {
55
- await mkdir(dirname(cacheFile), { recursive: true });
56
- await writeFile(cacheFile, JSON.stringify(data), 'utf-8');
57
- }
58
- } catch (err) {
59
- log.warn('Failed to cache data on disk: ' + cacheFile, { cacheFile, err });
60
- }
109
+ await ensureDir(cacheFile, log);
110
+ await Promise.all([
111
+ writeFile(cacheFile, JSON.stringify(data), 'utf-8'),
112
+ writeFile(metaFile, JSON.stringify({ etag, expiresAt: Date.now() + maxAgeMs }), 'utf-8'),
113
+ ]);
61
114
 
62
115
  return data;
116
+ } catch (err) {
117
+ log.warn(`Failed to fetch from ${url}`, { err });
118
+ return cachedData;
119
+ }
120
+ }
121
+
122
+ async function fetchAndParse<T>(
123
+ url: string,
124
+ fetch: typeof globalThis.fetch,
125
+ log: ReturnType<typeof createLogger>,
126
+ ): Promise<T | undefined> {
127
+ try {
128
+ const response = await fetch(url);
129
+ if (!response.ok) {
130
+ log.warn(`Failed to fetch from ${url}: ${response.status} ${response.statusText}`);
131
+ return undefined;
132
+ }
133
+ return (await response.json()) as T;
63
134
  } catch (err) {
64
135
  log.warn(`Failed to fetch from ${url}`, { err });
65
136
  return undefined;
66
137
  }
67
138
  }
139
+
140
+ async function ensureDir(filePath: string, log: ReturnType<typeof createLogger>) {
141
+ try {
142
+ await mkdir(dirname(filePath), { recursive: true });
143
+ } catch (err) {
144
+ log.warn('Failed to create cache directory for: ' + filePath, { err });
145
+ }
146
+ }
147
+
148
+ async function writeMetaFile(metaFile: string, meta: CacheMeta, log: ReturnType<typeof createLogger>) {
149
+ try {
150
+ await mkdir(dirname(metaFile), { recursive: true });
151
+ await writeFile(metaFile, JSON.stringify(meta), 'utf-8');
152
+ } catch (err) {
153
+ log.warn('Failed to write cache metadata: ' + metaFile, { err });
154
+ }
155
+ }
@@ -1,4 +1,6 @@
1
1
  import type { NetworkNames } from '@aztec/foundation/config';
2
+ import { createLogger } from '@aztec/foundation/log';
3
+ import { type ConsensusEnvVar, checkConsensusEnvOverrides } from '@aztec/stdlib/config';
2
4
 
3
5
  import path from 'path';
4
6
 
@@ -12,6 +14,12 @@ const NetworkConfigs: Partial<Record<NetworkNames, NetworkConfigEnv>> = {
12
14
  mainnet: mainnetConfig,
13
15
  };
14
16
 
17
+ /** Every generated network config must define every consensus-critical env var. */
18
+ export type ConsensusComplete = Record<ConsensusEnvVar, string | number | boolean>;
19
+ ({ devnetConfig, testnetConfig, mainnetConfig }) satisfies Record<string, ConsensusComplete>;
20
+
21
+ const log = createLogger('cli:chain_l2_config');
22
+
15
23
  function enrichEnvironmentWithNetworkConfig(config: NetworkConfigEnv): void {
16
24
  for (const [key, value] of Object.entries(config)) {
17
25
  if (process.env[key] === undefined && value !== undefined) {
@@ -31,7 +39,9 @@ function getDefaultDataDir(networkName: NetworkNames): string {
31
39
  * and DefaultSlasherConfig (which match the 'defaults' section of defaults.yml).
32
40
  *
33
41
  * For deployed networks: applies network configuration from generated defaults.yml,
34
- * merging base defaults with network-specific overrides.
42
+ * merging base defaults with network-specific overrides. Before merging, enforces that operators have not
43
+ * overridden any consensus-critical env var with a value diverging from the network config (throwing unless
44
+ * ALLOW_OVERRIDING_NETWORK_CONFIG is set), so all nodes of a network agree on consensus-critical values.
35
45
  *
36
46
  * @param networkName - The network name
37
47
  */
@@ -45,8 +55,13 @@ export function enrichEnvironmentWithChainName(networkName: NetworkNames) {
45
55
  }
46
56
 
47
57
  // Apply generated network config from defaults.yml
48
- const generatedConfig = NetworkConfigs[networkName];
58
+ // For devnet iterations (v4-devnet-1, etc.), use the base devnet config
59
+ const configKey = /^v\d+-devnet-\d+$/.test(networkName) ? 'devnet' : networkName;
60
+ const generatedConfig = NetworkConfigs[configKey];
49
61
  if (generatedConfig) {
62
+ // The check is pure; this layer owns env mutation, so apply its canonical writes before enriching.
63
+ const canonical = checkConsensusEnvOverrides(generatedConfig, process.env, msg => log.warn(msg));
64
+ Object.assign(process.env, canonical);
50
65
  enrichEnvironmentWithNetworkConfig(generatedConfig);
51
66
  }
52
67