@aztec/cli 5.0.0-rc.2 → 5.0.1

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 (29) hide show
  1. package/dest/cmds/validator_keys/eth_json_v3_worker.d.ts +2 -0
  2. package/dest/cmds/validator_keys/eth_json_v3_worker.d.ts.map +1 -0
  3. package/dest/cmds/validator_keys/eth_json_v3_worker.js +27 -0
  4. package/dest/cmds/validator_keys/index.d.ts +1 -1
  5. package/dest/cmds/validator_keys/index.d.ts.map +1 -1
  6. package/dest/cmds/validator_keys/index.js +7 -6
  7. package/dest/cmds/validator_keys/new.d.ts +7 -1
  8. package/dest/cmds/validator_keys/new.d.ts.map +1 -1
  9. package/dest/cmds/validator_keys/new.js +98 -12
  10. package/dest/cmds/validator_keys/set_funding_account.d.ts +14 -0
  11. package/dest/cmds/validator_keys/set_funding_account.d.ts.map +1 -0
  12. package/dest/cmds/validator_keys/set_funding_account.js +37 -0
  13. package/dest/cmds/validator_keys/shared.d.ts +15 -2
  14. package/dest/cmds/validator_keys/shared.d.ts.map +1 -1
  15. package/dest/cmds/validator_keys/shared.js +100 -23
  16. package/dest/cmds/validator_keys/utils.d.ts +12 -2
  17. package/dest/cmds/validator_keys/utils.d.ts.map +1 -1
  18. package/dest/cmds/validator_keys/utils.js +34 -0
  19. package/dest/utils/commands.d.ts +7 -6
  20. package/dest/utils/commands.d.ts.map +1 -1
  21. package/dest/utils/commands.js +8 -7
  22. package/package.json +30 -30
  23. package/src/cmds/validator_keys/eth_json_v3_worker.ts +30 -0
  24. package/src/cmds/validator_keys/index.ts +48 -8
  25. package/src/cmds/validator_keys/new.ts +129 -9
  26. package/src/cmds/validator_keys/set_funding_account.ts +55 -0
  27. package/src/cmds/validator_keys/shared.ts +123 -35
  28. package/src/cmds/validator_keys/utils.ts +44 -1
  29. package/src/utils/commands.ts +12 -11
@@ -0,0 +1,55 @@
1
+ import type { LogFn } from '@aztec/foundation/log';
2
+ import { loadKeystoreFile } from '@aztec/node-keystore/loader';
3
+ import type { KeyStore } from '@aztec/node-keystore/types';
4
+
5
+ import { dirname } from 'path';
6
+ import { privateKeyToAccount } from 'viem/accounts';
7
+
8
+ import { encryptFundingAccountToFile, maybePrintJson, resolveFundingAccount, writeKeystoreFile } from './shared.js';
9
+ import { validateFundingAccountOptions } from './utils.js';
10
+
11
+ export type SetFundingAccountOptions = {
12
+ remoteSigner?: string;
13
+ password?: string;
14
+ encryptedKeystoreDir?: string;
15
+ json?: boolean;
16
+ };
17
+
18
+ /**
19
+ * Sets the top-level funding account of an existing keystore, replacing any previous one. The
20
+ * account may be a private key, or an address paired with a remote signer URL. With a password,
21
+ * a plaintext key is encrypted to an ETH JSON V3 file and stored as a { path, password } reference.
22
+ */
23
+ export async function setFundingAccount(
24
+ existing: string,
25
+ fundingAccount: string,
26
+ options: SetFundingAccountOptions,
27
+ log: LogFn,
28
+ ) {
29
+ const { remoteSigner, password, encryptedKeystoreDir, json } = options;
30
+
31
+ const keystore: KeyStore = loadKeystoreFile(existing);
32
+
33
+ const validated = { fundingAccount, remoteSigner };
34
+ validateFundingAccountOptions(validated, !!keystore.remoteSigner);
35
+
36
+ let resolved = resolveFundingAccount(validated.fundingAccount!, remoteSigner);
37
+ if (password !== undefined) {
38
+ const outDir = encryptedKeystoreDir && encryptedKeystoreDir.length > 0 ? encryptedKeystoreDir : dirname(existing);
39
+ resolved = await encryptFundingAccountToFile(resolved, { outDir, password });
40
+ }
41
+
42
+ if (keystore.fundingAccount) {
43
+ log('Replacing existing funding account in keystore');
44
+ }
45
+ keystore.fundingAccount = resolved;
46
+
47
+ await writeKeystoreFile(existing, keystore);
48
+
49
+ if (!json) {
50
+ const value = validated.fundingAccount!;
51
+ const funderAddress = value.length === 66 ? privateKeyToAccount(value as `0x${string}`).address : value;
52
+ log(`Set funding account ${funderAddress} in ${existing}`);
53
+ }
54
+ maybePrintJson(log, !!json, keystore as unknown as Record<string, any>);
55
+ }
@@ -1,8 +1,9 @@
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';
5
- import type { EthAddress } from '@aztec/foundation/eth-address';
6
+ import { EthAddress } from '@aztec/foundation/eth-address';
6
7
  import type { LogFn } from '@aztec/foundation/log';
