@aztec/validator-client 0.0.0-test.0 → 0.0.1-commit.023c3e5

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 (78) hide show
  1. package/README.md +282 -0
  2. package/dest/block_proposal_handler.d.ts +63 -0
  3. package/dest/block_proposal_handler.d.ts.map +1 -0
  4. package/dest/block_proposal_handler.js +546 -0
  5. package/dest/checkpoint_builder.d.ts +66 -0
  6. package/dest/checkpoint_builder.d.ts.map +1 -0
  7. package/dest/checkpoint_builder.js +173 -0
  8. package/dest/config.d.ts +3 -14
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +41 -8
  11. package/dest/duties/validation_service.d.ts +50 -13
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +123 -17
  14. package/dest/factory.d.ts +28 -6
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +13 -6
  17. package/dest/index.d.ts +6 -2
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +5 -1
  20. package/dest/key_store/ha_key_store.d.ts +99 -0
  21. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  22. package/dest/key_store/ha_key_store.js +208 -0
  23. package/dest/key_store/index.d.ts +4 -1
  24. package/dest/key_store/index.d.ts.map +1 -1
  25. package/dest/key_store/index.js +3 -0
  26. package/dest/key_store/interface.d.ts +85 -6
  27. package/dest/key_store/interface.d.ts.map +1 -1
  28. package/dest/key_store/interface.js +3 -3
  29. package/dest/key_store/local_key_store.d.ts +46 -11
  30. package/dest/key_store/local_key_store.d.ts.map +1 -1
  31. package/dest/key_store/local_key_store.js +68 -17
  32. package/dest/key_store/node_keystore_adapter.d.ts +151 -0
  33. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -0
  34. package/dest/key_store/node_keystore_adapter.js +330 -0
  35. package/dest/key_store/web3signer_key_store.d.ts +66 -0
  36. package/dest/key_store/web3signer_key_store.d.ts.map +1 -0
  37. package/dest/key_store/web3signer_key_store.js +156 -0
  38. package/dest/metrics.d.ts +13 -5
  39. package/dest/metrics.d.ts.map +1 -1
  40. package/dest/metrics.js +63 -22
  41. package/dest/tx_validator/index.d.ts +3 -0
  42. package/dest/tx_validator/index.d.ts.map +1 -0
  43. package/dest/tx_validator/index.js +2 -0
  44. package/dest/tx_validator/nullifier_cache.d.ts +14 -0
  45. package/dest/tx_validator/nullifier_cache.d.ts.map +1 -0
  46. package/dest/tx_validator/nullifier_cache.js +24 -0
  47. package/dest/tx_validator/tx_validator_factory.d.ts +19 -0
  48. package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -0
  49. package/dest/tx_validator/tx_validator_factory.js +54 -0
  50. package/dest/validator.d.ts +73 -58
  51. package/dest/validator.d.ts.map +1 -1
  52. package/dest/validator.js +559 -166
  53. package/package.json +37 -21
  54. package/src/block_proposal_handler.ts +555 -0
  55. package/src/checkpoint_builder.ts +314 -0
  56. package/src/config.ts +52 -22
  57. package/src/duties/validation_service.ts +193 -19
  58. package/src/factory.ts +65 -11
  59. package/src/index.ts +5 -1
  60. package/src/key_store/ha_key_store.ts +269 -0
  61. package/src/key_store/index.ts +3 -0
  62. package/src/key_store/interface.ts +100 -5
  63. package/src/key_store/local_key_store.ts +77 -18
  64. package/src/key_store/node_keystore_adapter.ts +398 -0
  65. package/src/key_store/web3signer_key_store.ts +205 -0
  66. package/src/metrics.ts +86 -23
  67. package/src/tx_validator/index.ts +2 -0
  68. package/src/tx_validator/nullifier_cache.ts +30 -0
  69. package/src/tx_validator/tx_validator_factory.ts +154 -0
  70. package/src/validator.ts +757 -221
  71. package/dest/errors/index.d.ts +0 -2
  72. package/dest/errors/index.d.ts.map +0 -1
  73. package/dest/errors/index.js +0 -1
  74. package/dest/errors/validator.error.d.ts +0 -29
  75. package/dest/errors/validator.error.d.ts.map +0 -1
  76. package/dest/errors/validator.error.js +0 -45
  77. package/src/errors/index.ts +0 -1
  78. package/src/errors/validator.error.ts +0 -55
