@aztec/node-keystore 0.0.1-commit.24de95ac

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.
package/src/signer.ts ADDED
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Signer Interface and Implementations
3
+ *
4
+ * Common interface for different signing backends (local, remote, encrypted)
5
+ */
6
+ import type { EthSigner } from '@aztec/ethereum';
7
+ import { Buffer32 } from '@aztec/foundation/buffer';
8
+ import { Secp256k1Signer, randomBytes, toRecoveryBit } from '@aztec/foundation/crypto';
9
+ import type { EthAddress } from '@aztec/foundation/eth-address';
10
+ import { Signature, type ViemTransactionSignature } from '@aztec/foundation/eth-signature';
11
+ import { jsonStringify } from '@aztec/foundation/json-rpc';
12
+ import { withHexPrefix } from '@aztec/foundation/string';
13
+
14
+ import {
15
+ type TransactionSerializable,
16
+ type TypedDataDefinition,
17
+ hashTypedData,
18
+ keccak256,
19
+ parseTransaction,
20
+ serializeTransaction,
21
+ } from 'viem';
22
+
23
+ import type { EthRemoteSignerConfig } from './types.js';
24
+
25
+ /**
26
+ * Error thrown for remote signer HTTP or JSON-RPC failures
27
+ */
28
+ export class SignerError extends Error {
29
+ constructor(
30
+ message: string,
31
+ public method: string,
32
+ public url: string,
33
+ public statusCode?: number,
34
+ public errorCode?: number,
35
+ ) {
36
+ super(message);
37
+ this.name = 'SignerError';
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Local signer that holds an in-memory Secp256k1 private key.
43
+ */
44
+ export class LocalSigner implements EthSigner {
45
+ private readonly signer: Secp256k1Signer;
46
+
47
+ constructor(private privateKey: Buffer32) {
48
+ this.signer = new Secp256k1Signer(privateKey);
49
+ }
50
+
51
+ get address(): EthAddress {
52
+ return this.signer.address;
53
+ }
54
+
55
+ signMessage(message: Buffer32): Promise<Signature> {
56
+ return Promise.resolve(this.signer.signMessage(message));
57
+ }
58
+
59
+ signTypedData(typedData: TypedDataDefinition): Promise<Signature> {
60
+ const digest = hashTypedData(typedData);
61
+ return Promise.resolve(this.signer.sign(Buffer32.fromString(digest)));
62
+ }
63
+
64
+ signTransaction(transaction: TransactionSerializable): Promise<Signature> {
65
+ // Taken from viem's `signTransaction` implementation
66
+ const tx: TransactionSerializable =
67
+ transaction.type === 'eip4844'
68
+ ? {
69
+ ...transaction,
70
+ sidecars: false,
71
+ }
72
+ : transaction;
73
+ const serializedTx = serializeTransaction(tx);
74
+ const txHash = keccak256(serializedTx);
75
+ const sig = this.signer.sign(Buffer32.fromString(txHash.slice(2)));
76
+ return Promise.resolve(new Signature(sig.r, sig.s, toRecoveryBit(sig.v)));
77
+ }
78
+ }
79
+
80
+ // reference - https://docs.web3signer.consensys.io/reference/api/json-rpc#eth_signtransaction
81
+ type RemoteSignerTxObject = {
82
+ from: string;
83
+ to?: string | null;
84
+ gas?: string;
85
+ maxPriorityFeePerGas?: string;
86
+ maxFeePerGas?: string;
87
+ nonce?: string;
88
+ value?: string;
89
+ data?: string;
90
+
91
+ // EIP-4844 extension - https://github.com/Consensys/web3signer/pull/1096
92
+ maxFeePerBlobGas?: string;
93
+ blobVersionedHashes?: readonly string[];
94
+ blobs?: readonly string[];
95
+ };
96
+
97
+ /**
98
+ * Remote signer that proxies signing operations to a Web3Signer-compatible HTTP endpoint.
99
+ */
100
+ export class RemoteSigner implements EthSigner {
101
+ constructor(
102
+ public readonly address: EthAddress,
103
+ private readonly config: EthRemoteSignerConfig,
104
+ private fetch: typeof globalThis.fetch = globalThis.fetch,
105
+ ) {}
106
+
107
+ /**
108
+ * Validates that a web3signer is accessible and that the given addresses are available.
109
+ * @param remoteSignerUrl - The URL of the web3signer (can be string or EthRemoteSignerConfig)
110
+ * @param addresses - The addresses to check for availability
111
+ * @param fetch - Optional fetch implementation for testing
112
+ * @throws Error if the web3signer is not accessible or if any address is not available
113
+ */
114
+ static async validateAccess(
115
+ remoteSignerUrl: EthRemoteSignerConfig,
116
+ addresses: string[],
117
+ fetch: typeof globalThis.fetch = globalThis.fetch,
118
+ ): Promise<void> {
119
+ const url = typeof remoteSignerUrl === 'string' ? remoteSignerUrl : remoteSignerUrl.remoteSignerUrl;
120
+
121
+ try {
122
+ // Check if the web3signer is reachable by calling eth_accounts
123
+ const response = await fetch(url, {
124
+ method: 'POST',
125
+ headers: {
126
+ 'Content-Type': 'application/json',
127
+ },
128
+ body: JSON.stringify({
129
+ jsonrpc: '2.0',
130
+ method: 'eth_accounts',
131
+ params: [],
132
+ id: 1,
133
+ }),
134
+ });
135
+
136
+ if (!response.ok) {
137
+ const errorText = await response.text();
138
+ throw new SignerError(
139
+ `Web3Signer validation failed: ${response.status} ${response.statusText} - ${errorText}`,
140
+ 'eth_accounts',
141
+ url,
142
+ response.status,
143
+ );
144
+ }
145
+
146
+ const result = await response.json();
147
+
148
+ if (result.error) {
149
+ throw new SignerError(
150
+ `Web3Signer JSON-RPC error during validation: ${result.error.code} - ${result.error.message}`,
151
+ 'eth_accounts',
152
+ url,
153
+ 200,
154
+ result.error.code,
155
+ );
156
+ }
157
+
158
+ if (!result.result || !Array.isArray(result.result)) {
159
+ throw new Error('Invalid response from Web3Signer: expected array of accounts');
160
+ }
161
+
162
+ // Normalize addresses to lowercase for comparison
163
+ const availableAccounts: string[] = result.result.map((addr: string) => addr.toLowerCase());
164
+ const requestedAddresses = addresses.map(addr => addr.toLowerCase());
165
+
166
+ // Check if all requested addresses are available
167
+ const missingAddresses = requestedAddresses.filter(addr => !availableAccounts.includes(addr));
168
+
169
+ if (missingAddresses.length > 0) {
170
+ throw new Error(`The following addresses are not available in the web3signer: ${missingAddresses.join(', ')}`);
171
+ }
172
+ } catch (error: any) {
173
+ if (error instanceof SignerError) {
174
+ throw error;
175
+ }
176
+ if (error.code === 'ECONNREFUSED' || error.cause?.code === 'ECONNREFUSED') {
177
+ throw new Error(`Unable to connect to web3signer at ${url}. Please ensure it is running and accessible.`);
178
+ }
179
+ throw error;
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Sign a message using eth_sign via remote JSON-RPC.
185
+ */
186
+ async signMessage(message: Buffer32): Promise<Signature> {
187
+ return await this.makeJsonRpcSignRequest(message);
188
+ }
189
+
190
+ /**
191
+ * Sign typed data using eth_signTypedData_v4 via remote JSON-RPC.
192
+ */
193
+ async signTypedData(typedData: TypedDataDefinition): Promise<Signature> {
194
+ return await this.makeJsonRpcSignTypedDataRequest(typedData);
195
+ }
196
+
197
+ signTransaction(transaction: TransactionSerializable): Promise<Signature> {
198
+ return this.makeJsonRpcSignTransactionRequest(transaction);
199
+ }
200
+
201
+ /**
202
+ * Make a JSON-RPC sign request using eth_sign
203
+ */
204
+ /**
205
+ * Make a JSON-RPC eth_sign request.
206
+ */
207
+ private async makeJsonRpcSignRequest(data: Buffer32): Promise<Signature> {
208
+ let signatureHex = await this.makeJsonRpcRequest('eth_sign', this.address.toString(), data.toString());
209
+
210
+ if (typeof signatureHex !== 'string') {
211
+ throw new Error('Invalid signature');
212
+ }
213
+
214
+ if (!signatureHex.startsWith('0x')) {
215
+ signatureHex = '0x' + signatureHex;
216
+ }
217
+
218
+ return Signature.fromString(signatureHex as `0x${string}`);
219
+ }
220
+
221
+ /**
222
+ * Make a JSON-RPC eth_signTypedData_v4 request.
223
+ */
224
+ private async makeJsonRpcSignTypedDataRequest(typedData: TypedDataDefinition): Promise<Signature> {
225
+ let signatureHex = await this.makeJsonRpcRequest(
226
+ 'eth_signTypedData',
227
+ this.address.toString(),
228
+ jsonStringify(typedData),
229
+ );
230
+
231
+ if (typeof signatureHex !== 'string') {
232
+ throw new Error('Invalid signature');
233
+ }
234
+
235
+ if (!signatureHex.startsWith('0x')) {
236
+ signatureHex = '0x' + signatureHex;
237
+ }
238
+
239
+ return Signature.fromString(signatureHex as `0x${string}`);
240
+ }
241
+
242
+ /**
243
+ * Make a JSON-RPC eth_signTransaction request.
244
+ */
245
+ private async makeJsonRpcSignTransactionRequest(tx: TransactionSerializable): Promise<Signature> {
246
+ if (tx.type !== 'eip1559') {
247
+ throw new Error('This signer does not support tx type: ' + tx.type);
248
+ }
249
+
250
+ const txObject: RemoteSignerTxObject = {
251
+ from: this.address.toString(),
252
+ to: tx.to ?? null,
253
+ data: tx.data,
254
+ value: typeof tx.value !== 'undefined' ? withHexPrefix(tx.value.toString(16)) : undefined,
255
+ nonce: typeof tx.nonce !== 'undefined' ? withHexPrefix(tx.nonce.toString(16)) : undefined,
256
+ gas: typeof tx.gas !== 'undefined' ? withHexPrefix(tx.gas.toString(16)) : undefined,
257
+ maxFeePerGas: typeof tx.maxFeePerGas !== 'undefined' ? withHexPrefix(tx.maxFeePerGas.toString(16)) : undefined,
258
+ maxPriorityFeePerGas:
259
+ typeof tx.maxPriorityFeePerGas !== 'undefined'
260
+ ? withHexPrefix(tx.maxPriorityFeePerGas.toString(16))
261
+ : undefined,
262
+
263
+ // maxFeePerBlobGas:
264
+ // typeof tx.maxFeePerBlobGas !== 'undefined' ? withHexPrefix(tx.maxFeePerBlobGas.toString(16)) : undefined,
265
+ // blobVersionedHashes: tx.blobVersionedHashes,
266
+ // blobs: tx.blobs?.map(blob => (typeof blob === 'string' ? blob : bufferToHex(Buffer.from(blob)))),
267
+ };
268
+
269
+ let rawTxHex = await this.makeJsonRpcRequest('eth_signTransaction', txObject);
270
+
271
+ if (typeof rawTxHex !== 'string') {
272
+ throw new Error('Invalid signed tx');
273
+ }
274
+
275
+ if (!rawTxHex.startsWith('0x')) {
276
+ rawTxHex = '0x' + rawTxHex;
277
+ }
278
+
279
+ // we get back to whole signed tx. Deserialize it in order to read the signature
280
+ const parsedTxWithSignature = parseTransaction(rawTxHex);
281
+ if (
282
+ parsedTxWithSignature.r === undefined ||
283
+ parsedTxWithSignature.s === undefined ||
284
+ parsedTxWithSignature.v === undefined
285
+ ) {
286
+ throw new Error('Tx not signed by Web3Signer');
287
+ }
288
+
289
+ return Signature.fromViemTransactionSignature(parsedTxWithSignature as ViemTransactionSignature);
290
+ }
291
+
292
+ /**
293
+ * Sends a JSON-RPC request and returns its result
294
+ */
295
+ private async makeJsonRpcRequest(method: string, ...params: any[]): Promise<any> {
296
+ const url = this.getSignerUrl();
297
+ const id = this.generateId();
298
+
299
+ const response = await this.fetch(url, {
300
+ method: 'POST',
301
+ headers: {
302
+ 'Content-Type': 'application/json',
303
+ },
304
+ body: jsonStringify({ jsonrpc: '2.0', method, params, id }),
305
+ });
306
+
307
+ if (!response.ok) {
308
+ const errorText = await response.text();
309
+ throw new SignerError(
310
+ `Web3Signer request failed for ${method} at ${url}: ${response.status} ${response.statusText} - ${errorText}`,
311
+ method,
312
+ url,
313
+ response.status,
314
+ );
315
+ }
316
+
317
+ const result = await response.json();
318
+
319
+ if (result.error) {
320
+ throw new SignerError(
321
+ `Web3Signer JSON-RPC error for ${method} at ${url}: ${result.error.code} - ${result.error.message}`,
322
+ method,
323
+ url,
324
+ response.status,
325
+ result.error.code,
326
+ );
327
+ }
328
+
329
+ if (!result.result) {
330
+ throw new Error('Invalid response from Web3Signer: no result found');
331
+ }
332
+
333
+ return result.result;
334
+ }
335
+
336
+ /**
337
+ * Resolve the effective remote signer URL from config.
338
+ */
339
+ private getSignerUrl(): string {
340
+ if (typeof this.config === 'string') {
341
+ return this.config;
342
+ }
343
+ return this.config.remoteSignerUrl;
344
+ }
345
+
346
+ /**
347
+ * Generate an id to use for a JSON-RPC call
348
+ */
349
+ private generateId(): string {
350
+ return randomBytes(4).toString('hex');
351
+ }
352
+ }
package/src/types.ts ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * Keys and Addresses Configuration Types
3
+ *
4
+ * TypeScript definitions based on the specification for validator keystore files.
5
+ * These types define the JSON structure for configuring validators, provers, and
6
+ * their associated keys and addresses.
7
+ */
8
+ import type { EthAddress } from '@aztec/foundation/eth-address';
9
+ import type { Hex } from '@aztec/foundation/string';
10
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
11
+
12
+ /**
13
+ * An encrypted keystore file config points to a local file with an encrypted private key.
14
+ * The file may be in different formats:
15
+ * - JSON V3 format for ETH keys (Ethereum wallet standard)
16
+ * - EIP-2335 format for BLS keys (Ethereum 2.0 validator standard)
17
+ */
18
+ export type EncryptedKeyFileConfig = { path: string; password?: string };
19
+
20
+ /** A private key is a 32-byte 0x-prefixed hex */
21
+ export type EthPrivateKey = Hex<32>;
22
+
23
+ /** A BLS private key is a 32-byte 0x-prefixed hex */
24
+ export type BLSPrivateKey = Hex<32>;
25
+
26
+ /** URL type for remote signers */
27
+ export type Url = string;
28
+
29
+ /**
30
+ * A remote signer is configured as an URL to connect to, and optionally a client certificate to use for auth
31
+ */
32
+ export type EthRemoteSignerConfig =
33
+ | Url
34
+ | {
35
+ remoteSignerUrl: Url;
36
+ certPath?: string;
37
+ certPass?: string;
38
+ };
39
+
40
+ /**
41
+ * A remote signer account config is equal to the remote signer config, but requires an address to be specified.
42
+ * If only the address is set, then the default remote signer config from the parent config is used.
43
+ */
44
+ export type EthRemoteSignerAccount =
45
+ | EthAddress
46
+ | {
47
+ address: EthAddress;
48
+ remoteSignerUrl: Url;
49
+ certPath?: string;
50
+ certPass?: string;
51
+ };
52
+
53
+ /** An L1 account is a private key, a remote signer configuration, or an encrypted keystore file (JSON V3 format) */
54
+ export type EthAccount = EthPrivateKey | EthRemoteSignerAccount | EncryptedKeyFileConfig;
55
+
56
+ /** A mnemonic can be used to define a set of accounts */
57
+ export type MnemonicConfig = {
58
+ mnemonic: string;
59
+ addressIndex?: number;
60
+ accountIndex?: number;
61
+ addressCount?: number;
62
+ accountCount?: number;
63
+ };
64
+
65
+ /** One or more L1 accounts */
66
+ export type EthAccounts = EthAccount | EthAccount[] | MnemonicConfig;
67
+
68
+ export type ProverKeyStoreWithId = {
69
+ /** Address that identifies the prover. This address will receive the rewards. */
70
+ id: EthAddress;
71
+ /** One or more EOAs used for sending proof L1 txs. */
72
+ publisher: EthAccounts;
73
+ };
74
+
75
+ export type ProverKeyStore = ProverKeyStoreWithId | EthAccount;
76
+
77
+ /** A BLS account is either a private key, or an EIP-2335 encrypted keystore file */
78
+ export type BLSAccount = BLSPrivateKey | EncryptedKeyFileConfig;
79
+
80
+ /** An AttesterAccount is a combined EthAccount and optional BLSAccount */
81
+ export type AttesterAccount = { eth: EthAccount; bls?: BLSAccount } | EthAccount;
82
+
83
+ /** One or more attester accounts combining ETH and BLS keys */
84
+ export type AttesterAccounts = AttesterAccount | AttesterAccount[] | MnemonicConfig;
85
+
86
+ export type ValidatorKeyStore = {
87
+ /**
88
+ * One or more validator attester keys to handle in this configuration block.
89
+ * An attester address may only appear once across all configuration blocks across all keystore files.
90
+ */
91
+ attester: AttesterAccounts;
92
+ /**
93
+ * Coinbase address to use when proposing an L2 block as any of the validators in this configuration block.
94
+ * Falls back to the attester address if not set.
95
+ */
96
+ coinbase?: EthAddress;
97
+ /**
98
+ * One or more EOAs used for sending block proposal L1 txs for all validators in this configuration block.
99
+ * Falls back to the attester account if not set.
100
+ */
101
+ publisher?: EthAccounts;
102
+ /**
103
+ * Fee recipient address to use when proposing an L2 block as any of the validators in this configuration block.
104
+ */
105
+ feeRecipient: AztecAddress;
106
+ /**
107
+ * Default remote signer for all accounts in this block.
108
+ */
109
+ remoteSigner?: EthRemoteSignerConfig;
110
+ /**
111
+ * Used for automatically funding publisher accounts in this block.
112
+ */
113
+ fundingAccount?: EthAccount;
114
+ };
115
+
116
+ export type KeyStore = {
117
+ /** Schema version of this keystore file (initially 1). */
118
+ schemaVersion: number;
119
+ /** Validator configurations. */
120
+ validators?: ValidatorKeyStore[];
121
+ /** One or more accounts used for creating slash payloads on L1. Does not create slash payloads if not set. */
122
+ slasher?: EthAccounts;
123
+ /** Default config for the remote signer for all accounts in this file. */
124
+ remoteSigner?: EthRemoteSignerConfig;
125
+ /** Prover configuration. Only one prover configuration is allowed. */
126
+ prover?: ProverKeyStore;
127
+ /** Used for automatically funding publisher accounts if there is none defined in the corresponding ValidatorKeyStore*/
128
+ fundingAccount?: EthAccount;
129
+ };