7
8
  import type { EthAccount, EthPrivateKey, ValidatorKeyStore } from '@aztec/node-keystore/types';
8
9
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
@@ -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 = {
@@ -76,6 +125,21 @@ export function deriveEthAttester(
76
125
  : (('0x' + Buffer.from(acct.getHdKey().privateKey!).toString('hex')) as EthPrivateKey);
77
126
  }
78
127
 
128
+ /**
129
+ * Resolve a `--funding-account` value into a keystore `EthAccount`. A 66-char value is a private key
130
+ * (used verbatim). A 42-char value is an address: with an explicit `remoteSigner` URL it becomes an
131
+ * `{ address, remoteSignerUrl }` pair; without one it is stored as a bare address that falls back to
132
+ * the keystore-level remote signer at runtime. Callers must validate the value first (see
133
+ * `validateFundingAccountOptions`).
134
+ */
135
+ export function resolveFundingAccount(fundingAccount: string, remoteSigner?: string): EthAccount {
136
+ if (fundingAccount.length === 66) {
137
+ return fundingAccount as EthPrivateKey;
138
+ }
139
+ const address = EthAddress.fromString(fundingAccount);
140
+ return remoteSigner ? ({ address, remoteSignerUrl: remoteSigner } as EthAccount) : address;
141
+ }
142
+
79
143
  export async function buildValidatorEntries(input: BuildValidatorsInput) {
80
144
  const {
81
145
  validatorCount,
@@ -228,7 +292,7 @@ export async function writeBn254BlsKeystore(
228
292
  ): Promise<string> {
229
293
  mkdirSync(outDir, { recursive: true });
230
294
 
231
- const keystore = createBn254Keystore(password, privateKeyHex, pubkeyHex, derivationPath);
295
+ const keystore = await createBn254Keystore(password, privateKeyHex, pubkeyHex, derivationPath);
232
296
 
233
297
  const safeBase = fileNameBase.replace(/[^a-zA-Z0-9_-]/g, '_');
234
298
  const outPath = join(outDir, `keystore-${safeBase}.json`);
@@ -241,28 +305,29 @@ export async function writeBlsBn254ToFile(
241
305
  validators: ValidatorKeyStore[],
242
306
  options: { outDir: string; password: string; blsPath?: string },
243
307
  ): 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;
308
+ await Promise.all(
309
+ validators.map(async (v, i) => {
310
+ if (!v || typeof v !== 'object' || !('attester' in v)) {
311
+ return;
312
+ }
313
+ const att = (v as any).attester;
250
314
 
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
- }
315
+ // Shapes: { bls: <hex> } or { eth: <ethAccount>, bls?: <hex> } or plain EthAccount
316
+ const blsKey: string | undefined = typeof att === 'object' && 'bls' in att ? (att as any).bls : undefined;
317
+ if (!blsKey || typeof blsKey !== 'string') {
318
+ return;
319
+ }
256
320
 
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);
321
+ const pub = await computeBlsPublicKeyCompressed(blsKey);
322
+ const path = options.blsPath ?? defaultBlsPath;
323
+ const fileBase = `${String(i + 1)}_${pub.slice(2, 18)}`;
324
+ const keystorePath = await writeBn254BlsKeystore(options.outDir, fileBase, options.password, blsKey, pub, path);
261
325
 
262
- if (typeof att === 'object') {
263
- (att as any).bls = { path: keystorePath, password: options.password };
264
- }
265
- }
326
+ if (typeof att === 'object') {
327
+ (att as any).bls = { path: keystorePath, password: options.password };
328
+ }
329
+ }),
330
+ );
266
331
  }
267
332
 
268
333
  /** Writes an Ethereum JSON V3 keystore using ethers, returns absolute path */
