@webevm/devnode 0.0.0 → 0.1.0
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/LICENSE +21 -0
- package/README.md +219 -2
- package/dist/accounts.d.ts +82 -0
- package/dist/accounts.d.ts.map +1 -0
- package/dist/accounts.js +129 -0
- package/dist/accounts.js.map +1 -0
- package/dist/allocs.d.ts +26 -0
- package/dist/allocs.d.ts.map +1 -0
- package/dist/allocs.js +99 -0
- package/dist/allocs.js.map +1 -0
- package/dist/dev-node.d.ts +63 -0
- package/dist/dev-node.d.ts.map +1 -0
- package/dist/dev-node.js +166 -0
- package/dist/dev-node.js.map +1 -0
- package/dist/eip712.d.ts +23 -0
- package/dist/eip712.d.ts.map +1 -0
- package/dist/eip712.js +333 -0
- package/dist/eip712.js.map +1 -0
- package/dist/impersonation.d.ts +20 -0
- package/dist/impersonation.d.ts.map +1 -0
- package/dist/impersonation.js +95 -0
- package/dist/impersonation.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/send.d.ts +20 -0
- package/dist/send.d.ts.map +1 -0
- package/dist/send.js +385 -0
- package/dist/send.js.map +1 -0
- package/dist/sign.d.ts +14 -0
- package/dist/sign.d.ts.map +1 -0
- package/dist/sign.js +155 -0
- package/dist/sign.js.map +1 -0
- package/dist/worker-host.d.ts +87 -0
- package/dist/worker-host.d.ts.map +1 -0
- package/dist/worker-host.js +112 -0
- package/dist/worker-host.js.map +1 -0
- package/package.json +81 -13
- package/src/accounts.ts +218 -0
- package/src/allocs.ts +134 -0
- package/src/dev-node.ts +220 -0
- package/src/eip712.ts +390 -0
- package/src/impersonation.ts +119 -0
- package/src/index.ts +25 -0
- package/src/send.ts +469 -0
- package/src/sign.ts +199 -0
- package/src/worker-host.ts +151 -0
- package/.npm-publish.log +0 -0
package/src/send.ts
ADDED
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* send.ts: `eth_sendTransaction` from a DEV ACCOUNT. Fill exactly what the
|
|
3
|
+
* request leaves out, sign with the account's key, submit, return the hash.
|
|
4
|
+
*
|
|
5
|
+
* THE FILLING matches the node's own `eth_fillTransaction`
|
|
6
|
+
* (`packages/webevm/src/node.ts`), through the node's PUBLIC methods only:
|
|
7
|
+
*
|
|
8
|
+
* - `nonce`: the PENDING nonce (`eth_getTransactionCount` at `pending`), so a
|
|
9
|
+
* send queued behind an unmined one (manual or interval mining) does not reuse
|
|
10
|
+
* its nonce;
|
|
11
|
+
* - `gas`: `eth_estimateGas` on the same request (its access list and
|
|
12
|
+
* authorization list included, which the node charges and applies);
|
|
13
|
+
* - fees: legacy `gasPrice` from `eth_gasPrice`; the EIP-1559 pair from the
|
|
14
|
+
* node's own `eth_fillTransaction`, because the base fee it adds to the
|
|
15
|
+
* priority fee is a node option no other public method reports as such (a
|
|
16
|
+
* block's `baseFeePerGas` can differ under a `blockEnv`). So the two cannot
|
|
17
|
+
* drift apart.
|
|
18
|
+
*
|
|
19
|
+
* UNLIKE `eth_fillTransaction`, NOTHING THE REQUEST NAMES IS DROPPED. The
|
|
20
|
+
* envelope follows the fields: type 4 for an `authorizationList`, type 0 for a
|
|
21
|
+
* `gasPrice` (type 1 with an `accessList` too), type 2 otherwise (carrying any
|
|
22
|
+
* `accessList`). An explicit `type` is honoured.
|
|
23
|
+
*
|
|
24
|
+
* THE SEND PATH follows the node's sender mode (ADR 0017): on `'trusted'`,
|
|
25
|
+
* `evm_sendRawTransactionAs(raw, from)` with the REAL signature, so no ecrecover
|
|
26
|
+
* runs and the chain's transactions still replay on any node (ADR 0002's
|
|
27
|
+
* portability caveat is about fabricated signatures only); on `'recover'`,
|
|
28
|
+
* `eth_sendRawTransaction(raw)`.
|
|
29
|
+
*
|
|
30
|
+
* ONE OPERATION, ONE QUEUE. Fill, sign and submit run as a single job on a
|
|
31
|
+
* queue per layer: two concurrent sends from one account would otherwise both
|
|
32
|
+
* read the same pending nonce before either is submitted. The node serialises
|
|
33
|
+
* its own requests (ADR 0012), not a sequence of them, so the layer orders its
|
|
34
|
+
* own sequences.
|
|
35
|
+
*
|
|
36
|
+
* DECISIONS made here (task `devnode-eth-send-transaction-from-dev-accounts`),
|
|
37
|
+
* each user-visible and reversible before 1.0:
|
|
38
|
+
*
|
|
39
|
+
* - AN UNKNOWN `from` IS REFUSED WITH `4100`, EIP-1193's "Unauthorized" ("the
|
|
40
|
+
* requested method and/or account has not been authorized"), the code wallets
|
|
41
|
+
* use for an account they hold no key for, and viem maps it to
|
|
42
|
+
* `UnauthorizedProviderError`. A missing or malformed `from` is `-32602`.
|
|
43
|
+
* Alternatives: `-32000` (a generic server error), or `-32602` for both, which
|
|
44
|
+
* would read as a malformed request when the request is well formed. The
|
|
45
|
+
* impersonation task extends the message, not the code: it names
|
|
46
|
+
* `hardhat_impersonateAccount` (or `anvil_impersonateAccount`) while the
|
|
47
|
+
* `impersonation` option is on, and the option itself while it is off.
|
|
48
|
+
* - A REQUEST THAT CANNOT BE SENT AS NAMED IS REFUSED WITH `-32602`, never
|
|
49
|
+
* trimmed into one that can: fields its type cannot carry (a `gasPrice` with
|
|
50
|
+
* EIP-1559 fees or with an `authorizationList`, an `accessList` on type 0, an
|
|
51
|
+
* `authorizationList` on anything but type 4), blob fields or type 3 (which
|
|
52
|
+
* this layer does not build), a `type` other than 0, 1, 2 or 4, `data` and
|
|
53
|
+
* `input` both present and different (as geth refuses them), and a `chainId`
|
|
54
|
+
* that is not the node's. `eth_fillTransaction` drops some of these instead;
|
|
55
|
+
* that is its documented difference, and the reason this does not reuse it.
|
|
56
|
+
* - SIGNING IS DETERMINISTIC (RFC 6979, no extra entropy), so the same request
|
|
57
|
+
* on the same state signs to the same bytes and the same hash.
|
|
58
|
+
* - THE SIGNING `Common` is the node's chain ID on Prague, the fork with every
|
|
59
|
+
* type this layer builds. The NODE's fork decides what is accepted: a type 4
|
|
60
|
+
* on Cancun is refused by the node in its own words, not by the signer.
|
|
61
|
+
*
|
|
62
|
+
* `eth_signTransaction` (task `devnode-signing-methods-and-eip-712`) is the
|
|
63
|
+
* same fill, the same types and the same refusals (each `-32602` and `4100`
|
|
64
|
+
* names `eth_signTransaction`), stopping before the submit. Its DECISIONS, each
|
|
65
|
+
* user-visible and reversible before 1.0:
|
|
66
|
+
*
|
|
67
|
+
* - IT RETURNS THE RAW SIGNED TRANSACTION AS A HEX STRING, as anvil does and as
|
|
68
|
+
* viem's `signTransaction` over a JSON-RPC account reads it. Alternative:
|
|
69
|
+
* geth's `{raw, tx}` object, which viem would hand back as an object.
|
|
70
|
+
* - IT RUNS ON THE SAME QUEUE AS THE SENDS, so its pending nonce counts every
|
|
71
|
+
* send queued before it. Two signs with no send between them read the same
|
|
72
|
+
* nonce: nothing was submitted, as on anvil.
|
|
73
|
+
* - Its `4100` names only the `accounts` remedy: impersonation never signs
|
|
74
|
+
* (ADR 0017).
|
|
75
|
+
*
|
|
76
|
+
* AN IMPERSONATED `from` (task `devnode-impersonation`, see
|
|
77
|
+
* ./impersonation.ts) is filled exactly as a dev account's is and given the
|
|
78
|
+
* FABRICATED signature of `fabricatedSignature` instead of a real one, then
|
|
79
|
+
* sent through `evm_sendRawTransactionAs` (the option requires a `'trusted'`
|
|
80
|
+
* node). A dev account that is also impersonated sends with its key: the key
|
|
81
|
+
* is looked up first. `eth_signTransaction` refuses an impersonated `from`
|
|
82
|
+
* with `4100`, since what it returns would be a signature that is not one.
|
|
83
|
+
*/
|
|
84
|
+
import {Common, Hardfork, Mainnet} from '@ethereumjs/common';
|
|
85
|
+
import {createTx, type TypedTxData} from '@ethereumjs/tx';
|
|
86
|
+
import {bytesToHex} from '@ethereumjs/util';
|
|
87
|
+
import {RpcError, type SlimNode} from 'webevm';
|
|
88
|
+
import type {DevAccount} from './accounts.js';
|
|
89
|
+
import type {Impersonation} from './impersonation.js';
|
|
90
|
+
import {
|
|
91
|
+
fabricatedSignature,
|
|
92
|
+
impersonatedNoKeyMessage,
|
|
93
|
+
} from './impersonation.js';
|
|
94
|
+
import {noKeyMessage} from './sign.js';
|
|
95
|
+
|
|
96
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
97
|
+
const HEX_QUANTITY = /^0x[0-9a-fA-F]+$/;
|
|
98
|
+
const HEX_DATA = /^0x([0-9a-fA-F]{2})*$/;
|
|
99
|
+
|
|
100
|
+
/** The fields that make a request an EIP-1559 one. */
|
|
101
|
+
const FEE_1559 = ['maxFeePerGas', 'maxPriorityFeePerGas'] as const;
|
|
102
|
+
/** EIP-4844's fields, which this layer does not build a transaction from. */
|
|
103
|
+
const BLOB_FIELDS = [
|
|
104
|
+
'blobVersionedHashes',
|
|
105
|
+
'maxFeePerBlobGas',
|
|
106
|
+
'blobs',
|
|
107
|
+
'sidecars',
|
|
108
|
+
] as const;
|
|
109
|
+
|
|
110
|
+
type Request = Record<string, unknown>;
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* A malformed request, thrown by the helpers below and turned into a `-32602`
|
|
114
|
+
* naming the method that was called (`eth_sendTransaction` or
|
|
115
|
+
* `eth_signTransaction`) where the request is built.
|
|
116
|
+
*/
|
|
117
|
+
class InvalidRequest extends Error {}
|
|
118
|
+
|
|
119
|
+
function invalid(message: string): never {
|
|
120
|
+
throw new InvalidRequest(message);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** A request's quantity as a bigint, or `undefined` when it is absent. */
|
|
124
|
+
function quantity(p: Request, field: string): bigint | undefined {
|
|
125
|
+
const value = p[field];
|
|
126
|
+
if (value == null) return undefined;
|
|
127
|
+
if (typeof value === 'string' && HEX_QUANTITY.test(value))
|
|
128
|
+
return BigInt(value);
|
|
129
|
+
if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0)
|
|
130
|
+
return BigInt(value);
|
|
131
|
+
if (typeof value === 'bigint' && value >= 0n) return value;
|
|
132
|
+
return invalid(
|
|
133
|
+
`\`${field}\` must be a hex quantity (received ${JSON.stringify(String(value))}).`,
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function present(p: Request, field: string): boolean {
|
|
138
|
+
return p[field] != null;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The envelope type the request names or implies, refusing a conflict. */
|
|
142
|
+
function envelopeType(p: Request): 0 | 1 | 2 | 4 {
|
|
143
|
+
for (const field of BLOB_FIELDS) {
|
|
144
|
+
if (present(p, field))
|
|
145
|
+
invalid(
|
|
146
|
+
`\`${field}\` is an EIP-4844 (type 3) field, and a dev account does not send type 3 transactions. Sign it yourself and use eth_sendRawTransaction.`,
|
|
147
|
+
);
|
|
148
|
+
}
|
|
149
|
+
const has1559 = FEE_1559.some((f) => present(p, f));
|
|
150
|
+
const explicit = quantity(p, 'type');
|
|
151
|
+
let type: 0 | 1 | 2 | 4;
|
|
152
|
+
if (explicit !== undefined) {
|
|
153
|
+
if (
|
|
154
|
+
explicit !== 0n &&
|
|
155
|
+
explicit !== 1n &&
|
|
156
|
+
explicit !== 2n &&
|
|
157
|
+
explicit !== 4n
|
|
158
|
+
)
|
|
159
|
+
invalid(
|
|
160
|
+
`type ${explicit} is not one a dev account sends: 0 (legacy), 1 (EIP-2930), 2 (EIP-1559) or 4 (EIP-7702).`,
|
|
161
|
+
);
|
|
162
|
+
type = Number(explicit) as 0 | 1 | 2 | 4;
|
|
163
|
+
} else if (present(p, 'authorizationList')) type = 4;
|
|
164
|
+
else if (present(p, 'gasPrice') && !has1559)
|
|
165
|
+
type = present(p, 'accessList') ? 1 : 0;
|
|
166
|
+
else type = 2;
|
|
167
|
+
|
|
168
|
+
const conflict = (field: string) =>
|
|
169
|
+
invalid(
|
|
170
|
+
`\`${field}\` cannot be carried by a type ${type} transaction, and a dev account's transaction carries every field it is given rather than dropping one. Remove it, or ${type === 0 || type === 1 ? 'remove `gasPrice` and pass EIP-1559 fees' : 'pick a type that carries it'}.`,
|
|
171
|
+
);
|
|
172
|
+
if (type === 0 || type === 1) {
|
|
173
|
+
for (const f of FEE_1559) if (present(p, f)) conflict(f);
|
|
174
|
+
if (present(p, 'authorizationList')) conflict('authorizationList');
|
|
175
|
+
if (type === 0 && present(p, 'accessList')) conflict('accessList');
|
|
176
|
+
} else {
|
|
177
|
+
if (present(p, 'gasPrice')) conflict('gasPrice');
|
|
178
|
+
if (type === 2 && present(p, 'authorizationList'))
|
|
179
|
+
conflict('authorizationList');
|
|
180
|
+
}
|
|
181
|
+
return type;
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** The request's call data, `data` or `input`, refusing two different ones. */
|
|
185
|
+
function callData(p: Request): string {
|
|
186
|
+
const {data, input} = p;
|
|
187
|
+
for (const [name, v] of [
|
|
188
|
+
['data', data],
|
|
189
|
+
['input', input],
|
|
190
|
+
] as const) {
|
|
191
|
+
if (v != null && (typeof v !== 'string' || !HEX_DATA.test(v)))
|
|
192
|
+
invalid(`\`${name}\` must be even-length 0x hex.`);
|
|
193
|
+
}
|
|
194
|
+
if (
|
|
195
|
+
typeof data === 'string' &&
|
|
196
|
+
typeof input === 'string' &&
|
|
197
|
+
data.toLowerCase() !== input.toLowerCase()
|
|
198
|
+
)
|
|
199
|
+
invalid(
|
|
200
|
+
'both `data` and `input` are set and they differ. Pass one, or the same bytes in both.',
|
|
201
|
+
);
|
|
202
|
+
return ((input ?? data ?? '0x') as string).toLowerCase();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** An authorization entry in the form `@ethereumjs/tx` reads, `v` accepted as yParity. */
|
|
206
|
+
function authorization(entry: unknown): Record<string, string> {
|
|
207
|
+
if (entry === null || typeof entry !== 'object')
|
|
208
|
+
invalid(
|
|
209
|
+
'each `authorizationList` entry must be {chainId, address, nonce, yParity, r, s}.',
|
|
210
|
+
);
|
|
211
|
+
const e = entry as Record<string, unknown>;
|
|
212
|
+
let yParity = e.yParity ?? e.v;
|
|
213
|
+
if (typeof yParity === 'string' && HEX_QUANTITY.test(yParity)) {
|
|
214
|
+
const parity = BigInt(yParity);
|
|
215
|
+
if (parity >= 27n) yParity = `0x${(parity - 27n).toString(16)}`;
|
|
216
|
+
}
|
|
217
|
+
const out: Record<string, string> = {};
|
|
218
|
+
for (const [field, value] of Object.entries({
|
|
219
|
+
chainId: e.chainId,
|
|
220
|
+
address: e.address,
|
|
221
|
+
nonce: e.nonce,
|
|
222
|
+
yParity,
|
|
223
|
+
r: e.r,
|
|
224
|
+
s: e.s,
|
|
225
|
+
})) {
|
|
226
|
+
if (typeof value !== 'string')
|
|
227
|
+
invalid(
|
|
228
|
+
`an \`authorizationList\` entry's \`${field}\` must be a hex string.`,
|
|
229
|
+
);
|
|
230
|
+
out[field] = value;
|
|
231
|
+
}
|
|
232
|
+
return out;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** The two transaction methods of the layer, sharing one queue. */
|
|
236
|
+
export interface TransactionMethods {
|
|
237
|
+
/** `eth_sendTransaction`: fill, sign, submit; resolves to the hash. */
|
|
238
|
+
sendTransaction(params: unknown): Promise<string>;
|
|
239
|
+
/** `eth_signTransaction`: fill and sign as `eth_sendTransaction` does; resolves to the raw signed transaction, unsent. */
|
|
240
|
+
signTransaction(params: unknown): Promise<string>;
|
|
241
|
+
/** Run `job` on the same queue, after every send and sign issued before it. */
|
|
242
|
+
inOrder<T>(job: () => T): Promise<T>;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
type TransactionMethod = 'eth_sendTransaction' | 'eth_signTransaction';
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The layer's `eth_sendTransaction` and `eth_signTransaction`: functions of the
|
|
249
|
+
* request's params, which run every send and every sign on ONE queue, signing
|
|
250
|
+
* with the given accounts' keys, or, for an address `impersonation` holds, a
|
|
251
|
+
* fabricated signature.
|
|
252
|
+
*/
|
|
253
|
+
export function createTransactionMethods(
|
|
254
|
+
node: SlimNode,
|
|
255
|
+
accounts: readonly DevAccount[],
|
|
256
|
+
impersonation: Impersonation,
|
|
257
|
+
): TransactionMethods {
|
|
258
|
+
const keys = new Map(accounts.map((a) => [a.address, a.privateKey]));
|
|
259
|
+
let common: Promise<{common: Common; chainId: bigint}> | undefined;
|
|
260
|
+
const signingCommon = () =>
|
|
261
|
+
(common ??= (async () => {
|
|
262
|
+
const chainId = BigInt(
|
|
263
|
+
(await node.request({method: 'eth_chainId'})) as string,
|
|
264
|
+
);
|
|
265
|
+
return {
|
|
266
|
+
chainId,
|
|
267
|
+
common: new Common({
|
|
268
|
+
chain: {...Mainnet, chainId: Number(chainId), name: 'webevm-devnode'},
|
|
269
|
+
hardfork: Hardfork.Prague,
|
|
270
|
+
}),
|
|
271
|
+
};
|
|
272
|
+
})().catch((e) => {
|
|
273
|
+
common = undefined;
|
|
274
|
+
throw e;
|
|
275
|
+
}));
|
|
276
|
+
|
|
277
|
+
/** Fill and sign; `-32602` for a malformed request, named by `method`. */
|
|
278
|
+
async function build(
|
|
279
|
+
params: unknown,
|
|
280
|
+
method: TransactionMethod,
|
|
281
|
+
): Promise<{raw: string; from: string}> {
|
|
282
|
+
try {
|
|
283
|
+
return await fillAndSign(params, method);
|
|
284
|
+
} catch (e) {
|
|
285
|
+
if (e instanceof InvalidRequest)
|
|
286
|
+
throw new RpcError(-32602, `${method}: ${e.message}`);
|
|
287
|
+
throw e;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function fillAndSign(
|
|
292
|
+
params: unknown,
|
|
293
|
+
method: TransactionMethod,
|
|
294
|
+
): Promise<{raw: string; from: string}> {
|
|
295
|
+
const p = (Array.isArray(params) ? params[0] : undefined) as unknown;
|
|
296
|
+
if (p === null || typeof p !== 'object' || Array.isArray(p))
|
|
297
|
+
invalid('expected one transaction request object as its parameter.');
|
|
298
|
+
const request = p as Request;
|
|
299
|
+
if (typeof request.from !== 'string' || !ADDRESS.test(request.from))
|
|
300
|
+
invalid(
|
|
301
|
+
'`from` must be the 20-byte hex address of the dev account to send from.',
|
|
302
|
+
);
|
|
303
|
+
const from = request.from.toLowerCase();
|
|
304
|
+
// The key first: a dev account that is also impersonated signs with it.
|
|
305
|
+
const privateKey = keys.get(from);
|
|
306
|
+
if (!privateKey) {
|
|
307
|
+
const impersonated = impersonation.addresses.has(from);
|
|
308
|
+
if (method === 'eth_signTransaction')
|
|
309
|
+
throw new RpcError(
|
|
310
|
+
4100,
|
|
311
|
+
impersonated
|
|
312
|
+
? impersonatedNoKeyMessage(method, from)
|
|
313
|
+
: noKeyMessage(method, from),
|
|
314
|
+
);
|
|
315
|
+
if (!impersonated)
|
|
316
|
+
throw new RpcError(
|
|
317
|
+
4100,
|
|
318
|
+
`eth_sendTransaction: ${from} is not a dev account, so @webevm/devnode holds no key to sign for it. ` +
|
|
319
|
+
`Configure its private key in the dev node's \`accounts\` option, or impersonate it: ` +
|
|
320
|
+
(impersonation.enabled
|
|
321
|
+
? `call hardhat_impersonateAccount (or anvil_impersonateAccount) with ["${from}"] first.`
|
|
322
|
+
: `turn on the dev node's \`impersonation\` option, then call hardhat_impersonateAccount (or anvil_impersonateAccount) with ["${from}"].`),
|
|
323
|
+
);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const type = envelopeType(request);
|
|
327
|
+
const data = callData(request);
|
|
328
|
+
const to = request.to == null ? undefined : request.to;
|
|
329
|
+
if (to !== undefined && (typeof to !== 'string' || !ADDRESS.test(to)))
|
|
330
|
+
invalid('`to` must be a 20-byte hex address, or absent to create.');
|
|
331
|
+
const {chainId, common} = await signingCommon();
|
|
332
|
+
const requestChainId = quantity(request, 'chainId');
|
|
333
|
+
if (requestChainId !== undefined && requestChainId !== chainId)
|
|
334
|
+
invalid(
|
|
335
|
+
`\`chainId\` ${requestChainId} is not this node's chain ID (${chainId}).`,
|
|
336
|
+
);
|
|
337
|
+
if (request.accessList != null && !Array.isArray(request.accessList))
|
|
338
|
+
invalid('`accessList` must be an array of {address, storageKeys}.');
|
|
339
|
+
if (
|
|
340
|
+
request.authorizationList != null &&
|
|
341
|
+
!Array.isArray(request.authorizationList)
|
|
342
|
+
)
|
|
343
|
+
invalid(
|
|
344
|
+
'`authorizationList` must be an array of {chainId, address, nonce, yParity, r, s}.',
|
|
345
|
+
);
|
|
346
|
+
// Validate every named quantity before any round trip.
|
|
347
|
+
const value = quantity(request, 'value') ?? 0n;
|
|
348
|
+
const named = {
|
|
349
|
+
nonce: quantity(request, 'nonce'),
|
|
350
|
+
gas: quantity(request, 'gas'),
|
|
351
|
+
gasPrice: quantity(request, 'gasPrice'),
|
|
352
|
+
maxFeePerGas: quantity(request, 'maxFeePerGas'),
|
|
353
|
+
maxPriorityFeePerGas: quantity(request, 'maxPriorityFeePerGas'),
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
const nonce =
|
|
357
|
+
named.nonce ??
|
|
358
|
+
BigInt(
|
|
359
|
+
(await node.request({
|
|
360
|
+
method: 'eth_getTransactionCount',
|
|
361
|
+
params: [from, 'pending'],
|
|
362
|
+
})) as string,
|
|
363
|
+
);
|
|
364
|
+
|
|
365
|
+
let gas = named.gas;
|
|
366
|
+
if (gas === undefined) {
|
|
367
|
+
// The same request, minus the `gas` being estimated.
|
|
368
|
+
const estimate: Request = {...request, from};
|
|
369
|
+
delete estimate.gas;
|
|
370
|
+
gas = BigInt(
|
|
371
|
+
(await node.request({
|
|
372
|
+
method: 'eth_estimateGas',
|
|
373
|
+
params: [estimate],
|
|
374
|
+
})) as string,
|
|
375
|
+
);
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
const txData: Record<string, unknown> = {
|
|
379
|
+
type,
|
|
380
|
+
nonce,
|
|
381
|
+
gasLimit: gas,
|
|
382
|
+
to,
|
|
383
|
+
value,
|
|
384
|
+
data,
|
|
385
|
+
};
|
|
386
|
+
if (type === 0 || type === 1) {
|
|
387
|
+
txData.gasPrice =
|
|
388
|
+
named.gasPrice ??
|
|
389
|
+
BigInt((await node.request({method: 'eth_gasPrice'})) as string);
|
|
390
|
+
} else {
|
|
391
|
+
let {maxFeePerGas, maxPriorityFeePerGas} = named;
|
|
392
|
+
if (maxFeePerGas === undefined || maxPriorityFeePerGas === undefined) {
|
|
393
|
+
// The node's own EIP-1559 filling, on a plain transfer whose nonce and
|
|
394
|
+
// gas are fixed so it neither reads the nonce nor estimates.
|
|
395
|
+
const probe: Request = {from, to: from, nonce: '0x0', gas: '0x5208'};
|
|
396
|
+
if (maxFeePerGas !== undefined)
|
|
397
|
+
probe.maxFeePerGas = `0x${maxFeePerGas.toString(16)}`;
|
|
398
|
+
if (maxPriorityFeePerGas !== undefined)
|
|
399
|
+
probe.maxPriorityFeePerGas = `0x${maxPriorityFeePerGas.toString(16)}`;
|
|
400
|
+
const filled = (await node.request({
|
|
401
|
+
method: 'eth_fillTransaction',
|
|
402
|
+
params: [probe],
|
|
403
|
+
})) as {tx: {maxFeePerGas: string; maxPriorityFeePerGas: string}};
|
|
404
|
+
maxFeePerGas ??= BigInt(filled.tx.maxFeePerGas);
|
|
405
|
+
maxPriorityFeePerGas ??= BigInt(filled.tx.maxPriorityFeePerGas);
|
|
406
|
+
}
|
|
407
|
+
txData.maxFeePerGas = maxFeePerGas;
|
|
408
|
+
txData.maxPriorityFeePerGas = maxPriorityFeePerGas;
|
|
409
|
+
}
|
|
410
|
+
if (type !== 0) {
|
|
411
|
+
txData.chainId = chainId;
|
|
412
|
+
txData.accessList = request.accessList ?? [];
|
|
413
|
+
}
|
|
414
|
+
if (type === 4) {
|
|
415
|
+
txData.authorizationList = (
|
|
416
|
+
(request.authorizationList ?? []) as unknown[]
|
|
417
|
+
).map(authorization);
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
try {
|
|
421
|
+
if (privateKey) {
|
|
422
|
+
const raw = bytesToHex(
|
|
423
|
+
createTx(txData as TypedTxData, {common})
|
|
424
|
+
.sign(privateKey, false)
|
|
425
|
+
.serialize(),
|
|
426
|
+
);
|
|
427
|
+
return {raw, from};
|
|
428
|
+
}
|
|
429
|
+
// Impersonated: the fabricated signature, y-parity 0 (EIP-155's
|
|
430
|
+
// `chainId * 2 + 35` on a legacy transaction).
|
|
431
|
+
const {r, s} = fabricatedSignature(from);
|
|
432
|
+
const v = type === 0 ? chainId * 2n + 35n : 0n;
|
|
433
|
+
const raw = bytesToHex(
|
|
434
|
+
createTx({...txData, v, r, s} as TypedTxData, {common}).serialize(),
|
|
435
|
+
);
|
|
436
|
+
return {raw, from};
|
|
437
|
+
} catch (e) {
|
|
438
|
+
return invalid(
|
|
439
|
+
`the transaction could not be built: ${(e as Error).message}`,
|
|
440
|
+
);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
async function send(params: unknown): Promise<string> {
|
|
445
|
+
const {raw, from} = await build(params, 'eth_sendTransaction');
|
|
446
|
+
return (await node.request(
|
|
447
|
+
node.senderMode === 'trusted'
|
|
448
|
+
? {method: 'evm_sendRawTransactionAs', params: [raw, from]}
|
|
449
|
+
: {method: 'eth_sendRawTransaction', params: [raw]},
|
|
450
|
+
)) as string;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// The queue: each job starts when the one before it has settled, whatever
|
|
454
|
+
// its outcome, so a refused one cannot stall the ones behind it. A sign
|
|
455
|
+
// runs on it too, so it reads the pending nonce AFTER every send queued
|
|
456
|
+
// before it has been submitted.
|
|
457
|
+
let queue: Promise<unknown> = Promise.resolve();
|
|
458
|
+
function enqueue<T>(run: () => Promise<T>): Promise<T> {
|
|
459
|
+
const job = queue.then(run);
|
|
460
|
+
queue = job.catch(() => undefined);
|
|
461
|
+
return job;
|
|
462
|
+
}
|
|
463
|
+
return {
|
|
464
|
+
sendTransaction: (params) => enqueue(() => send(params)),
|
|
465
|
+
signTransaction: (params) =>
|
|
466
|
+
enqueue(async () => (await build(params, 'eth_signTransaction')).raw),
|
|
467
|
+
inOrder: (job) => enqueue(async () => job()),
|
|
468
|
+
};
|
|
469
|
+
}
|
package/src/sign.ts
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* sign.ts: MESSAGE SIGNING by dev accounts: `personal_sign`, `eth_sign`
|
|
3
|
+
* (EIP-191 personal messages) and `eth_signTypedData_v4` (EIP-712, hashed by
|
|
4
|
+
* ./eip712.ts). `eth_signTransaction` is in ./send.ts, beside the send it fills
|
|
5
|
+
* and signs exactly as.
|
|
6
|
+
*
|
|
7
|
+
* Signing is `@noble/curves`' secp256k1 (`@ethereumjs/util` v10 exports no
|
|
8
|
+
* signing function; ADR 0017), on the digest itself (`prehash: false`),
|
|
9
|
+
* deterministic (RFC 6979, no extra entropy) and low-`s`, so the same request
|
|
10
|
+
* signs to the same bytes, as viem's local accounts sign. A signature is the
|
|
11
|
+
* 65 bytes `r ‖ s ‖ v` with `v` 27 or 28, as geth, anvil, Hardhat, MetaMask and
|
|
12
|
+
* viem return it.
|
|
13
|
+
*
|
|
14
|
+
* PARAMETER ORDERS, which are opposite:
|
|
15
|
+
*
|
|
16
|
+
* - `personal_sign [message, address]`, as MetaMask and geth take it (the
|
|
17
|
+
* order viem's `signMessage` sends);
|
|
18
|
+
* - `eth_sign [address, message]`, as geth takes it, and it signs the SAME
|
|
19
|
+
* EIP-191 digest: `keccak256("\x19Ethereum Signed Message:\n" ‖ len ‖ message)`.
|
|
20
|
+
* - `eth_signTypedData_v4 [address, typedData]`, `typedData` an object or its
|
|
21
|
+
* JSON text (viem sends the text).
|
|
22
|
+
*
|
|
23
|
+
* DECISIONS made here (task `devnode-signing-methods-and-eip-712`), each
|
|
24
|
+
* user-visible and reversible before 1.0:
|
|
25
|
+
*
|
|
26
|
+
* - AN ADDRESS WITH NO KEY IS REFUSED WITH `4100`, the code
|
|
27
|
+
* `eth_sendTransaction` uses for the same thing (see ./send.ts), naming only
|
|
28
|
+
* the `accounts` remedy: impersonation never signs (ADR 0017). An
|
|
29
|
+
* IMPERSONATED address with no key is refused with the same `4100`, saying so
|
|
30
|
+
* (`impersonatedNoKeyMessage` in ./impersonation.ts): a dev account that is
|
|
31
|
+
* also impersonated still signs with its key.
|
|
32
|
+
* - `personal_sign` TAKES A MESSAGE THAT IS NOT HEX AS UTF-8 TEXT, as MetaMask
|
|
33
|
+
* does (dapps pass a login message as plain text), and 0x hex as the bytes it
|
|
34
|
+
* spells. So a text message that happens to be valid 0x hex is signed as
|
|
35
|
+
* bytes, exactly as MetaMask signs it. `eth_sign` requires 0x hex, as geth
|
|
36
|
+
* does. Alternative: hex only for both (geth's and anvil's rule), which
|
|
37
|
+
* refuses the plain-text message a MetaMask-shaped dapp sends.
|
|
38
|
+
* - `eth_sign` SIGNS ARBITRARY DATA WITH THE EIP-191 PREFIX, as geth and anvil
|
|
39
|
+
* do (MetaMask's `eth_sign` signs a raw 32-byte hash, without the prefix, and
|
|
40
|
+
* is disabled by default there because a raw hash can be a transaction).
|
|
41
|
+
* This layer never signs a raw hash.
|
|
42
|
+
*/
|
|
43
|
+
import {secp256k1} from '@noble/curves/secp256k1.js';
|
|
44
|
+
import {keccak_256} from '@noble/hashes/sha3.js';
|
|
45
|
+
import {RpcError} from 'webevm';
|
|
46
|
+
import type {DevAccount} from './accounts.js';
|
|
47
|
+
import {hashTypedData} from './eip712.js';
|
|
48
|
+
import {impersonatedNoKeyMessage, type Impersonation} from './impersonation.js';
|
|
49
|
+
|
|
50
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
51
|
+
const HEX_DATA = /^0x([0-9a-fA-F]{2})*$/;
|
|
52
|
+
|
|
53
|
+
const encoder = new TextEncoder();
|
|
54
|
+
|
|
55
|
+
type SigningMethod =
|
|
56
|
+
| 'personal_sign'
|
|
57
|
+
| 'eth_sign'
|
|
58
|
+
| 'eth_signTypedData_v4'
|
|
59
|
+
| 'eth_signTransaction';
|
|
60
|
+
|
|
61
|
+
/** The message of a `4100` refusal: no key is held for `address`. */
|
|
62
|
+
export function noKeyMessage(method: SigningMethod, address: string): string {
|
|
63
|
+
return (
|
|
64
|
+
`${method}: ${address} is not a dev account, so @webevm/devnode holds no key to sign for it. ` +
|
|
65
|
+
`Configure its private key in the dev node's \`accounts\` option.`
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function invalid(method: SigningMethod, message: string): never {
|
|
70
|
+
throw new RpcError(-32602, `${method}: ${message}`);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function hexToBytes(hex: string): Uint8Array {
|
|
74
|
+
const out = new Uint8Array((hex.length - 2) / 2);
|
|
75
|
+
for (let i = 0; i < out.length; i++)
|
|
76
|
+
out[i] = parseInt(hex.slice(2 + 2 * i, 4 + 2 * i), 16);
|
|
77
|
+
return out;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function toHex(bytes: Uint8Array): string {
|
|
81
|
+
let s = '0x';
|
|
82
|
+
for (const b of bytes) s += b.toString(16).padStart(2, '0');
|
|
83
|
+
return s;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** EIP-191 version 0x45: the personal-message digest. */
|
|
87
|
+
function personalMessageHash(message: Uint8Array): Uint8Array {
|
|
88
|
+
const prefix = encoder.encode(
|
|
89
|
+
`\x19Ethereum Signed Message:\n${message.length}`,
|
|
90
|
+
);
|
|
91
|
+
const data = new Uint8Array(prefix.length + message.length);
|
|
92
|
+
data.set(prefix);
|
|
93
|
+
data.set(message, prefix.length);
|
|
94
|
+
return keccak_256(data);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** A 32-byte digest signed as `r ‖ s ‖ v`, `v` 27 or 28. */
|
|
98
|
+
function signDigest(digest: Uint8Array, privateKey: Uint8Array): string {
|
|
99
|
+
// 'recovered' is `recovery ‖ r ‖ s`.
|
|
100
|
+
const sig = secp256k1.sign(digest, privateKey, {
|
|
101
|
+
prehash: false,
|
|
102
|
+
lowS: true,
|
|
103
|
+
format: 'recovered',
|
|
104
|
+
});
|
|
105
|
+
const out = new Uint8Array(65);
|
|
106
|
+
out.set(sig.subarray(1, 65));
|
|
107
|
+
out[64] = 27 + sig[0]!;
|
|
108
|
+
return toHex(out);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The layer's message-signing methods, over the given accounts' keys. */
|
|
112
|
+
export interface MessageSigner {
|
|
113
|
+
personalSign(params: unknown): Promise<string>;
|
|
114
|
+
ethSign(params: unknown): Promise<string>;
|
|
115
|
+
signTypedDataV4(params: unknown): Promise<string>;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function createMessageSigner(
|
|
119
|
+
accounts: readonly DevAccount[],
|
|
120
|
+
impersonation: Impersonation,
|
|
121
|
+
): MessageSigner {
|
|
122
|
+
const keys = new Map(accounts.map((a) => [a.address, a.privateKey]));
|
|
123
|
+
|
|
124
|
+
function params(method: SigningMethod, raw: unknown): [unknown, unknown] {
|
|
125
|
+
if (!Array.isArray(raw) || raw.length < 2)
|
|
126
|
+
invalid(
|
|
127
|
+
method,
|
|
128
|
+
method === 'personal_sign'
|
|
129
|
+
? 'expected [message, address].'
|
|
130
|
+
: method === 'eth_sign'
|
|
131
|
+
? 'expected [address, message].'
|
|
132
|
+
: 'expected [address, typedData].',
|
|
133
|
+
);
|
|
134
|
+
return [raw[0], raw[1]];
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function keyFor(method: SigningMethod, address: unknown): Uint8Array {
|
|
138
|
+
if (typeof address !== 'string' || !ADDRESS.test(address))
|
|
139
|
+
invalid(
|
|
140
|
+
method,
|
|
141
|
+
`the address must be the 20-byte hex address of the dev account to sign with (received ${JSON.stringify(address)}).`,
|
|
142
|
+
);
|
|
143
|
+
const from = address.toLowerCase();
|
|
144
|
+
const key = keys.get(from);
|
|
145
|
+
if (!key)
|
|
146
|
+
throw new RpcError(
|
|
147
|
+
4100,
|
|
148
|
+
impersonation.addresses.has(from)
|
|
149
|
+
? impersonatedNoKeyMessage(method, from)
|
|
150
|
+
: noKeyMessage(method, from),
|
|
151
|
+
);
|
|
152
|
+
return key;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
return {
|
|
156
|
+
async personalSign(raw) {
|
|
157
|
+
const [message, address] = params('personal_sign', raw);
|
|
158
|
+
if (typeof message !== 'string')
|
|
159
|
+
invalid(
|
|
160
|
+
'personal_sign',
|
|
161
|
+
'the message must be a string, 0x hex or text.',
|
|
162
|
+
);
|
|
163
|
+
const key = keyFor('personal_sign', address);
|
|
164
|
+
const bytes = HEX_DATA.test(message)
|
|
165
|
+
? hexToBytes(message)
|
|
166
|
+
: encoder.encode(message);
|
|
167
|
+
return signDigest(personalMessageHash(bytes), key);
|
|
168
|
+
},
|
|
169
|
+
async ethSign(raw) {
|
|
170
|
+
const [address, message] = params('eth_sign', raw);
|
|
171
|
+
if (typeof message !== 'string' || !HEX_DATA.test(message))
|
|
172
|
+
invalid('eth_sign', 'the message must be even-length 0x hex.');
|
|
173
|
+
const key = keyFor('eth_sign', address);
|
|
174
|
+
return signDigest(personalMessageHash(hexToBytes(message)), key);
|
|
175
|
+
},
|
|
176
|
+
async signTypedDataV4(raw) {
|
|
177
|
+
const [address, data] = params('eth_signTypedData_v4', raw);
|
|
178
|
+
const key = keyFor('eth_signTypedData_v4', address);
|
|
179
|
+
let typed: unknown = data;
|
|
180
|
+
if (typeof data === 'string') {
|
|
181
|
+
try {
|
|
182
|
+
typed = JSON.parse(data);
|
|
183
|
+
} catch {
|
|
184
|
+
invalid(
|
|
185
|
+
'eth_signTypedData_v4',
|
|
186
|
+
'the typed data is a string that is not JSON.',
|
|
187
|
+
);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
let digest: Uint8Array;
|
|
191
|
+
try {
|
|
192
|
+
digest = hashTypedData(typed);
|
|
193
|
+
} catch (e) {
|
|
194
|
+
return invalid('eth_signTypedData_v4', (e as Error).message);
|
|
195
|
+
}
|
|
196
|
+
return signDigest(digest, key);
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
}
|