@aztec/cli 3.0.0-devnet.2 → 3.0.0-devnet.20251212

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 (149) hide show
  1. package/README.md +1 -1
  2. package/dest/cmds/aztec_node/block_number.d.ts +1 -1
  3. package/dest/cmds/aztec_node/get_block.d.ts +1 -1
  4. package/dest/cmds/aztec_node/get_block.d.ts.map +1 -1
  5. package/dest/cmds/aztec_node/get_block.js +2 -1
  6. package/dest/cmds/aztec_node/get_current_base_fee.d.ts +1 -1
  7. package/dest/cmds/aztec_node/get_l1_to_l2_message_witness.d.ts +1 -1
  8. package/dest/cmds/aztec_node/get_logs.d.ts +3 -2
  9. package/dest/cmds/aztec_node/get_logs.d.ts.map +1 -1
  10. package/dest/cmds/aztec_node/get_node_info.d.ts +1 -1
  11. package/dest/cmds/aztec_node/index.d.ts +1 -1
  12. package/dest/cmds/contracts/index.d.ts +1 -1
  13. package/dest/cmds/contracts/inspect_contract.d.ts +1 -1
  14. package/dest/cmds/contracts/inspect_contract.d.ts.map +1 -1
  15. package/dest/cmds/contracts/inspect_contract.js +4 -10
  16. package/dest/cmds/contracts/parse_parameter_struct.d.ts +1 -1
  17. package/dest/cmds/infrastructure/index.d.ts +1 -1
  18. package/dest/cmds/infrastructure/index.d.ts.map +1 -1
  19. package/dest/cmds/infrastructure/index.js +0 -1
  20. package/dest/cmds/infrastructure/sequencers.d.ts +1 -2
  21. package/dest/cmds/infrastructure/sequencers.d.ts.map +1 -1
  22. package/dest/cmds/infrastructure/sequencers.js +3 -1
  23. package/dest/cmds/infrastructure/setup_l2_contract.d.ts +1 -1
  24. package/dest/cmds/l1/advance_epoch.d.ts +1 -1
  25. package/dest/cmds/l1/assume_proven_through.d.ts +1 -1
  26. package/dest/cmds/l1/assume_proven_through.d.ts.map +1 -1
  27. package/dest/cmds/l1/assume_proven_through.js +2 -1
  28. package/dest/cmds/l1/bridge_erc20.d.ts +1 -1
  29. package/dest/cmds/l1/bridge_erc20.d.ts.map +1 -1
  30. package/dest/cmds/l1/bridge_erc20.js +2 -1
  31. package/dest/cmds/l1/create_l1_account.d.ts +1 -1
  32. package/dest/cmds/l1/deploy_l1_contracts.d.ts +1 -1
  33. package/dest/cmds/l1/deploy_l1_contracts.js +1 -1
  34. package/dest/cmds/l1/deploy_new_rollup.d.ts +2 -2
  35. package/dest/cmds/l1/deploy_new_rollup.d.ts.map +1 -1
  36. package/dest/cmds/l1/deploy_new_rollup.js +1 -1
  37. package/dest/cmds/l1/get_l1_addresses.d.ts +1 -1
  38. package/dest/cmds/l1/get_l1_addresses.d.ts.map +1 -1
  39. package/dest/cmds/l1/get_l1_addresses.js +2 -1
  40. package/dest/cmds/l1/get_l1_balance.d.ts +1 -1
  41. package/dest/cmds/l1/get_l1_balance.js +1 -1
  42. package/dest/cmds/l1/governance_utils.d.ts +5 -5
  43. package/dest/cmds/l1/governance_utils.d.ts.map +1 -1
  44. package/dest/cmds/l1/governance_utils.js +3 -1
  45. package/dest/cmds/l1/index.d.ts +1 -1
  46. package/dest/cmds/l1/prover_stats.d.ts +1 -1
  47. package/dest/cmds/l1/prover_stats.d.ts.map +1 -1
  48. package/dest/cmds/l1/prover_stats.js +29 -29
  49. package/dest/cmds/l1/trigger_seed_snapshot.d.ts +2 -2
  50. package/dest/cmds/l1/trigger_seed_snapshot.d.ts.map +1 -1
  51. package/dest/cmds/l1/trigger_seed_snapshot.js +2 -1
  52. package/dest/cmds/l1/update_l1_validators.d.ts +6 -6
  53. package/dest/cmds/l1/update_l1_validators.d.ts.map +1 -1
  54. package/dest/cmds/l1/update_l1_validators.js +7 -3
  55. package/dest/cmds/misc/compute_selector.d.ts +1 -1
  56. package/dest/cmds/misc/example_contracts.d.ts +1 -1
  57. package/dest/cmds/misc/generate_bootnode_enr.d.ts +1 -1
  58. package/dest/cmds/misc/generate_p2p_private_key.d.ts +1 -1
  59. package/dest/cmds/misc/generate_secret_and_hash.d.ts +1 -1
  60. package/dest/cmds/misc/generate_secret_and_hash.js +1 -1
  61. package/dest/cmds/misc/generate_secret_key.d.ts +1 -1
  62. package/dest/cmds/misc/get_canonical_sponsored_fpc_address.d.ts +1 -1
  63. package/dest/cmds/misc/index.d.ts +1 -1
  64. package/dest/cmds/misc/update/common.d.ts +1 -1
  65. package/dest/cmds/misc/update/github.d.ts +1 -1
  66. package/dest/cmds/misc/update/noir.d.ts +1 -1
  67. package/dest/cmds/misc/update/npm.d.ts +1 -1
  68. package/dest/cmds/misc/update/npm.js +1 -1
  69. package/dest/cmds/misc/update/utils.d.ts +1 -1
  70. package/dest/cmds/misc/update.d.ts +1 -1
  71. package/dest/cmds/validator_keys/add.d.ts +5 -0
  72. package/dest/cmds/validator_keys/add.d.ts.map +1 -0
  73. package/dest/cmds/validator_keys/add.js +83 -0
  74. package/dest/cmds/validator_keys/generate_bls_keypair.d.ts +12 -0
  75. package/dest/cmds/validator_keys/generate_bls_keypair.d.ts.map +1 -0
  76. package/dest/cmds/validator_keys/generate_bls_keypair.js +27 -0
  77. package/dest/cmds/validator_keys/index.d.ts +4 -0
  78. package/dest/cmds/validator_keys/index.d.ts.map +1 -0
  79. package/dest/cmds/validator_keys/index.js +32 -0
  80. package/dest/cmds/validator_keys/new.d.ts +29 -0
  81. package/dest/cmds/validator_keys/new.d.ts.map +1 -0
  82. package/dest/cmds/validator_keys/new.js +132 -0
  83. package/dest/cmds/validator_keys/shared.d.ts +68 -0
  84. package/dest/cmds/validator_keys/shared.d.ts.map +1 -0
  85. package/dest/cmds/validator_keys/shared.js +274 -0
  86. package/dest/cmds/validator_keys/staker.d.ts +38 -0
  87. package/dest/cmds/validator_keys/staker.d.ts.map +1 -0
  88. package/dest/cmds/validator_keys/staker.js +208 -0
  89. package/dest/cmds/validator_keys/utils.d.ts +25 -0
  90. package/dest/cmds/validator_keys/utils.d.ts.map +1 -0
  91. package/dest/cmds/validator_keys/utils.js +52 -0
  92. package/dest/config/cached_fetch.d.ts +1 -1
  93. package/dest/config/chain_l2_config.d.ts +14 -10
  94. package/dest/config/chain_l2_config.d.ts.map +1 -1
  95. package/dest/config/chain_l2_config.js +128 -67
  96. package/dest/config/enrich_env.d.ts +1 -1
  97. package/dest/config/get_l1_config.d.ts +3 -2
  98. package/dest/config/get_l1_config.d.ts.map +1 -1
  99. package/dest/config/get_l1_config.js +3 -1
  100. package/dest/config/index.d.ts +1 -1
  101. package/dest/config/network_config.d.ts +6 -3
  102. package/dest/config/network_config.d.ts.map +1 -1
  103. package/dest/config/network_config.js +58 -28
  104. package/dest/utils/aztec.d.ts +5 -3
  105. package/dest/utils/aztec.d.ts.map +1 -1
  106. package/dest/utils/aztec.js +6 -3
  107. package/dest/utils/commands.d.ts +12 -3
  108. package/dest/utils/commands.d.ts.map +1 -1
  109. package/dest/utils/commands.js +30 -3
  110. package/dest/utils/encoding.d.ts +1 -1
  111. package/dest/utils/encoding.js +1 -1
  112. package/dest/utils/github.d.ts +1 -1
  113. package/dest/utils/index.d.ts +1 -1
  114. package/dest/utils/inspect.d.ts +3 -2
  115. package/dest/utils/inspect.d.ts.map +1 -1
  116. package/dest/utils/setup_contracts.d.ts +1 -1
  117. package/package.json +37 -28
  118. package/public_include_metric_prefixes.json +1 -0
  119. package/src/cmds/aztec_node/get_block.ts +2 -1
  120. package/src/cmds/aztec_node/get_logs.ts +3 -2
  121. package/src/cmds/contracts/inspect_contract.ts +4 -11
  122. package/src/cmds/infrastructure/index.ts +0 -1
  123. package/src/cmds/infrastructure/sequencers.ts +3 -2
  124. package/src/cmds/l1/assume_proven_through.ts +4 -1
  125. package/src/cmds/l1/bridge_erc20.ts +2 -1
  126. package/src/cmds/l1/deploy_l1_contracts.ts +1 -1
  127. package/src/cmds/l1/deploy_new_rollup.ts +2 -1
  128. package/src/cmds/l1/get_l1_addresses.ts +3 -1
  129. package/src/cmds/l1/get_l1_balance.ts +1 -1
  130. package/src/cmds/l1/governance_utils.ts +3 -8
  131. package/src/cmds/l1/prover_stats.ts +38 -30
  132. package/src/cmds/l1/trigger_seed_snapshot.ts +2 -1
  133. package/src/cmds/l1/update_l1_validators.ts +7 -12
  134. package/src/cmds/misc/generate_secret_and_hash.ts +1 -1
  135. package/src/cmds/misc/update/npm.ts +1 -1
  136. package/src/cmds/validator_keys/add.ts +123 -0
  137. package/src/cmds/validator_keys/generate_bls_keypair.ts +34 -0
  138. package/src/cmds/validator_keys/index.ts +142 -0
  139. package/src/cmds/validator_keys/new.ts +207 -0
  140. package/src/cmds/validator_keys/shared.ts +326 -0
  141. package/src/cmds/validator_keys/staker.ts +301 -0
  142. package/src/cmds/validator_keys/utils.ts +80 -0
  143. package/src/config/chain_l2_config.ts +176 -92
  144. package/src/config/get_l1_config.ts +4 -1
  145. package/src/config/network_config.ts +67 -29
  146. package/src/utils/aztec.ts +9 -9
  147. package/src/utils/commands.ts +41 -3
  148. package/src/utils/encoding.ts +1 -1
  149. package/src/utils/inspect.ts +2 -1