@@ -0,0 +1,398 @@
1
+ import type { EthSigner } from '@aztec/ethereum/eth-signer';
2
+ import type { Buffer32 } from '@aztec/foundation/buffer';
3
+ import { EthAddress } from '@aztec/foundation/eth-address';
4
+ import type { Signature } from '@aztec/foundation/eth-signature';
5
+ import { KeystoreManager, loadKeystoreFile } from '@aztec/node-keystore';
6
+ import type { EthRemoteSignerConfig } from '@aztec/node-keystore';
7
+ import { AztecAddress } from '@aztec/stdlib/aztec-address';
8
+ import { InvalidValidatorPrivateKeyError } from '@aztec/stdlib/validators';
9
+ import type { SigningContext } from '@aztec/validator-ha-signer/types';
10
+
11
+ import type { TypedDataDefinition } from 'viem';
12
+ import { privateKeyToAccount } from 'viem/accounts';
13
+
14
+ import type { ExtendedValidatorKeyStore } from './interface.js';
15
+
16
+ type AddressHex = string;
17
+ type ValidatorIndex = number;
18
+
19
+ interface ValidatorCache {
20
+ attesters: EthSigner[];
21
+ publishers: EthSigner[];
22
+ all: EthSigner[];
23
+ byAddress: Map<AddressHex, EthSigner>; // all signers, any role
24
+ attesterSet: Set<AddressHex>; // attester addresses only
25
+ }
26
+
27
+ export class NodeKeystoreAdapter implements ExtendedValidatorKeyStore {
28
+ private readonly keystoreManager: KeystoreManager;
29
+
30
+ // Per-validator cache (lazy)
31
+ private readonly validators = new Map<ValidatorIndex, ValidatorCache>();
32
+
33
+ private readonly addressIndex = new Map<AddressHex, { signer: EthSigner; validatorIndex: ValidatorIndex }>();
34
+
35
+ private constructor(keystoreManager: KeystoreManager) {
36
+ this.keystoreManager = keystoreManager;
37
+ }
38
+
39
+ /**
40
+ * Create an adapter from a keystore JSON file on disk.
41
+ * @param keystoreFilePath Absolute or relative path to a keystore JSON file
42
+ * @returns A configured NodeKeystoreAdapter instance
43
+ * @throws Error when the file fails schema validation or cannot be read
44
+ */
45
+ static fromKeystoreFile(keystoreFilePath: string): NodeKeystoreAdapter {
46
+ const keystoreConfig = loadKeystoreFile(keystoreFilePath);
47
+ return NodeKeystoreAdapter.fromKeystoreConfig(keystoreConfig);
48
+ }
49
+
50
+ /**
51
+ * Create an adapter from an in-memory keystore-like object.
52
+ * Validates resolved duplicate attester addresses across validators and sources.
53
+ * @param keystoreConfig Parsed config object (typically result of loadKeystoreFile)
54
+ * @returns A configured NodeKeystoreAdapter instance
55
+ * @throws Error when resolved duplicate attester addresses are detected
56
+ */
57
+ static fromKeystoreConfig(keystoreConfig: unknown): NodeKeystoreAdapter {
58
+ const keystoreManager = new KeystoreManager(keystoreConfig as any);
59
+ // Validate resolved attester addresses (covers JSON V3 and mnemonic duplicates across validators)
60
+ keystoreManager.validateResolvedUniqueAttesterAddresses();
61
+ return new NodeKeystoreAdapter(keystoreManager);
62
+ }
63
+
64
+ /**
65
+ * Build an adapter directly from a list of validator private keys.
66
+ * Each key becomes a separate validator using the same key for attester and publisher,
67
+ * coinbase defaults to the derived EOA address, and feeRecipient is a 32-byte padded address.
68
+ * Note: Fee recipient is a temporary placeholder, replace with actual fee recipient when implemented.
69
+ */
70
+ static fromPrivateKeys(privateKeys: string[]): NodeKeystoreAdapter {
71
+ // Minimal validation: 0x + 64 hex
72
+ const isPk = (s: string) => /^0x[0-9a-fA-F]{64}$/.test(s);
73
+ for (const pk of privateKeys) {
74
+ if (!isPk(pk)) {
75
+ throw new InvalidValidatorPrivateKeyError();
76
+ }
77
+ }
78
+
79
+ const validators = privateKeys.map(pk => {
80
+ const account = privateKeyToAccount(pk as `0x${string}`);
81
+ const ethAddress = account.address as `0x${string}`;
82
+ // TODO: Temporary fee recipient, replace with actual fee recipient when implemented
83
+ const feeRecipient = `0x${ethAddress.slice(2).padStart(64, '0')}` as `0x${string}`;
84
+ return {
85
+ attester: pk as `0x${string}`,
86
+ publisher: pk as `0x${string}`,
87
+ coinbase: ethAddress,
88
+ feeRecipient,
89
+ };
90
+ });
91
+
92
+ const cfg = { schemaVersion: 1, validators } as const;
93
+ return NodeKeystoreAdapter.fromKeystoreConfig(cfg);
94
+ }
95
+
96
+ /**
97
+ * Build an adapter for a Web3Signer setup by providing the signer URL and the EOA addresses.
98
+ * Each address becomes a separate validator; attester and publisher point to the same remote signer entry.
99
+ * Note: Fee recipient is a temporary placeholder, replace with actual fee recipient when implemented.
100
+ */
101
+ static fromWeb3Signer(web3SignerUrl: string, addresses: EthAddress[]): NodeKeystoreAdapter {
102
+ const validators = addresses.map(address => {
103
+ const ethAddress = address.toString() as `0x${string}`;
104
+ // TODO: Temporary fee recipient, replace with actual fee recipient when implemented
105
+ const feeRecipient = `0x${ethAddress.slice(2).padStart(64, '0')}` as `0x${string}`;
106
+ return {
107
+ attester: { address: ethAddress, remoteSignerUrl: web3SignerUrl },
108
+ publisher: { address: ethAddress, remoteSignerUrl: web3SignerUrl },
109
+ coinbase: ethAddress,
110
+ feeRecipient,
111
+ };
112
+ });
113
+
114
+ const cfg = { schemaVersion: 1, validators } as const;
115
+ return NodeKeystoreAdapter.fromKeystoreConfig(cfg);
116
+ }
117
+
118
+ static fromKeyStoreManager(manager: KeystoreManager): NodeKeystoreAdapter {
119
+ return new NodeKeystoreAdapter(manager);
120
+ }
121
+
122
+ /**
123
+ * Normalize address keys to lowercase hex strings for map/set usage.
124
+ */
125
+ private static key(addr: EthAddress | AddressHex): AddressHex {
126
+ return typeof addr === 'string' ? addr.toLowerCase() : addr.toString().toLowerCase();
127
+ }
128
+
129
+ /**
130
+ * Ensure per-validator signer cache exists; build it by creating
131
+ * attester/publisher signers and populating indices when missing.
132
+ * @param validatorIndex Index of the validator in the keystore
133
+ * @returns The cached validator entry
134
+ */
135
+ private ensureValidator(validatorIndex: number): ValidatorCache {
136
+ const cached = this.validators.get(validatorIndex);
137
+ if (cached) {
138
+ return cached;
139
+ }
140
+
141
+ const attesters = this.keystoreManager.createAttesterSigners(validatorIndex);
142
+ const publishers = this.keystoreManager.createPublisherSigners(validatorIndex);
143
+
144
+ // Build 'all' + indices
145
+ const byAddress = new Map<AddressHex, EthSigner>();
146
+ const attesterSet = new Set<AddressHex>();
147
+
148
+ for (const s of attesters) {
149
+ const k = NodeKeystoreAdapter.key(s.address);
150
+ byAddress.set(k, s);
151
+ attesterSet.add(k);
152
+ }
153
+ for (const s of publishers) {
154
+ const k = NodeKeystoreAdapter.key(s.address);
155
+ if (!byAddress.has(k)) {
156
+ byAddress.set(k, s);
157
+ }
158
+ }
159
+
160
+ const all = Array.from(byAddress.values());
161
+
162
+ // Populate global index
163
+ for (const [k, signer] of byAddress.entries()) {
164
+ this.addressIndex.set(k, { signer, validatorIndex });
165
+ }
166
+
167
+ const built: ValidatorCache = { attesters, publishers, all, byAddress, attesterSet };
168
+ this.validators.set(validatorIndex, built);
169
+ return built;
170
+ }
171
+
172
+ /**
173
+ * Iterate all validator indices in the keystore manager.
174
+ */
175
+ private *validatorIndices(): Iterable<number> {
176
+ const n = this.keystoreManager.getValidatorCount();
177
+ for (let i = 0; i < n; i++) {
178
+ yield i;
179
+ }
180
+ }
181
+
182
+ /**
183
+ * Find the validator index that contains the given attester address.
184
+ * @param attesterAddress Address to locate
185
+ * @returns Validator index
186
+ * @throws Error when no validator contains the attester
187
+ */
188
+ private findValidatorIndexForAttester(attesterAddress: EthAddress): number {
189
+ const key = NodeKeystoreAdapter.key(attesterAddress);
190
+
191
+ // Fast path: if we’ve already cached any validator that includes this as attester
192
+ for (const i of this.validatorIndices()) {
193
+ const v = this.ensureValidator(i);
194
+ if (v.attesterSet.has(key)) {
195
+ return i;
196
+ }
197
+ }
198
+
199
+ throw new Error(`Attester address ${attesterAddress.toString()} not found in any validator configuration`);
200
+ }
201
+
202
+ /**
203
+ * Get attester address by flat index across all validators' attester sets.
204
+ * @param index Zero-based flat index across all attesters
205
+ * @returns EthAddress for the indexed attester
206
+ * @throws Error when index is out of bounds
207
+ */
208
+ getAddress(index: number): EthAddress {
209
+ const all = this.getAddresses();
210
+ if (index < 0 || index >= all.length) {
211
+ throw new Error(`Index ${index} is out of bounds (0..${all.length - 1}).`);
212
+ }
213
+ return all[index];
214
+ }
215
+
216
+ /**
217
+ * Get all attester addresses across validators (legacy-compatible view).
218
+ */
219
+ getAddresses(): EthAddress[] {
220
+ const out: EthAddress[] = [];
221
+ for (const i of this.validatorIndices()) {
222
+ const v = this.ensureValidator(i);
223
+ // attester addresses only for backward compatibility
224
+ for (const s of v.attesters) {
225
+ out.push(s.address);
226
+ }
227
+ }
228
+ return out;
229
+ }
230
+
231
+ /**
232
+ * Sign typed data with all attester signers across validators.
233
+ * @param typedData EIP-712 typed data
234
+ * @param _context Signing context (ignored by NodeKeystoreAdapter, used for HA protection)
235
+ * @returns Array of signatures in validator order, flattened
236
+ */
237
+ async signTypedData(typedData: TypedDataDefinition, _context: SigningContext): Promise<Signature[]> {
238
+ const jobs: Promise<Signature>[] = [];
239
+ for (const i of this.validatorIndices()) {
240
+ const v = this.ensureValidator(i);
241
+ for (const s of v.attesters) {
242
+ jobs.push(this.keystoreManager.signTypedData(s, typedData));
243
+ }
244
+ }
245
+ return await Promise.all(jobs);
246
+ }
247
+
248
+ /**
249
+ * Sign a message with all attester signers across validators.
250
+ * @param message 32-byte message (already hashed/padded as needed)
251
+ * @param _context Signing context (ignored by NodeKeystoreAdapter, used for HA protection)
252
+ * @returns Array of signatures in validator order, flattened
253
+ */
254
+ async signMessage(message: Buffer32, _context: SigningContext): Promise<Signature[]> {
255
+ const jobs: Promise<Signature>[] = [];
256
+ for (const i of this.validatorIndices()) {
257
+ const v = this.ensureValidator(i);
258
+ for (const s of v.attesters) {
259
+ jobs.push(this.keystoreManager.signMessage(s, message));
260
+ }
261
+ }
262
+ return await Promise.all(jobs);
263
+ }
264
+
265
+ /**
266
+ * Sign typed data with a signer identified by address (any role).
267
+ * Hydrates caches on-demand when the address is first seen.
268
+ * @param address Address to sign with
269
+ * @param typedData EIP-712 typed data
270
+ * @param _context Signing context (ignored by NodeKeystoreAdapter, used for HA protection)
271
+ * @returns Signature from the signer matching the address
272
+ * @throws Error when no signer exists for the address
273
+ */
274
+ async signTypedDataWithAddress(
275
+ address: EthAddress,
276
+ typedData: TypedDataDefinition,
277
+ _context: SigningContext,
278
+ ): Promise<Signature> {
279
+ const entry = this.addressIndex.get(NodeKeystoreAdapter.key(address));
280
+ if (entry) {
281
+ return await this.keystoreManager.signTypedData(entry.signer, typedData);
282
+ }
283
+
284
+ // If not in global index yet, lazily hydrate all validators once and retry
285
+ for (const i of this.validatorIndices()) {
286
+ this.ensureValidator(i);
287
+ }
288
+ const second = this.addressIndex.get(NodeKeystoreAdapter.key(address));
289
+ if (second) {
290
+ return await this.keystoreManager.signTypedData(second.signer, typedData);
291
+ }
292
+
293
+ throw new Error(`No signer found for address ${address.toString()}`);
294
+ }
295
+
296
+ /**
297
+ * Sign a message with a signer identified by address (any role).
298
+ * Hydrates caches on-demand when the address is first seen.
299
+ * @param address Address to sign with
300
+ * @param message 32-byte message
301
+ * @param _context Signing context (ignored by NodeKeystoreAdapter, used for HA protection)
302
+ * @returns Signature from the signer matching the address
303
+ * @throws Error when no signer exists for the address
304
+ */
305
+ async signMessageWithAddress(address: EthAddress, message: Buffer32, _context: SigningContext): Promise<Signature> {
306
+ const entry = this.addressIndex.get(NodeKeystoreAdapter.key(address));
307
+ if (entry) {
308
+ return await this.keystoreManager.signMessage(entry.signer, message);
309
+ }
310
+
311
+ for (const i of this.validatorIndices()) {
312
+ this.ensureValidator(i);
313
+ }
314
+ const second = this.addressIndex.get(NodeKeystoreAdapter.key(address));
315
+ if (second) {
316
+ return await this.keystoreManager.signMessage(second.signer, message);
317
+ }
318
+
319
+ throw new Error(`No signer found for address ${address.toString()}`);
320
+ }
321
+
322
+ /**
323
+ * Get all attester addresses across validators (alias of getAddresses).
324
+ */
325
+ getAttesterAddresses(): EthAddress[] {
326
+ return this.getAddresses();
327
+ }
328
+
329
+ /**
330
+ * Get the effective coinbase address for the validator that contains the given attester.
331
+ * @param attesterAddress Address of an attester belonging to the validator
332
+ * @returns Coinbase EthAddress
333
+ */
334
+ getCoinbaseAddress(attesterAddress: EthAddress): EthAddress {
335
+ const validatorIndex = this.findValidatorIndexForAttester(attesterAddress);
336
+ return this.keystoreManager.getCoinbaseAddress(validatorIndex, attesterAddress);
337
+ }
338
+
339
+ /**
340
+ * Get the publisher addresses for the validator that contains the given attester.
341
+ * @param attesterAddress Address of an attester belonging to the validator
342
+ * @returns Array of publisher addresses
343
+ */
344
+ getPublisherAddresses(attesterAddress: EthAddress): EthAddress[] {
345
+ const validatorIndex = this.findValidatorIndexForAttester(attesterAddress);
346
+ const v = this.ensureValidator(validatorIndex);
347
+ return v.publishers.map(s => s.address);
348
+ }
349
+
350
+ getAttestorForPublisher(publisherAddress: EthAddress): EthAddress {
351
+ const attestorAddresses = this.getAttesterAddresses();
352
+ for (const attestor of attestorAddresses) {
353
+ const publishers = this.getPublisherAddresses(attestor);
354
+ const found = publishers.some(publisher => publisher.equals(publisherAddress));
355
+ if (found) {
356
+ return attestor;
357
+ }
358
+ }
359
+ // Could not find an attestor for this publisher
360
+ throw new Error(`Failed to find attestor for publisher ${publisherAddress.toString()}`);
361
+ }
362
+
363
+ /**
364
+ * Get the fee recipient for the validator that contains the given attester.
365
+ * @param attesterAddress Address of an attester belonging to the validator
366
+ * @returns Fee recipient as AztecAddress
367
+ */
368
+ getFeeRecipient(attesterAddress: EthAddress): AztecAddress {
369
+ const validatorIndex = this.findValidatorIndexForAttester(attesterAddress);
370
+ return this.keystoreManager.getFeeRecipient(validatorIndex);
371
+ }
372
+
373
+ /**
374
+ * Get the effective remote signer configuration for the attester.
375
+ * Precedence: account-level override > validator-level override > file-level default.
376
+ * Returns undefined for local signers (private key / JSON-V3 / mnemonic).
377
+ * @param attesterAddress Address of an attester belonging to the validator
378
+ * @returns Effective remote signer configuration or undefined
379
+ */
380
+ getRemoteSignerConfig(attesterAddress: EthAddress): EthRemoteSignerConfig | undefined {
381
+ const validatorIndex = this.findValidatorIndexForAttester(attesterAddress);
382
+ return this.keystoreManager.getEffectiveRemoteSignerConfig(validatorIndex, attesterAddress);
383
+ }
384
+
385
+ /**
386
+ * Start the key store - no-op
387
+ */
388
+ start(): Promise<void> {
389
+ return Promise.resolve();
390
+ }
391
+
392
+ /**
393
+ * Stop the key store - no-op
394
+ */
395
+ stop(): Promise<void> {
396
+ return Promise.resolve();
397
+ }
398
+ }
@@ -0,0 +1,205 @@
1
+ import type { Buffer32 } from '@aztec/foundation/buffer';
2
+ import { normalizeSignature } from '@aztec/foundation/crypto/secp256k1-signer';
3
+ import { EthAddress } from '@aztec/foundation/eth-address';
4
+ import { Signature } from '@aztec/foundation/eth-signature';
5
+ import type { SigningContext } from '@aztec/validator-ha-signer/types';
6
+
7
+ import type { TypedDataDefinition } from 'viem';
8
+
9
+ import type { ValidatorKeyStore } from './interface.js';
10
+
11
+ /**
12
+ * Web3Signer Key Store
13
+ *
14
+ * An implementation of the Key store using Web3Signer remote signing service.
15
+ * This implementation uses the Web3Signer JSON-RPC API for secp256k1 signatures.
16
+ */
17
+ export class Web3SignerKeyStore implements ValidatorKeyStore {
18
+ constructor(
19
+ private addresses: EthAddress[],
20
+ private baseUrl: string,
21
+ ) {}
22
+
23
+ /**
24
+ * Get the address of a signer by index
25
+ *
26
+ * @param index - The index of the signer
27
+ * @returns the address
28
+ */
29
+ public getAddress(index: number): EthAddress {
30
+ if (index >= this.addresses.length) {
31
+ throw new Error(`Index ${index} is out of bounds.`);
32
+ }
33
+ return this.addresses[index];
34
+ }
35
+
36
+ /**
37
+ * Get all addresses
38
+ *
39
+ * @returns all addresses
40
+ */
41
+ public getAddresses(): EthAddress[] {
42
+ return this.addresses;
43
+ }
44
+
45
+ /**
46
+ * Sign EIP-712 typed data with all keystore addresses
47
+ * @param typedData - The complete EIP-712 typed data structure (domain, types, primaryType, message)
48
+ * @param _context - Signing context (ignored by Web3SignerKeyStore, used for HA protection)
49
+ * @return signatures
50
+ */
51
+ public signTypedData(typedData: TypedDataDefinition, _context: SigningContext): Promise<Signature[]> {
52
+ return Promise.all(this.addresses.map(address => this.makeJsonRpcSignTypedDataRequest(address, typedData)));
53
+ }
54
+
55
+ /**
56
+ * Sign EIP-712 typed data with a specific address
57
+ * @param address - The address of the signer to use
58
+ * @param typedData - The complete EIP-712 typed data structure (domain, types, primaryType, message)
59
+ * @param _context - Signing context (ignored by Web3SignerKeyStore, used for HA protection)
60
+ * @returns signature for the specified address
61
+ * @throws Error if the address is not found in the keystore or signing fails
62
+ */
63
+ public async signTypedDataWithAddress(
64
+ address: EthAddress,
65
+ typedData: TypedDataDefinition,
66
+ _context: SigningContext,
67
+ ): Promise<Signature> {
68
+ if (!this.addresses.some(addr => addr.equals(address))) {
69
+ throw new Error(`Address ${address.toString()} not found in keystore`);
70
+ }
71
+
72
+ return await this.makeJsonRpcSignTypedDataRequest(address, typedData);
73
+ }
74
+
75
+ /**
76
+ * Sign a message with all keystore addresses using EIP-191 prefix
77
+ *
78
+ * @param message - The message to sign
79
+ * @param _context - Signing context (ignored by Web3SignerKeyStore, used for HA protection)
80
+ * @return signatures
81
+ */
82
+ public signMessage(message: Buffer32, _context: SigningContext): Promise<Signature[]> {
83
+ return Promise.all(this.addresses.map(address => this.makeJsonRpcSignRequest(address, message)));
84
+ }
85
+
86
+ /**
87
+ * Sign a message with a specific address using EIP-191 prefix
88
+ * @param address - The address of the signer to use
89
+ * @param message - The message to sign
90
+ * @param _context - Signing context (ignored by Web3SignerKeyStore, used for HA protection)
91
+ * @returns signature for the specified address
92
+ * @throws Error if the address is not found in the keystore or signing fails
93
+ */
94
+ public async signMessageWithAddress(
95
+ address: EthAddress,
96
+ message: Buffer32,
97
+ _context: SigningContext,
98
+ ): Promise<Signature> {
99
+ if (!this.addresses.some(addr => addr.equals(address))) {
100
+ throw new Error(`Address ${address.toString()} not found in keystore`);
101
+ }
102
+ return await this.makeJsonRpcSignRequest(address, message);
103
+ }
104
+
105
+ /**
106
+ * Make a JSON-RPC sign request to Web3Signer using eth_sign
107
+ * @param address - The Ethereum address to sign with
108
+ * @param data - The data to sign
109
+ * @returns The signature
110
+ */
111
+ private async makeJsonRpcSignRequest(address: EthAddress, data: Buffer32): Promise<Signature> {
112
+ const url = this.baseUrl;
113
+
114
+ // Use JSON-RPC eth_sign method which automatically applies Ethereum message prefixing
115
+ const body = {
116
+ jsonrpc: '2.0',
117
+ method: 'eth_sign',
118
+ params: [
119
+ address.toString(), // Ethereum address as identifier
120
+ data.toString(), // Raw data to sign (eth_sign will apply Ethereum message prefix)
121
+ ],
122
+ id: 1,
123
+ };
124
+
125
+ const response = await fetch(url, {
126
+ method: 'POST',
127
+ headers: {
128
+ 'Content-Type': 'application/json',
129
+ },
130
+ body: JSON.stringify(body),
131
+ });
132
+
133
+ if (!response.ok) {
134
+ const errorText = await response.text();
135
+ throw new Error(`Web3Signer request failed: ${response.status} ${response.statusText} - ${errorText}`);
136
+ }
137
+
138
+ const result = await response.json();
139
+
140
+ // Handle JSON-RPC response format
141
+ if (result.error) {
142
+ throw new Error(`Web3Signer JSON-RPC error: ${result.error.code} - ${result.error.message}`);
143
+ }
144
+
145
+ if (!result.result) {
146
+ throw new Error('Invalid response from Web3Signer: no result found');
147
+ }
148
+
149
+ let signatureHex = result.result;
150
+
151
+ // Ensure the signature has the 0x prefix
152
+ if (!signatureHex.startsWith('0x')) {
153
+ signatureHex = '0x' + signatureHex;
154
+ }
155
+
156
+ // Parse the signature from the hex string
157
+ return normalizeSignature(Signature.fromString(signatureHex as `0x${string}`));
158
+ }
159
+
160
+ private async makeJsonRpcSignTypedDataRequest(
161
+ address: EthAddress,
162
+ typedData: TypedDataDefinition,
163
+ ): Promise<Signature> {
164
+ const url = this.baseUrl;
165
+
166
+ const body = {
167
+ jsonrpc: '2.0',
168
+ method: 'eth_signTypedData',
169
+ params: [address.toString(), JSON.stringify(typedData)],
170
+ id: 1,
171
+ };
172
+
173
+ const response = await fetch(url, {
174
+ method: 'POST',
175
+ headers: {
176
+ 'Content-Type': 'application/json',
177
+ },
178
+ body: JSON.stringify(body),
179
+ });
180
+
181
+ if (!response.ok) {
182
+ const errorText = await response.text();
183
+ throw new Error(`Web3Signer request failed: ${response.status} ${response.statusText} - ${errorText}`);
184
+ }
185
+
186
+ const result = await response.json();
187
+
188
+ if (result.error) {
189
+ throw new Error(`Web3Signer JSON-RPC error: ${result.error.code} - ${result.error.message}`);
190
+ }
191
+
192
+ if (!result.result) {
193
+ throw new Error('Invalid response from Web3Signer: no result found');
194
+ }
195
+
196
+ let signatureHex = result.result;
197
+
198
+ // Ensure the signature has the 0x prefix
199
+ if (!signatureHex.startsWith('0x')) {
200
+ signatureHex = '0x' + signatureHex;
201
+ }
202
+
203
+ return normalizeSignature(Signature.fromString(signatureHex as `0x${string}`));
204
+ }
205
+ }