@aztec/node-keystore 2.0.0-nightly.20250816

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.
@@ -0,0 +1,646 @@
1
+ /**
2
+ * Keystore Manager
3
+ *
4
+ * Manages keystore configuration and delegates signing operations to appropriate signers.
5
+ */
6
+ import { Buffer32 } from '@aztec/foundation/buffer';
7
+ import { EthAddress } from '@aztec/foundation/eth-address';
8
+ import type { Signature } from '@aztec/foundation/eth-signature';
9
+
10
+ import { Wallet } from '@ethersproject/wallet';
11
+ import { readFileSync, readdirSync, statSync } from 'fs';
12
+ import { extname, join } from 'path';
13
+ import type { TypedDataDefinition } from 'viem';
14
+ import { mnemonicToAccount } from 'viem/accounts';
15
+
16
+ import { LocalSigner, RemoteSigner, type Signer } from './signer.js';
17
+ import type {
18
+ EthAccount,
19
+ EthAccounts,
20
+ EthJsonKeyFileV3Config,
21
+ EthMnemonicConfig,
22
+ EthPrivateKey,
23
+ EthRemoteSignerAccount,
24
+ EthRemoteSignerConfig,
25
+ KeyStore,
26
+ ProverKeyStore,
27
+ ValidatorKeyStore as ValidatorKeystoreConfig,
28
+ } from './types.js';
29
+
30
+ /**
31
+ * Error thrown when keystore operations fail
32
+ */
33
+ export class KeystoreError extends Error {
34
+ constructor(
35
+ message: string,
36
+ public override cause?: Error,
37
+ ) {
38
+ super(message);
39
+ this.name = 'KeystoreError';
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Keystore Manager - coordinates signing operations based on keystore configuration
45
+ */
46
+ export class KeystoreManager {
47
+ private readonly keystore: KeyStore;
48
+
49
+ /**
50
+ * Create a keystore manager from a parsed configuration.
51
+ * Performs a lightweight duplicate-attester check without decrypting JSON V3 or deriving mnemonics.
52
+ * @param keystore Parsed keystore configuration
53
+ */
54
+ constructor(keystore: KeyStore) {
55
+ this.keystore = keystore;
56
+ this.validateUniqueAttesterAddresses();
57
+ }
58
+
59
+ /**
60
+ * Validates that attester addresses are unique across all validators
61
+ * Only checks simple private key attesters, not JSON-V3 or mnemonic attesters,
62
+ * these are validated when decrypting the JSON-V3 keystore files
63
+ * @throws KeystoreError if duplicate attester addresses are found
64
+ */
65
+ private validateUniqueAttesterAddresses(): void {
66
+ const seenAddresses = new Set<string>();
67
+ const validatorCount = this.getValidatorCount();
68
+ for (let validatorIndex = 0; validatorIndex < validatorCount; validatorIndex++) {
69
+ const validator = this.getValidator(validatorIndex);
70
+ const addresses = this.extractAddressesWithoutSensitiveOperations(validator.attester);
71
+ for (const addr of addresses) {
72
+ const address = addr.toString().toLowerCase();
73
+ if (seenAddresses.has(address)) {
74
+ throw new KeystoreError(
75
+ `Duplicate attester address found: ${addr.toString()}. An attester address may only appear once across all configuration blocks.`,
76
+ );
77
+ }
78
+ seenAddresses.add(address);
79
+ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Best-effort address extraction that avoids decryption/derivation (no JSON-V3 or mnemonic processing).
85
+ * This is used at construction time to check for obvious duplicates without throwing for invalid inputs.
86
+ */
87
+ private extractAddressesWithoutSensitiveOperations(accounts: EthAccounts): EthAddress[] {
88
+ const results: EthAddress[] = [];
89
+
90
+ const handleAccount = (account: EthAccount): void => {
91
+ // String cases: private key or address or remote signer address
92
+ if (typeof account === 'string') {
93
+ if (account.startsWith('0x') && account.length === 66) {
94
+ // Private key -> derive address locally without external deps
95
+ try {
96
+ const signer = new LocalSigner(Buffer32.fromString(account as EthPrivateKey));
97
+ results.push(signer.address);
98
+ } catch {
99
+ // Ignore invalid private key at construction time
100
+ }
101
+ return;
102
+ }
103
+
104
+ if (account.startsWith('0x') && account.length === 42) {
105
+ // Address string
106
+ try {
107
+ results.push(EthAddress.fromString(account));
108
+ } catch {
109
+ // Ignore invalid address format at construction time
110
+ }
111
+ return;
112
+ }
113
+
114
+ // Any other string cannot be confidently resolved here
115
+ return;
116
+ }
117
+
118
+ // JSON V3 keystore: skip (requires decryption)
119
+ if ('path' in account) {
120
+ return;
121
+ }
122
+
123
+ // Mnemonic: skip (requires derivation and may throw on invalid mnemonics)
124
+ if ('mnemonic' in (account as any)) {
125
+ return;
126
+ }
127
+
128
+ // Remote signer account (object form)
129
+ const remoteSigner = account as EthRemoteSignerAccount;
130
+ const address = typeof remoteSigner === 'string' ? remoteSigner : remoteSigner.address;
131
+ if (address) {
132
+ try {
133
+ results.push(EthAddress.fromString(address));
134
+ } catch {
135
+ // Ignore invalid address format at construction time
136
+ }
137
+ }
138
+ };
139
+
140
+ if (Array.isArray(accounts)) {
141
+ for (const account of accounts) {
142
+ const subResults = this.extractAddressesWithoutSensitiveOperations(account);
143
+ results.push(...subResults);
144
+ }
145
+ return results;
146
+ }
147
+
148
+ handleAccount(accounts as EthAccount);
149
+ return results;
150
+ }
151
+
152
+ /**
153
+ * Create signers for validator attester accounts
154
+ */
155
+ createAttesterSigners(validatorIndex: number): Signer[] {
156
+ const validator = this.getValidator(validatorIndex);
157
+ return this.createSignersFromEthAccounts(validator.attester, validator.remoteSigner || this.keystore.remoteSigner);
158
+ }
159
+
160
+ /**
161
+ * Create signers for validator publisher accounts (falls back to attester if not specified)
162
+ */
163
+ createPublisherSigners(validatorIndex: number): Signer[] {
164
+ const validator = this.getValidator(validatorIndex);
165
+
166
+ if (validator.publisher) {
167
+ return this.createSignersFromEthAccounts(
168
+ validator.publisher,
169
+ validator.remoteSigner || this.keystore.remoteSigner,
170
+ );
171
+ }
172
+
173
+ // Fall back to attester signers
174
+ return this.createAttesterSigners(validatorIndex);
175
+ }
176
+
177
+ /**
178
+ * Create signers for slasher accounts
179
+ */
180
+ createSlasherSigners(): Signer[] {
181
+ if (!this.keystore.slasher) {
182
+ return [];
183
+ }
184
+
185
+ return this.createSignersFromEthAccounts(this.keystore.slasher, this.keystore.remoteSigner);
186
+ }
187
+
188
+ /**
189
+ * Create signers for prover accounts
190
+ */
191
+ createProverSigners(): Signer[] {
192
+ if (!this.keystore.prover) {
193
+ return [];
194
+ }
195
+
196
+ // Handle simple prover case (just a private key)
197
+ if (
198
+ typeof this.keystore.prover === 'string' ||
199
+ 'path' in this.keystore.prover ||
200
+ 'address' in this.keystore.prover
201
+ ) {
202
+ return this.createSignersFromEthAccounts(this.keystore.prover as EthAccount, this.keystore.remoteSigner);
203
+ }
204
+
205
+ // Handle complex prover case with id and publishers
206
+ const proverConfig = this.keystore.prover;
207
+ const signers: Signer[] = [];
208
+
209
+ for (const publisherAccounts of proverConfig.publisher) {
210
+ const publisherSigners = this.createSignersFromEthAccounts(publisherAccounts, this.keystore.remoteSigner);
211
+ signers.push(...publisherSigners);
212
+ }
213
+
214
+ return signers;
215
+ }
216
+
217
+ /**
218
+ * Get validator configuration by index
219
+ */
220
+ getValidator(index: number): ValidatorKeystoreConfig {
221
+ if (!this.keystore.validators || index >= this.keystore.validators.length || index < 0) {
222
+ throw new KeystoreError(`Validator index ${index} out of bounds`);
223
+ }
224
+ return this.keystore.validators[index];
225
+ }
226
+
227
+ /**
228
+ * Get validator count
229
+ */
230
+ getValidatorCount(): number {
231
+ return this.keystore.validators?.length || 0;
232
+ }
233
+
234
+ /**
235
+ * Get coinbase address for validator (falls back to first attester address)
236
+ */
237
+ getCoinbaseAddress(validatorIndex: number): EthAddress {
238
+ const validator = this.getValidator(validatorIndex);
239
+
240
+ if (validator.coinbase) {
241
+ return EthAddress.fromString(validator.coinbase);
242
+ }
243
+
244
+ // Fall back to first attester address
245
+ const attesterSigners = this.createAttesterSigners(validatorIndex);
246
+ if (attesterSigners.length === 0) {
247
+ throw new KeystoreError(`No attester signers found for validator ${validatorIndex}`);
248
+ }
249
+
250
+ return attesterSigners[0].address;
251
+ }
252
+
253
+ /**
254
+ * Get fee recipient for validator
255
+ */
256
+ getFeeRecipient(validatorIndex: number): string {
257
+ const validator = this.getValidator(validatorIndex);
258
+ return validator.feeRecipient;
259
+ }
260
+
261
+ /**
262
+ * Get the raw slasher configuration as provided in the keystore file.
263
+ * @returns The slasher accounts configuration or undefined if not set
264
+ */
265
+ getSlasherAccounts(): EthAccounts | undefined {
266
+ return this.keystore.slasher;
267
+ }
268
+
269
+ /**
270
+ * Get the raw prover configuration as provided in the keystore file.
271
+ * @returns The prover configuration or undefined if not set
272
+ */
273
+ getProverConfig(): ProverKeyStore | undefined {
274
+ return this.keystore.prover;
275
+ }
276
+
277
+ /**
278
+ * Resolves attester accounts (including JSON V3 and mnemonic) and checks for duplicate addresses across validators.
279
+ * Throws if the same resolved address appears in more than one validator configuration.
280
+ */
281
+ validateResolvedUniqueAttesterAddresses(): void {
282
+ const seenAddresses = new Set<string>();
283
+ const validatorCount = this.getValidatorCount();
284
+ for (let validatorIndex = 0; validatorIndex < validatorCount; validatorIndex++) {
285
+ const validator = this.getValidator(validatorIndex);
286
+ const signers = this.createSignersFromEthAccounts(
287
+ validator.attester,
288
+ validator.remoteSigner || this.keystore.remoteSigner,
289
+ );
290
+ for (const signer of signers) {
291
+ const address = signer.address.toString().toLowerCase();
292
+ if (seenAddresses.has(address)) {
293
+ throw new KeystoreError(
294
+ `Duplicate attester address found after resolving accounts: ${address}. An attester address may only appear once across all configuration blocks.`,
295
+ );
296
+ }
297
+ seenAddresses.add(address);
298
+ }
299
+ }
300
+ }
301
+
302
+ /**
303
+ * Create signers from EthAccounts configuration
304
+ */
305
+ private createSignersFromEthAccounts(accounts: EthAccounts, defaultRemoteSigner?: EthRemoteSignerConfig): Signer[] {
306
+ if (typeof accounts === 'string') {
307
+ return [this.createSignerFromEthAccount(accounts, defaultRemoteSigner)];
308
+ }
309
+
310
+ if (Array.isArray(accounts)) {
311
+ const signers: Signer[] = [];
312
+ for (const account of accounts) {
313
+ const accountSigners = this.createSignersFromEthAccounts(account, defaultRemoteSigner);
314
+ signers.push(...accountSigners);
315
+ }
316
+ return signers;
317
+ }
318
+
319
+ // Mnemonic configuration
320
+ if ('mnemonic' in accounts) {
321
+ return this.createSignersFromMnemonic(accounts);
322
+ }
323
+
324
+ // Single account object - handle JSON V3 directory case
325
+ if ('path' in accounts) {
326
+ const result = this.createSignerFromJsonV3(accounts);
327
+ return result;
328
+ }
329
+
330
+ return [this.createSignerFromEthAccount(accounts, defaultRemoteSigner)];
331
+ }
332
+
333
+ /**
334
+ * Create a signer from a single EthAccount configuration
335
+ */
336
+ private createSignerFromEthAccount(account: EthAccount, defaultRemoteSigner?: EthRemoteSignerConfig): Signer {
337
+ // Private key (hex string)
338
+ if (typeof account === 'string') {
339
+ if (account.startsWith('0x') && account.length === 66) {
340
+ // Private key
341
+ return new LocalSigner(Buffer32.fromString(account as EthPrivateKey));
342
+ } else {
343
+ // Remote signer address only - use default remote signer config
344
+ if (!defaultRemoteSigner) {
345
+ throw new KeystoreError(`No remote signer configuration found for address ${account}`);
346
+ }
347
+ return new RemoteSigner(EthAddress.fromString(account), defaultRemoteSigner);
348
+ }
349
+ }
350
+
351
+ // JSON V3 keystore
352
+ if ('path' in account) {
353
+ const result = this.createSignerFromJsonV3(account);
354
+ return result[0];
355
+ }
356
+
357
+ // Remote signer account
358
+ const remoteSigner = account as EthRemoteSignerAccount;
359
+ if (typeof remoteSigner === 'string') {
360
+ // Just an address - use default config
361
+ if (!defaultRemoteSigner) {
362
+ throw new KeystoreError(`No remote signer configuration found for address ${remoteSigner}`);
363
+ }
364
+ return new RemoteSigner(EthAddress.fromString(remoteSigner), defaultRemoteSigner);
365
+ }
366
+
367
+ // Remote signer with config
368
+ const config = remoteSigner.remoteSignerUrl
369
+ ? {
370
+ remoteSignerUrl: remoteSigner.remoteSignerUrl,
371
+ certPath: remoteSigner.certPath,
372
+ certPass: remoteSigner.certPass,
373
+ }
374
+ : defaultRemoteSigner;
375
+
376
+ if (!config) {
377
+ throw new KeystoreError(`No remote signer configuration found for address ${remoteSigner.address}`);
378
+ }
379
+
380
+ return new RemoteSigner(EthAddress.fromString(remoteSigner.address), config);
381
+ }
382
+
383
+ /**
384
+ * Create signer from JSON V3 keystore file or directory
385
+ */
386
+ private createSignerFromJsonV3(config: EthJsonKeyFileV3Config): Signer[] {
387
+ try {
388
+ const stats = statSync(config.path);
389
+
390
+ if (stats.isDirectory()) {
391
+ // Handle directory - load all JSON files
392
+ const files = readdirSync(config.path);
393
+ const signers: Signer[] = [];
394
+ const seenAddresses = new Map<string, string>(); // address -> file name
395
+
396
+ for (const file of files) {
397
+ // Only process .json files
398
+ if (extname(file).toLowerCase() !== '.json') {
399
+ continue;
400
+ }
401
+
402
+ const filePath = join(config.path, file);
403
+ try {
404
+ const signer = this.createSignerFromSingleJsonV3File(filePath, config.password);
405
+ const addressString = signer.address.toString().toLowerCase();
406
+ const existingFile = seenAddresses.get(addressString);
407
+ if (existingFile) {
408
+ throw new KeystoreError(
409
+ `Duplicate JSON V3 keystore address ${addressString} found in directory ${config.path} (files: ${existingFile} and ${file}). Each keystore must have a unique address.`,
410
+ );
411
+ }
412
+ seenAddresses.set(addressString, file);
413
+ signers.push(signer);
414
+ } catch (error) {
415
+ // Re-throw with file context
416
+ throw new KeystoreError(`Failed to load keystore file ${file}: ${error}`, error as Error);
417
+ }
418
+ }
419
+
420
+ if (signers.length === 0) {
421
+ throw new KeystoreError(`No JSON keystore files found in directory ${config.path}`);
422
+ }
423
+ return signers;
424
+ } else {
425
+ // Single file
426
+ return [this.createSignerFromSingleJsonV3File(config.path, config.password)];
427
+ }
428
+ } catch (error) {
429
+ if (error instanceof KeystoreError) {
430
+ throw error;
431
+ }
432
+ throw new KeystoreError(`Failed to access JSON V3 keystore ${config.path}: ${error}`, error as Error);
433
+ }
434
+ }
435
+
436
+ /**
437
+ * Create signer from a single JSON V3 keystore file
438
+ */
439
+ private createSignerFromSingleJsonV3File(filePath: string, password?: string): Signer {
440
+ try {
441
+ // Read the keystore file
442
+ const keystoreJson = readFileSync(filePath, 'utf8');
443
+
444
+ // Get password - prompt for it if not provided
445
+ const resolvedPassword = password;
446
+ if (!resolvedPassword) {
447
+ throw new KeystoreError(`No password provided for keystore ${filePath}. Provide password in config.`);
448
+ }
449
+
450
+ // Use @ethersproject/wallet to decrypt the JSON V3 keystore synchronously
451
+ const ethersWallet = Wallet.fromEncryptedJsonSync(keystoreJson, resolvedPassword);
452
+
453
+ // Convert the private key to our format
454
+ const privateKey = Buffer32.fromString(ethersWallet.privateKey);
455
+
456
+ return new LocalSigner(privateKey);
457
+ } catch (error) {
458
+ const err = error as Error;
459
+ throw new KeystoreError(`Failed to decrypt JSON V3 keystore ${filePath}: ${err.message}`, err);
460
+ }
461
+ }
462
+
463
+ /**
464
+ * Create signers from mnemonic configuration using BIP44 derivation
465
+ */
466
+ private createSignersFromMnemonic(config: EthMnemonicConfig): Signer[] {
467
+ const { mnemonic, addressIndex = 0, accountIndex = 0, addressCount = 1, accountCount = 1 } = config;
468
+ const signers: Signer[] = [];
469
+
470
+ try {
471
+ // Use viem's mnemonic derivation (imported at top of file)
472
+
473
+ // Normalize mnemonic by trimming whitespace
474
+ const normalizedMnemonic = mnemonic.trim();
475
+
476
+ for (let accIdx = accountIndex; accIdx < accountIndex + accountCount; accIdx++) {
477
+ for (let addrIdx = addressIndex; addrIdx < addressIndex + addressCount; addrIdx++) {
478
+ const viemAccount = mnemonicToAccount(normalizedMnemonic, {
479
+ accountIndex: accIdx,
480
+ addressIndex: addrIdx,
481
+ });
482
+
483
+ // Extract the private key from the viem account
484
+ const privateKeyBytes = viemAccount.getHdKey().privateKey!;
485
+ const privateKey = Buffer32.fromBuffer(Buffer.from(privateKeyBytes));
486
+ signers.push(new LocalSigner(privateKey));
487
+ }
488
+ }
489
+
490
+ return signers;
491
+ } catch (error) {
492
+ throw new KeystoreError(`Failed to derive accounts from mnemonic: ${error}`, error as Error);
493
+ }
494
+ }
495
+
496
+ /**
497
+ * Sign message with a specific signer
498
+ */
499
+ async signMessage(signer: Signer, message: Buffer32): Promise<Signature> {
500
+ return await signer.signMessage(message);
501
+ }
502
+
503
+ /**
504
+ * Sign typed data with a specific signer
505
+ */
506
+ async signTypedData(signer: Signer, typedData: TypedDataDefinition): Promise<Signature> {
507
+ return await signer.signTypedData(typedData);
508
+ }
509
+
510
+ /**
511
+ * Get the effective remote signer configuration for a specific attester address
512
+ * Precedence: account-level override > validator-level config > file-level default
513
+ */
514
+ getEffectiveRemoteSignerConfig(
515
+ validatorIndex: number,
516
+ attesterAddress: EthAddress,
517
+ ): EthRemoteSignerConfig | undefined {
518
+ const validator = this.getValidator(validatorIndex);
519
+
520
+ // Helper to get address from an account configuration
521
+ const getAddressFromAccount = (account: EthAccount): EthAddress | EthAddress[] | null => {
522
+ if (typeof account === 'string') {
523
+ if (account.startsWith('0x') && account.length === 66) {
524
+ // This is a private key - derive the address
525
+ try {
526
+ const signer = new LocalSigner(Buffer32.fromString(account as EthPrivateKey));
527
+ return signer.address;
528
+ } catch {
529
+ return null;
530
+ }
531
+ } else if (account.startsWith('0x') && account.length === 42) {
532
+ // This is an address
533
+ try {
534
+ return EthAddress.fromString(account);
535
+ } catch {
536
+ return null;
537
+ }
538
+ }
539
+ return null;
540
+ }
541
+
542
+ // JSON V3 keystore
543
+ if ('path' in account) {
544
+ try {
545
+ const signers = this.createSignerFromJsonV3(account);
546
+ return signers.map(s => s.address);
547
+ } catch {
548
+ return null;
549
+ }
550
+ }
551
+
552
+ // Remote signer account
553
+ const remoteSigner = account as EthRemoteSignerAccount;
554
+ const address = typeof remoteSigner === 'string' ? remoteSigner : remoteSigner.address;
555
+ try {
556
+ return EthAddress.fromString(address);
557
+ } catch {
558
+ return null;
559
+ }
560
+ };
561
+
562
+ // Helper to check if account matches and get its remote signer config
563
+ const checkAccount = (account: EthAccount): EthRemoteSignerConfig | undefined => {
564
+ const addresses = getAddressFromAccount(account);
565
+ if (!addresses) {
566
+ return undefined;
567
+ }
568
+
569
+ const addressArray = Array.isArray(addresses) ? addresses : [addresses];
570
+ const matches = addressArray.some(addr => addr.equals(attesterAddress));
571
+
572
+ if (!matches) {
573
+ return undefined;
574
+ }
575
+
576
+ // Found a match - determine the config to return
577
+ if (typeof account === 'string') {
578
+ if (account.startsWith('0x') && account.length === 66) {
579
+ // Private key - local signer, no remote config
580
+ return undefined;
581
+ } else {
582
+ // Address only - use defaults
583
+ return validator.remoteSigner || this.keystore.remoteSigner;
584
+ }
585
+ }
586
+
587
+ // JSON V3 - local signer, no remote config
588
+ if ('path' in account) {
589
+ return undefined;
590
+ }
591
+
592
+ // Remote signer account with potential override
593
+ const remoteSigner = account as EthRemoteSignerAccount;
594
+ if (typeof remoteSigner === 'string') {
595
+ // Just an address - use defaults
596
+ return validator.remoteSigner || this.keystore.remoteSigner;
597
+ }
598
+
599
+ // Has inline config
600
+ if (remoteSigner.remoteSignerUrl) {
601
+ return {
602
+ remoteSignerUrl: remoteSigner.remoteSignerUrl,
603
+ certPath: remoteSigner.certPath,
604
+ certPass: remoteSigner.certPass,
605
+ };
606
+ } else {
607
+ // No URL specified, use defaults
608
+ return validator.remoteSigner || this.keystore.remoteSigner;
609
+ }
610
+ };
611
+
612
+ // Check the attester configuration
613
+ const { attester } = validator;
614
+
615
+ if (typeof attester === 'string') {
616
+ const result = checkAccount(attester);
617
+ return result === undefined ? undefined : result;
618
+ }
619
+
620
+ if (Array.isArray(attester)) {
621
+ for (const account of attester) {
622
+ const result = checkAccount(account);
623
+ if (result !== undefined) {
624
+ return result;
625
+ }
626
+ }
627
+ return undefined;
628
+ }
629
+
630
+ // Mnemonic configuration
631
+ if ('mnemonic' in attester) {
632
+ try {
633
+ const signers = this.createSignersFromMnemonic(attester);
634
+ const matches = signers.some(s => s.address.equals(attesterAddress));
635
+ // Mnemonic-derived keys are local signers
636
+ return matches ? undefined : undefined;
637
+ } catch {
638
+ return undefined;
639
+ }
640
+ }
641
+
642
+ // Single account object
643
+ const result = checkAccount(attester);
644
+ return result === undefined ? undefined : result;
645
+ }
646
+ }