@@ -0,0 +1,207 @@
1
+ import { prettyPrintJSON } from '@aztec/cli/utils';
2
+ import { createEthereumChain } from '@aztec/ethereum/chain';
3
+ import { GSEContract } from '@aztec/ethereum/contracts';
4
+ import type { EthAddress } from '@aztec/foundation/eth-address';
5
+ import type { LogFn } from '@aztec/foundation/log';
6
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
7
+
8
+ import { wordlist } from '@scure/bip39/wordlists/english.js';
9
+ import { writeFile } from 'fs/promises';
10
+ import { basename, dirname, join } from 'path';
11
+ import { createPublicClient, fallback, http } from 'viem';
12
+ import { generateMnemonic, mnemonicToAccount } from 'viem/accounts';
13
+
14
+ import {
15
+ buildValidatorEntries,
16
+ logValidatorSummaries,
17
+ maybePrintJson,
18
+ resolveKeystoreOutputPath,
19
+ writeBlsBn254ToFile,
20
+ writeEthJsonV3ToFile,
21
+ writeKeystoreFile,
22
+ } from './shared.js';
23
+ import { processAttesterAccounts } from './staker.js';
24
+ import {
25
+ validateBlsPathOptions,
26
+ validatePublisherOptions,
27
+ validateRemoteSignerOptions,
28
+ validateStakerOutputOptions,
29
+ } from './utils.js';
30
+
31
+ export type NewValidatorKeystoreOptions = {
32
+ dataDir?: string;
33
+ file?: string;
34
+ count?: number;
35
+ publisherCount?: number;
36
+ publishers?: string[];
37
+ mnemonic?: string;
38
+ passphrase?: string;
39
+ accountIndex?: number;
40
+ addressIndex?: number;
41
+ separatePublisher?: boolean;
42
+ ikm?: string;
43
+ blsPath?: string;
44
+ password?: string;
45
+ encryptedKeystoreDir?: string;
46
+ json?: boolean;
47
+ feeRecipient: AztecAddress;
48
+ coinbase?: EthAddress;
49
+ remoteSigner?: string;
50
+ stakerOutput?: boolean;
51
+ gseAddress?: EthAddress;
52
+ l1RpcUrls?: string[];
53
+ l1ChainId?: number;
54
+ };
55
+
56
+ export async function newValidatorKeystore(options: NewValidatorKeystoreOptions, log: LogFn) {
57
+ // validate bls-path inputs before proceeding with key generation
58
+ validateBlsPathOptions(options);
59
+ // validate staker output options before proceeding with key generation
60
+ validateStakerOutputOptions(options);
61
+ // validate publisher options
62
+ validatePublisherOptions(options);
63
+ // validate remote signer options
64
+ validateRemoteSignerOptions(options);
65
+
66
+ const {
67
+ dataDir,
68
+ file,
69
+ count,
70
+ publisherCount = 0,
71
+ publishers,
72
+ json,
73
+ coinbase,
74
+ accountIndex = 0,
75
+ addressIndex = 0,
76
+ feeRecipient,
77
+ remoteSigner,
78
+ blsPath,
79
+ ikm,
80
+ mnemonic: _mnemonic,
81
+ password,
82
+ encryptedKeystoreDir,
83
+ stakerOutput,
84
+ gseAddress,
85
+ l1RpcUrls,
86
+ l1ChainId,
87
+ } = options;
88
+
89
+ const mnemonic = _mnemonic ?? generateMnemonic(wordlist);
90
+
91
+ if (!_mnemonic && !json) {
92
+ log('No mnemonic provided, generating new one...');
93
+ log(`Using new mnemonic:`);
94
+ log('');
95
+ log(mnemonic);
96
+ log('');
97
+ }
98
+
99
+ const validatorCount = typeof count === 'number' && Number.isFinite(count) && count > 0 ? Math.floor(count) : 1;
100
+ const { outputPath } = await resolveKeystoreOutputPath(dataDir, file);
101
+ const keystoreOutDir = dirname(outputPath);
102
+
103
+ const { validators, summaries } = await buildValidatorEntries({
104
+ validatorCount,
105
+ publisherCount,
106
+ publishers,
107
+ accountIndex,
108
+ baseAddressIndex: addressIndex,
109
+ mnemonic,
110
+ ikm,
111
+ blsPath,
112
+ feeRecipient,
113
+ coinbase,
114
+ remoteSigner,
115
+ });
116
+
117
+ // If password provided, write ETH JSON V3 and BLS BN254 keystores and replace plaintext
118
+ if (password !== undefined) {
119
+ const encryptedKeystoreOutDir =
120
+ encryptedKeystoreDir && encryptedKeystoreDir.length > 0 ? encryptedKeystoreDir : keystoreOutDir;
121
+ await writeEthJsonV3ToFile(validators, { outDir: encryptedKeystoreOutDir, password });
122
+ await writeBlsBn254ToFile(validators, { outDir: encryptedKeystoreOutDir, password });
123
+ }
124
+
125
+ const keystore = {
126
+ schemaVersion: 1,
127
+ validators,
128
+ };
129
+
130
+ await writeKeystoreFile(outputPath, keystore);
131
+
132
+ // Generate staker outputs if requested
133
+ const allStakerOutputs: any[] = [];
134
+ if (stakerOutput && gseAddress && l1RpcUrls && l1ChainId !== undefined) {
135
+ const chain = createEthereumChain(l1RpcUrls, l1ChainId);
136
+ const publicClient = createPublicClient({
137
+ chain: chain.chainInfo,
138
+ transport: fallback(l1RpcUrls.map(url => http(url))),
139
+ });
140
+ const gse = new GSEContract(publicClient, gseAddress);
141
+
142
+ // Extract keystore base name without extension for unique staker output filenames
143
+ const keystoreBaseName = basename(outputPath, '.json');
144
+
145
+ // Process each validator
146
+ for (let i = 0; i < validators.length; i++) {
147
+ const validator = validators[i];
148
+ const outputs = await processAttesterAccounts(validator.attester, gse, password);
149
+
150
+ // Collect all staker outputs
151
+ for (let j = 0; j < outputs.length; j++) {
152
+ allStakerOutputs.push(outputs[j]);
153
+ }
154
+ }
155
+
156
+ // Write a single JSON file with all staker outputs
157
+ if (allStakerOutputs.length > 0) {
158
+ const stakerOutputPath = join(keystoreOutDir, `${keystoreBaseName}_staker_output.json`);
159
+ await writeFile(stakerOutputPath, prettyPrintJSON(allStakerOutputs), 'utf-8');
160
+ }
161
+ }
162
+
163
+ const outputData = !_mnemonic ? { ...keystore, generatedMnemonic: mnemonic } : keystore;
164
+
165
+ // Handle JSON output
166
+ if (json) {
167
+ if (stakerOutput && allStakerOutputs.length > 0) {
168
+ const combinedOutput = {
169
+ keystore: outputData,
170
+ staker: allStakerOutputs,
171
+ };
172
+ maybePrintJson(log, json, combinedOutput as unknown as Record<string, any>);
173
+ } else {
174
+ maybePrintJson(log, json, outputData as unknown as Record<string, any>);
175
+ }
176
+ } else {
177
+ log(`Wrote validator keystore to ${outputPath}`);
178
+ if (stakerOutput && allStakerOutputs.length > 0) {
179
+ const keystoreBaseName = basename(outputPath, '.json');
180
+ const stakerOutputPath = join(keystoreOutDir, `${keystoreBaseName}_staker_output.json`);
181
+ log(`Wrote staker output for ${allStakerOutputs.length} validator(s) to ${stakerOutputPath}`);
182
+ log('');
183
+ }
184
+ }
185
+
186
+ // print a concise summary of public keys (addresses and BLS pubkeys) if no --json options was selected
187
+ if (!json) {
188
+ logValidatorSummaries(log, summaries);
189
+ }
190
+
191
+ if (mnemonic && remoteSigner && !json) {
192
+ for (let i = 0; i < validatorCount; i++) {
193
+ const addrIdx = addressIndex + i;
194
+ const acct = mnemonicToAccount(mnemonic, {
195
+ accountIndex,
196
+ addressIndex: addrIdx,
197
+ });
198
+ log(`attester address: ${acct.address} remoteSignerUrl: ${remoteSigner}`);
199
+ }
200
+ }
201
+
202
+ // Log staker outputs if not in JSON mode
203
+ if (!json && stakerOutput && allStakerOutputs.length > 0) {
204
+ log('\nStaker outputs:');
205
+ log(prettyPrintJSON(allStakerOutputs));
206
+ }
207
+ }
@@ -0,0 +1,326 @@
1
+ import { prettyPrintJSON } from '@aztec/cli/utils';
2
+ import { deriveBlsPrivateKey } from '@aztec/foundation/crypto/bls';
3
+ import { createBn254Keystore } from '@aztec/foundation/crypto/bls/bn254_keystore';
4
+ import { computeBn254G1PublicKeyCompressed } from '@aztec/foundation/crypto/bn254';
5
+ import type { EthAddress } from '@aztec/foundation/eth-address';
6
+ import type { LogFn } from '@aztec/foundation/log';
7
+ import type { EthAccount, EthPrivateKey, ValidatorKeyStore } from '@aztec/node-keystore/types';
8
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
9
+
10
+ import { Wallet } from '@ethersproject/wallet';
11
+ import { constants as fsConstants, mkdirSync } from 'fs';
12
+ import { access, writeFile } from 'fs/promises';
13
+ import { homedir } from 'os';
14
+ import { dirname, isAbsolute, join } from 'path';
15
+ import { mnemonicToAccount } from 'viem/accounts';
16
+
17
+ import { defaultBlsPath } from './utils.js';
18
+
19
+ export type ValidatorSummary = { attesterEth?: string; attesterBls?: string; publisherEth?: string[] };
20
+
21
+ export type BuildValidatorsInput = {
22
+ validatorCount: number;
23
+ publisherCount?: number;
24
+ publishers?: string[];
25
+ accountIndex: number;
26
+ baseAddressIndex: number;
27
+ mnemonic: string;
28
+ ikm?: string;
29
+ blsPath?: string;
30
+ feeRecipient: AztecAddress;
31
+ coinbase?: EthAddress;
32
+ remoteSigner?: string;
33
+ };
34
+
35
+ export function withValidatorIndex(path: string, accountIndex: number = 0, addressIndex: number = 0) {
36
+ // NOTE: The legacy BLS CLI is to allow users who generated keys in 2.1.4 to be able to use the same command
37
+ // to re-generate their keys. In 2.1.5 we switched how we append addresses to the path so this is to maintain backwards compatibility.
38
+ const useLegacyBlsCli = ['true', '1', 'yes', 'y'].includes(process.env.LEGACY_BLS_CLI ?? '');
39
+
40
+ const defaultBlsPathParts = defaultBlsPath.split('/');
41
+
42
+ const parts = path.split('/');
43
+ if (parts.length == defaultBlsPathParts.length && parts.every((part, index) => part === defaultBlsPathParts[index])) {
44
+ if (useLegacyBlsCli) {
45
+ // In 2.1.4, we were using address-index in parts[3] and did NOT use account-index, check lines 32 & 84
46
+ // https://github.com/AztecProtocol/aztec-packages/blob/v2.1.4/yarn-project/cli/src/cmds/validator_keys/shared.ts
47
+
48
+ parts[3] = String(addressIndex);
49
+ } else {
50
+ parts[3] = String(accountIndex);
51
+ parts[5] = String(addressIndex);
52
+ }
53
+ return parts.join('/');
54
+ }
55
+ return path;
56
+ }
57
+
58
+ /**
59
+ * Compute a compressed BN254 G1 public key from a private key.
60
+ * @param privateKeyHex - Private key as 0x-prefixed hex string
61
+ * @returns Compressed G1 point (32 bytes with sign bit in MSB)
62
+ */
63
+ export async function computeBlsPublicKeyCompressed(privateKeyHex: string): Promise<string> {
64
+ return await computeBn254G1PublicKeyCompressed(privateKeyHex);
65
+ }
66
+
67
+ export function deriveEthAttester(
68
+ mnemonic: string,
69
+ baseAccountIndex: number,
70
+ addressIndex: number,
71
+ remoteSigner?: string,
72
+ ): EthAccount | EthPrivateKey {
73
+ const acct = mnemonicToAccount(mnemonic, { accountIndex: baseAccountIndex, addressIndex });
74
+ return remoteSigner
75
+ ? ({ address: acct.address as unknown as EthAddress, remoteSignerUrl: remoteSigner } as EthAccount)
76
+ : (('0x' + Buffer.from(acct.getHdKey().privateKey!).toString('hex')) as EthPrivateKey);
77
+ }
78
+
79
+ export async function buildValidatorEntries(input: BuildValidatorsInput) {
80
+ const {
81
+ validatorCount,
82
+ publisherCount = 0,
83
+ publishers,
84
+ accountIndex,
85
+ baseAddressIndex,
86
+ mnemonic,
87
+ ikm,
88
+ blsPath,
89
+ feeRecipient,
90
+ coinbase,
91
+ remoteSigner,
92
+ } = input;
93
+
94
+ const summaries: ValidatorSummary[] = [];
95
+
96
+ const validators = await Promise.all(
97
+ Array.from({ length: validatorCount }, async (_unused, i) => {
98
+ const addressIndex = baseAddressIndex + i;
99
+ const basePath = blsPath ?? defaultBlsPath;
100
+ const perValidatorPath = withValidatorIndex(basePath, accountIndex, addressIndex);
101
+
102
+ const blsPrivKey = ikm || mnemonic ? deriveBlsPrivateKey(mnemonic, ikm, perValidatorPath) : undefined;
103
+ const blsPubCompressed = blsPrivKey ? await computeBlsPublicKeyCompressed(blsPrivKey) : undefined;
104
+
105
+ const ethAttester = deriveEthAttester(mnemonic, accountIndex, addressIndex, remoteSigner);
106
+ const attester = blsPrivKey ? { eth: ethAttester, bls: blsPrivKey } : ethAttester;
107
+
108
+ let publisherField: EthAccount | EthPrivateKey | (EthAccount | EthPrivateKey)[] | undefined;
109
+ const publisherAddresses: string[] = [];
110
+ if (publishers && publishers.length > 0) {
111
+ publisherAddresses.push(...publishers);
112
+ publisherField = publishers.length === 1 ? (publishers[0] as EthPrivateKey) : (publishers as EthPrivateKey[]);
113
+ } else if (publisherCount > 0) {
114
+ const publishersBaseIndex = baseAddressIndex + validatorCount + i * publisherCount;
115
+ const publisherAccounts = Array.from({ length: publisherCount }, (_unused2, j) => {
116
+ const publisherAddressIndex = publishersBaseIndex + j;
117
+ const pubAcct = mnemonicToAccount(mnemonic, {
118
+ accountIndex,
119
+ addressIndex: publisherAddressIndex,
120
+ });
121
+ publisherAddresses.push(pubAcct.address as unknown as string);
122
+ return remoteSigner
123
+ ? ({ address: pubAcct.address as unknown as EthAddress, remoteSignerUrl: remoteSigner } as EthAccount)
124
+ : (('0x' + Buffer.from(pubAcct.getHdKey().privateKey!).toString('hex')) as EthPrivateKey);
125
+ });
126
+ publisherField = publisherCount === 1 ? publisherAccounts[0] : publisherAccounts;
127
+ }
128
+
129
+ const acct = mnemonicToAccount(mnemonic, {
130
+ accountIndex,
131
+ addressIndex,
132
+ });
133
+ const attesterEthAddress = acct.address as unknown as string;
134
+ summaries.push({
135
+ attesterEth: attesterEthAddress,
136
+ attesterBls: blsPubCompressed,
137
+ publisherEth: publisherAddresses.length > 0 ? publisherAddresses : undefined,
138
+ });
139
+
140
+ return {
141
+ attester,
142
+ ...(publisherField !== undefined ? { publisher: publisherField } : {}),
143
+ feeRecipient,
144
+ coinbase: coinbase ?? attesterEthAddress,
145
+ } as ValidatorKeyStore;
146
+ }),
147
+ );
148
+
149
+ return { validators, summaries };
150
+ }
151
+
152
+ export async function resolveKeystoreOutputPath(dataDir?: string, file?: string) {
153
+ const defaultDataDir = join(homedir(), '.aztec', 'keystore');
154
+ const resolvedDir = dataDir && dataDir.length > 0 ? dataDir : defaultDataDir;
155
+ let outputPath: string;
156
+ if (file && file.length > 0) {
157
+ outputPath = isAbsolute(file) ? file : join(resolvedDir, file);
158
+ } else {
159
+ let index = 1;
160
+ while (true) {
161
+ const candidate = join(resolvedDir, `key${index}.json`);
162
+ try {
163
+ await access(candidate, fsConstants.F_OK);
164
+ index += 1;
165
+ } catch {
166
+ outputPath = candidate;
167
+ break;
168
+ }
169
+ }
170
+ }
171
+ return { resolvedDir, outputPath: outputPath! };
172
+ }
173
+
174
+ export async function writeKeystoreFile(path: string, keystore: unknown) {
175
+ mkdirSync(dirname(path), { recursive: true });
176
+ await writeFile(path, JSON.stringify(keystore, null, 2), { encoding: 'utf-8' });
177
+ }
178
+
179
+ export function logValidatorSummaries(log: LogFn, summaries: ValidatorSummary[]) {
180
+ const lines: string[] = [];
181
+ for (let i = 0; i < summaries.length; i++) {
182
+ const v = summaries[i];
183
+ lines.push(`acc${i + 1}:`);
184
+ lines.push(` attester:`);
185
+ if (v.attesterEth) {
186
+ lines.push(` eth: ${v.attesterEth}`);
187
+ }
188
+ if (v.attesterBls) {
189
+ lines.push(` bls: ${v.attesterBls}`);
190
+ }
191
+ if (v.publisherEth && v.publisherEth.length > 0) {
192
+ lines.push(` publisher:`);
193
+ for (const addr of v.publisherEth) {
194
+ lines.push(` - ${addr}`);
195
+ }
196
+ }
197
+ }
198
+ if (lines.length > 0) {
199
+ log(lines.join('\n'));
200
+ }
201
+ }
202
+
203
+ export function maybePrintJson(log: LogFn, jsonFlag: boolean | undefined, obj: unknown) {
204
+ if (jsonFlag) {
205
+ log(prettyPrintJSON(obj as Record<string, any>));
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Writes a BN254 keystore file for a BN254 BLS private key.
211
+ * Returns the absolute path to the written file.
212
+ *
213
+ * @param outDir - Directory to write the keystore file to
214
+ * @param fileNameBase - Base name for the keystore file (will be sanitized)
215
+ * @param password - Password for encrypting the private key
216
+ * @param privateKeyHex - Private key as 0x-prefixed hex string (32 bytes)
217
+ * @param pubkeyHex - Public key as hex string
218
+ * @param derivationPath - BIP-44 style derivation path
219
+ * @returns Absolute path to the written keystore file
220
+ */
221
+ export async function writeBn254BlsKeystore(
222
+ outDir: string,
223
+ fileNameBase: string,
224
+ password: string,
225
+ privateKeyHex: string,
226
+ pubkeyHex: string,
227
+ derivationPath: string,
228
+ ): Promise<string> {
229
+ mkdirSync(outDir, { recursive: true });
230
+
231
+ const keystore = createBn254Keystore(password, privateKeyHex, pubkeyHex, derivationPath);
232
+
233
+ const safeBase = fileNameBase.replace(/[^a-zA-Z0-9_-]/g, '_');
234
+ const outPath = join(outDir, `keystore-${safeBase}.json`);
235
+ await writeFile(outPath, JSON.stringify(keystore, null, 2), { encoding: 'utf-8' });
236
+ return outPath;
237
+ }
238
+
239
+ /** Replace plaintext BLS keys in validators with { path, password } pointing to BN254 keystore files. */
240
+ export async function writeBlsBn254ToFile(
241
+ validators: ValidatorKeyStore[],
242
+ options: { outDir: string; password: string; blsPath?: string },
243
+ ): 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;
250
+
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
+ }
256
+
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);
261
+
262
+ if (typeof att === 'object') {
263
+ (att as any).bls = { path: keystorePath, password: options.password };
264
+ }
265
+ }
266
+ }
267
+
268
+ /** Writes an Ethereum JSON V3 keystore using ethers, returns absolute path */
269
+ export async function writeEthJsonV3Keystore(
270
+ outDir: string,
271
+ fileNameBase: string,
272
+ password: string,
273
+ privateKeyHex: string,
274
+ ): Promise<string> {
275
+ const safeBase = fileNameBase.replace(/[^a-zA-Z0-9_-]/g, '_');
276
+ mkdirSync(outDir, { recursive: true });
277
+ const wallet = new Wallet(privateKeyHex);
278
+ const json = await wallet.encrypt(password);
279
+ const outPath = join(outDir, `keystore-eth-${safeBase}.json`);
280
+ await writeFile(outPath, json, { encoding: 'utf-8' });
281
+ return outPath;
282
+ }
283
+
284
+ /** Replace plaintext ETH keys in validators with { path, password } pointing to JSON V3 files. */
285
+ export async function writeEthJsonV3ToFile(
286
+ validators: ValidatorKeyStore[],
287
+ options: { outDir: string; password: string },
288
+ ): Promise<void> {
289
+ const maybeEncryptEth = async (account: any, label: string) => {
290
+ 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 };
294
+ }
295
+ return account;
296
+ };
297
+
298
+ for (let i = 0; i < validators.length; i++) {
299
+ const v = validators[i];
300
+ if (!v || typeof v !== 'object') {
301
+ continue;
302
+ }
303
+
304
+ // attester may be string (eth), object with eth, or remote signer
305
+ const att = (v as any).attester;
306
+ if (typeof att === 'string') {
307
+ (v as any).attester = await maybeEncryptEth(att, `attester_${i + 1}`);
308
+ } else if (att && typeof att === 'object' && 'eth' in att) {
309
+ (att as any).eth = await maybeEncryptEth((att as any).eth, `attester_${i + 1}`);
310
+ }
311
+
312
+ // publisher can be single or array
313
+ if ('publisher' in v) {
314
+ const pub = (v as any).publisher;
315
+ if (Array.isArray(pub)) {
316
+ const out: any[] = [];
317
+ for (let j = 0; j < pub.length; j++) {
318
+ out.push(await maybeEncryptEth(pub[j], `publisher_${i + 1}_${j + 1}`));
319
+ }
320
+ (v as any).publisher = out;
321
+ } else if (pub !== undefined) {
322
+ (v as any).publisher = await maybeEncryptEth(pub, `publisher_${i + 1}`);
323
+ }
324
+ }
325
+ }
326
+ }