@@ -274,25 +339,48 @@ export async function writeEthJsonV3Keystore(
274
339
  ): Promise<string> {
275
340
  const safeBase = fileNameBase.replace(/[^a-zA-Z0-9_-]/g, '_');
276
341
  mkdirSync(outDir, { recursive: true });
277
- const wallet = new Wallet(privateKeyHex);
278
- const json = await wallet.encrypt(password);
342
+ const json = await encryptEthJsonV3(privateKeyHex, password);
279
343
  const outPath = join(outDir, `keystore-eth-${safeBase}.json`);
280
344
  await writeFile(outPath, json, { encoding: 'utf-8' });
281
345
  return outPath;
282
346
  }
283
347
 
348
+ /**
349
+ * If `account` is a plaintext ETH private key, encrypt it to a JSON V3 file and return a
350
+ * { path, password } reference; otherwise return it unchanged.
351
+ */
352
+ async function maybeEncryptEthAccount(account: any, label: string, options: { outDir: string; password: string }) {
353
+ if (typeof account === 'string' && account.startsWith('0x') && account.length === 66) {
354
+ const fileBase = `${label}_${account.slice(2, 10)}`;
355
+ const p = await writeEthJsonV3Keystore(options.outDir, fileBase, options.password, account);
356
+ return { path: p, password: options.password };
357
+ }
358
+ return account;
359
+ }
360
+
361
+ /** Encrypt a plaintext funding-account key to a JSON V3 file, replacing it with a { path, password } reference. */
362
+ export async function encryptFundingAccountToFile(
363
+ account: EthAccount,
364
+ options: { outDir: string; password: string },
365
+ ): Promise<EthAccount> {
366
+ return (await maybeEncryptEthAccount(account, 'funding', options)) as EthAccount;
367
+ }
368
+
284
369
  /** Replace plaintext ETH keys in validators with { path, password } pointing to JSON V3 files. */
285
370
  export async function writeEthJsonV3ToFile(
286
371
  validators: ValidatorKeyStore[],
287
372
  options: { outDir: string; password: string },
288
373
  ): Promise<void> {
289
- const maybeEncryptEth = async (account: any, label: string) => {
374
+ const tasks: (() => Promise<void>)[] = [];
375
+
376
+ const maybeQueueEncryptEth = (account: any, label: string, setEncryptedAccount: (account: any) => void) => {
290
377
  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 };
378
+ tasks.push(async () => {
379
+ const fileBase = `${label}_${account.slice(2, 10)}`;
380
+ const path = await writeEthJsonV3Keystore(options.outDir, fileBase, options.password, account);
381
+ setEncryptedAccount({ path, password: options.password });
382
+ });
294
383
  }
295
- return account;
296
384
  };
297
385
 
298
386
  for (let i = 0; i < validators.length; i++) {
@@ -304,23 +392,23 @@ export async function writeEthJsonV3ToFile(
304
392
  // attester may be string (eth), object with eth, or remote signer
305
393
  const att = (v as any).attester;
306
394
  if (typeof att === 'string') {
307
- (v as any).attester = await maybeEncryptEth(att, `attester_${i + 1}`);
395
+ maybeQueueEncryptEth(att, `attester_${i + 1}`, account => ((v as any).attester = account));
308
396
  } else if (att && typeof att === 'object' && 'eth' in att) {
309
- (att as any).eth = await maybeEncryptEth((att as any).eth, `attester_${i + 1}`);
397
+ maybeQueueEncryptEth((att as any).eth, `attester_${i + 1}`, account => ((att as any).eth = account));
310
398
  }
311
399
 
312
400
  // publisher can be single or array
313
401
  if ('publisher' in v) {
314
402
  const pub = (v as any).publisher;
315
403
  if (Array.isArray(pub)) {
316
- const out: any[] = [];
317
404
  for (let j = 0; j < pub.length; j++) {
318
- out.push(await maybeEncryptEth(pub[j], `publisher_${i + 1}_${j + 1}`));
405
+ maybeQueueEncryptEth(pub[j], `publisher_${i + 1}_${j + 1}`, account => (pub[j] = account));
319
406
  }
320
- (v as any).publisher = out;
321
407
  } else if (pub !== undefined) {
322
- (v as any).publisher = await maybeEncryptEth(pub, `publisher_${i + 1}`);
408
+ maybeQueueEncryptEth(pub, `publisher_${i + 1}`, account => ((v as any).publisher = account));
323
409
  }
324
410
  }
325
411
  }
412
+
413
+ await asyncPool(maxEthKeystoreWorkers, tasks, task => task());
326
414
  }
@@ -1,4 +1,4 @@
1
- import type { EthAddress } from '@aztec/foundation/eth-address';
1
+ import { EthAddress } from '@aztec/foundation/eth-address';
2
2
  import { ethPrivateKeySchema } from '@aztec/node-keystore/schemas';
