@aztec-labs/node-keystore 6.0.0-nightly.20260829

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