3
3
  import type { EthPrivateKey } from '@aztec/node-keystore/types';
4
4
 
@@ -79,3 +79,46 @@ export function validatePublisherOptions(options: { publishers?: string[]; publi
79
79
  options.publishers = normalizedKeys as EthPrivateKey[];
80
80
  }
81
81
  }
82
+
83
+ /**
84
+ * Validates and normalizes the `--funding-account` option in place. The value may be a private key
85
+ * (used as a local signer) or an ETH address. An address needs a remote signer to sign funding txs:
86
+ * either `--remote-signer`, or a keystore that already defines one (pass `hasKeystoreRemoteSigner`),
87
+ * which a bare address inherits at runtime.
88
+ */
89
+ export function validateFundingAccountOptions(
90
+ options: { fundingAccount?: string; remoteSigner?: string },
91
+ hasKeystoreRemoteSigner = false,
92
+ ) {
93
+ if (!options.fundingAccount) {
94
+ return;
95
+ }
96
+
97
+ let value = options.fundingAccount.trim();
98
+ if (!value.startsWith('0x')) {
99
+ value = '0x' + value;
100
+ }
101
+
102
+ if (value.length === 66) {
103
+ try {
104
+ ethPrivateKeySchema.parse(value);
105
+ } catch (error) {
106
+ throw new Error(`Invalid funding account private key: ${error instanceof Error ? error.message : String(error)}`);
107
+ }
108
+ } else if (value.length === 42) {
109
+ try {
110
+ EthAddress.fromString(value);
111
+ } catch (error) {
112
+ throw new Error(`Invalid funding account address: ${error instanceof Error ? error.message : String(error)}`);
113
+ }
114
+ if (!options.remoteSigner && !hasKeystoreRemoteSigner) {
115
+ throw new Error(
116
+ '--funding-account as an address requires --remote-signer, or a keystore that already defines a remote signer',
117
+ );
118
+ }
119
+ } else {
120
+ throw new Error('Invalid funding account: expected a 32-byte private key or a 20-byte address');
121
+ }
122
+
123
+ options.fundingAccount = value;
124
+ }
@@ -1,4 +1,5 @@
1
1
  import { Fr } from '@aztec/foundation/curves/bn254';
2
+ import { GrumpkinScalar } from '@aztec/foundation/curves/grumpkin';
2
3
  import { EthAddress } from '@aztec/foundation/eth-address';
3
4
  import type { LogFn } from '@aztec/foundation/log';
4
5
  import type { PXE } from '@aztec/pxe/server';
@@ -50,14 +51,14 @@ export const l1ChainIdOption = new Option('-c, --l1-chain-id <number>', 'Chain I
50
51
  return parsedValue;
51
52
  });
52
53
 
53
- export const createSecretKeyOption = (
54
+ export const createSigningKeyOption = (
54
55
  description: string,
55
56
  mandatory: boolean,
56
- argsParser?: (value: string, previous: Fr) => Fr,
57
+ argsParser?: (value: string, previous: GrumpkinScalar) => GrumpkinScalar,
57
58
  ) =>
58
- new Option('-sk, --secret-key <string>', description)
59
- .env('SECRET_KEY')
60
- .argParser(argsParser ?? parseSecretKey)
59
+ new Option('-sk, --signing-key <string>', description)
60
+ .env('SIGNING_KEY')
61
+ .argParser(argsParser ?? parseSigningKey)
61
62
  .makeOptionMandatory(mandatory);
62
63
 
63
64
  export const logJson = (log: LogFn) => (obj: object) => log(JSON.stringify(obj, null, 2));
@@ -357,16 +358,16 @@ export function parsePartialAddress(address: string): Fr {
357
358
  }
358
359
 
359
360
  /**
360
- * Parses a secret key from a string.
361
- * @param privateKey - A string
362
- * @returns A secret key
361
+ * Parses an account signing key from a string.
362
+ * @param signingKey - A string
363
+ * @returns A signing key
363
364
  * @throws InvalidArgumentError if the input string is not valid.
364
365
  */
365
- export function parseSecretKey(secretKey: string): Fr {
366
+ export function parseSigningKey(signingKey: string): GrumpkinScalar {
366
367
  try {
367
- return Fr.fromHexString(secretKey);
368
+ return GrumpkinScalar.fromHexString(signingKey);
368
369
  } catch {
369
- throw new InvalidArgumentError(`Invalid encryption secret key: ${secretKey}`);
370
+ throw new InvalidArgumentError(`Invalid signing key: ${signingKey}`);
370
371
  }
371
372
  }
372
373