webevm 0.0.0 → 0.6.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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +693 -0
  3. package/dist/engine.d.ts +69 -0
  4. package/dist/engine.d.ts.map +1 -0
  5. package/dist/engine.js +269 -0
  6. package/dist/engine.js.map +1 -0
  7. package/dist/index.d.ts +12 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +21 -0
  10. package/dist/index.js.map +1 -0
  11. package/dist/intrinsic-gas.d.ts +149 -0
  12. package/dist/intrinsic-gas.d.ts.map +1 -0
  13. package/dist/intrinsic-gas.js +94 -0
  14. package/dist/intrinsic-gas.js.map +1 -0
  15. package/dist/node.d.ts +3 -0
  16. package/dist/node.d.ts.map +1 -0
  17. package/dist/node.js +1931 -0
  18. package/dist/node.js.map +1 -0
  19. package/dist/persistence.d.ts +22 -0
  20. package/dist/persistence.d.ts.map +1 -0
  21. package/dist/persistence.js +54 -0
  22. package/dist/persistence.js.map +1 -0
  23. package/dist/revm-state-store.d.ts +89 -0
  24. package/dist/revm-state-store.d.ts.map +1 -0
  25. package/dist/revm-state-store.js +394 -0
  26. package/dist/revm-state-store.js.map +1 -0
  27. package/dist/revm.d.ts +124 -0
  28. package/dist/revm.d.ts.map +1 -0
  29. package/dist/revm.js +657 -0
  30. package/dist/revm.js.map +1 -0
  31. package/dist/sender-recovery.d.ts +78 -0
  32. package/dist/sender-recovery.d.ts.map +1 -0
  33. package/dist/sender-recovery.js +53 -0
  34. package/dist/sender-recovery.js.map +1 -0
  35. package/dist/state-manager.d.ts +327 -0
  36. package/dist/state-manager.d.ts.map +1 -0
  37. package/dist/state-manager.js +439 -0
  38. package/dist/state-manager.js.map +1 -0
  39. package/dist/storage-keys.d.ts +21 -0
  40. package/dist/storage-keys.d.ts.map +1 -0
  41. package/dist/storage-keys.js +113 -0
  42. package/dist/storage-keys.js.map +1 -0
  43. package/dist/types.d.ts +696 -0
  44. package/dist/types.d.ts.map +1 -0
  45. package/dist/types.js +12 -0
  46. package/dist/types.js.map +1 -0
  47. package/dist/worker-client.d.ts +21 -0
  48. package/dist/worker-client.d.ts.map +1 -0
  49. package/dist/worker-client.js +77 -0
  50. package/dist/worker-client.js.map +1 -0
  51. package/dist/worker-entry.d.ts +32 -0
  52. package/dist/worker-entry.d.ts.map +1 -0
  53. package/dist/worker-entry.js +29 -0
  54. package/dist/worker-entry.js.map +1 -0
  55. package/dist/worker-host.d.ts +75 -0
  56. package/dist/worker-host.d.ts.map +1 -0
  57. package/dist/worker-host.js +188 -0
  58. package/dist/worker-host.js.map +1 -0
  59. package/package.json +90 -2
  60. package/src/engine.ts +300 -0
  61. package/src/index.ts +46 -0
  62. package/src/intrinsic-gas.ts +191 -0
  63. package/src/node.ts +2150 -0
  64. package/src/persistence.ts +80 -0
  65. package/src/revm-state-store.ts +455 -0
  66. package/src/revm.ts +809 -0
  67. package/src/sender-recovery.ts +142 -0
  68. package/src/state-manager.ts +531 -0
  69. package/src/storage-keys.ts +150 -0
  70. package/src/types.ts +717 -0
  71. package/src/worker-client.ts +112 -0
  72. package/src/worker-entry.ts +31 -0
  73. package/src/worker-host.ts +232 -0
package/src/node.ts ADDED
@@ -0,0 +1,2150 @@
1
+ /**
2
+ * node.ts — the execution-only EIP-1193 node.
3
+ *
4
+ * Design: sits BETWEEN bare `EVM.runCall` (no blocks/receipts/logs) and a full
5
+ * node (heavy). Runs on `@ethereumjs/vm` through the engine seam (see ./engine.ts)
6
+ * + a minimal mock blockchain with `SimpleStateManager` (plain Maps, NO trie, NO
7
+ * state-root) and NONE of the node / RPC / mempool / signing bloat.
8
+ *
9
+ * It is EXECUTION-ONLY:
10
+ * - NO account methods (eth_sendTransaction, eth_accounts, eth_sign,
11
+ * personal_x, wallet_x). Signing is client-side; node takes signed RAW txs.
12
+ * - Unsupported methods throw a real JSON-RPC method-not-found (-32601) — it
13
+ * NEVER fakes a success.
14
+ *
15
+ * BOTH halves of execution run on a swappable ENGINE (see ./engine.ts), defaulting
16
+ * to this VM's own `@ethereumjs/evm`: the READ path (`eth_call`,
17
+ * `eth_estimateGas`, `eth_fillTransaction`'s estimation) through `engine.call`,
18
+ * and the MINING path through `engine.transact`. What stays the node's either way:
19
+ * block construction, `cumulativeGasUsed`, receipt assembly, the RPC layer,
20
+ * transaction parsing and sender recovery.
21
+ *
22
+ * Transport-agnostic: just `request()` (async) + mine/dump/load. Knows nothing
23
+ * about Workers — see ./worker-entry.ts for the optional comlink wrapper.
24
+ *
25
+ * ONE THING AT A TIME. Every public entry point on the returned node —
26
+ * `request`, `mine`, `dumpState`, `loadState`, `getStateRoot` — runs through
27
+ * {@link SlimNode}'s serialisation point, so this node executes exactly one
28
+ * request at a time no matter how many are in flight. It is not an optimisation
29
+ * and it is not politeness: the node's state manager is a STACK of checkpoints
30
+ * shared by reads and transactions alike, `commit()` merges downward and
31
+ * `revert()` discards without either knowing who opened the level it acts on, so
32
+ * two overlapping executions destroy each other's writes. See the comment at
33
+ * `serialise` below and
34
+ * `docs/adr/0012-one-request-at-a-time-the-node-serialises-its-whole-public-surface.md`.
35
+ */
36
+ import {createVM, type VM} from '@ethereumjs/vm';
37
+ import {MerkleStateManager} from '@ethereumjs/statemanager';
38
+ import {OverlayStorageStateManager} from './state-manager.js';
39
+ import {Common, Mainnet, Hardfork} from '@ethereumjs/common';
40
+ import {createBlock, type Block} from '@ethereumjs/block';
41
+ import {createTxFromRLP, createTx, type TypedTransaction} from '@ethereumjs/tx';
42
+ import {
43
+ createAddressFromString,
44
+ createAccountFromRLP,
45
+ type Address,
46
+ Account,
47
+ hexToBytes as hexToBytesStrict,
48
+ bytesToHex,
49
+ bytesToBigInt,
50
+ bigIntToHex,
51
+ setLengthLeft,
52
+ bigIntToBytes,
53
+ } from '@ethereumjs/util';
54
+
55
+ // `@ethereumjs/util`'s hexToBytes is typed to require a `0x${string}` literal.
56
+ // Our hex comes from runtime sources (RPC params, serialized state) typed as
57
+ // plain `string`, so wrap it once with a runtime 0x-guard rather than casting at
58
+ // every call site. Throws on malformed input (same as the underlying fn).
59
+ function hexToBytes(s: string): Uint8Array {
60
+ return hexToBytesStrict((s.startsWith('0x') ? s : '0x' + s) as `0x${string}`);
61
+ }
62
+ import {keccak_256} from '@noble/hashes/sha3.js';
63
+ import {connectEngine, createEthereumjsEngine} from './engine.js';
64
+ // Sender derivation stays the node's on every engine; what an engine may lend it
65
+ // is the CURVE step. See ./sender-recovery.ts.
66
+ import {recoverSender} from './sender-recovery.js';
67
+ // The engine reports EXECUTION gas for a read and the node adds intrinsic gas on top;
68
+ // an engine that charges intrinsic gas itself (revm) subtracts the SAME formula,
69
+ // so it has exactly one home. See ./intrinsic-gas.ts.
70
+ import {
71
+ accessListGas,
72
+ intrinsicGas as intrinsicGasOf,
73
+ } from './intrinsic-gas.js';
74
+ import {
75
+ RpcError,
76
+ type NodeOptions,
77
+ type ReadCallResult,
78
+ type Engine,
79
+ type SenderMode,
80
+ type SlimNode,
81
+ type RequestArguments,
82
+ type SerializedState,
83
+ type SerializedBlock,
84
+ type SerializedReceipt,
85
+ type SerializedLog,
86
+ type SerializedTx,
87
+ } from './types.js';
88
+
89
+ const ZERO_HASH = '0x' + '00'.repeat(32);
90
+ const ZERO_ADDRESS = '0x' + '00'.repeat(20);
91
+ /**
92
+ * What a block's `logsBloom` reads as when it admits nothing: a block with no
93
+ * logs, and the defensive fallback for a stored header carrying none at all
94
+ * (`loadState` rebuilds one for an older dump, so this is reached only by a
95
+ * hand-built `SerializedBlock`). It is NO LONGER what EVERY block reports, which
96
+ * is what it was until 2026-08-11 — see `blockToRpc`.
97
+ */
98
+ const EMPTY_LOGS_BLOOM = '0x' + '00'.repeat(256);
99
+
100
+ /**
101
+ * How much gas an `eth_call` / `eth_estimateGas` that names none may burn. A
102
+ * node-wide CONSTANT, not the node's `blockGasLimit`: the two are the same
103
+ * number by default and are still decided apart, for the reasons recorded at its
104
+ * one use site in `evmCall`.
105
+ */
106
+ const DEFAULT_READ_BUDGET = 30_000_000n;
107
+
108
+ /**
109
+ * HOW MANY EXECUTIONS `eth_estimateGas`'s SEARCH MAY SPEND, after the two it
110
+ * always spends (the run at the upper bound, and the one that confirms the
111
+ * measured consumption).
112
+ *
113
+ * The bound is not a safety net for a search that might not terminate — the
114
+ * search below bisects a bigint window and always does — it is a COST CEILING.
115
+ * This node runs in a browser tab and every probe is a full execution of the
116
+ * request, so an estimate is the one read that can cost tens of them.
117
+ *
118
+ * WHY THIS MANY. Bisection alone closes any window this node can produce
119
+ * (30,000,000 gas at the widest) in 25 halvings, and the search reaches phase 2
120
+ * with a window far narrower than that — so 32 is enough to be EXACT for every
121
+ * transaction whose minimum limit is near what it consumes, which is every
122
+ * transaction that is not deliberately gas-sensitive. What can exhaust it is a
123
+ * contract that reads `GAS` and spends what it finds: there the search stops and
124
+ * returns the smallest limit it has PROVEN to succeed, an over-estimate, which is
125
+ * the safe direction (unused gas is not charged, while an under-estimate is a
126
+ * transaction that runs out of gas in the user's face).
127
+ */
128
+ const MAX_ESTIMATE_PROBES = 32n;
129
+
130
+ /**
131
+ * A standard `Error(string)` revert reason, if that is what these bytes are.
132
+ *
133
+ * Used to put WHY into the failure `eth_estimateGas` throws when a request
134
+ * cannot succeed at ANY gas limit. The raw bytes travel on the error's `data`
135
+ * as they always have (a client decodes them), but a human reading a console
136
+ * gets the sentence too.
137
+ *
138
+ * DEFENSIVE BY CONSTRUCTION: it decodes the one shape Solidity emits for
139
+ * `require(false, "...")` / `revert("...")` and answers `undefined` for
140
+ * everything else — a custom error, a bare `revert()`, a halt with no data,
141
+ * truncated bytes. Never throws: an estimate must not fail differently because
142
+ * a callee reverted in a shape this decoder does not know.
143
+ */
144
+ function revertReason(returnValue: Uint8Array): string | undefined {
145
+ // 4-byte selector of `Error(string)` + head (32) + length (32).
146
+ if (returnValue.length < 68) return undefined;
147
+ if (
148
+ returnValue[0] !== 0x08 ||
149
+ returnValue[1] !== 0xc3 ||
150
+ returnValue[2] !== 0x79 ||
151
+ returnValue[3] !== 0xa0
152
+ )
153
+ return undefined;
154
+ try {
155
+ // THE HEAD OFFSET IS CHECKED, not assumed. A `revert("...")` from any
156
+ // compiler puts the string's data immediately after the head, i.e. offset
157
+ // 0x20, and the length is then the word at [36,68). A legal-but-unusual
158
+ // encoding with a different offset would make that word something else
159
+ // entirely, and decoding it as a length yields a plausible-looking garbled
160
+ // sentence in an error message — worse than no sentence at all.
161
+ if (bytesToBigInt(returnValue.subarray(4, 36)) !== 32n) return undefined;
162
+ const length = Number(bytesToBigInt(returnValue.subarray(36, 68)));
163
+ if (length === 0 || 68 + length > returnValue.length) return undefined;
164
+ const text = new TextDecoder().decode(
165
+ returnValue.subarray(68, 68 + length),
166
+ );
167
+ return text.length > 0 ? text : undefined;
168
+ } catch {
169
+ return undefined;
170
+ }
171
+ }
172
+
173
+ function hex(b: Uint8Array): string {
174
+ return bytesToHex(b) as string;
175
+ }
176
+ function numHex(n: number | bigint): string {
177
+ return bigIntToHex(BigInt(n));
178
+ }
179
+ function txHashOf(tx: TypedTransaction): string {
180
+ return hex(tx.hash());
181
+ }
182
+
183
+ /**
184
+ * Intrinsic gas: 21000 base (+32000 create) + calldata (16/non-zero, 4/zero) +
185
+ * the EIP-3860 initcode word cost (2 gas per 32-byte word) for creates, from
186
+ * Shanghai on. An engine reports EXECUTION gas only (`runCall`'s
187
+ * `executionGasUsed` omits all of this), so the node adds it back: it is what a
188
+ * transaction pays before its first opcode, and therefore the part of a gas LIMIT
189
+ * that never reaches the frame. `eth_estimateGas` uses it as the LOWER BOUND of
190
+ * its search (see `estimateGas` below), not as the answer.
191
+ *
192
+ * `common` is threaded rather than captured, and it is THE node's `Common` — the
193
+ * same instance the engine is handed at `connect`, so the two callers of the
194
+ * shared formula cannot name different forks. See ./intrinsic-gas.ts.
195
+ */
196
+ function intrinsicGas(
197
+ dataHex: string,
198
+ isCreate: boolean,
199
+ common: Common,
200
+ ): bigint {
201
+ return intrinsicGasOf(
202
+ hexToBytes(dataHex.startsWith('0x') ? dataHex : '0x' + dataHex),
203
+ isCreate,
204
+ common,
205
+ );
206
+ }
207
+
208
+ /**
209
+ * WHAT A SENDER MUST BE ABLE TO PAY BEFORE THE TRANSACTION RUNS: its value plus
210
+ * its WHOLE gas limit at the MAXIMUM fee it offered.
211
+ *
212
+ * THE MAX FEE, NOT THE EFFECTIVE ONE, and that is the protocol's own line rather
213
+ * than a conservative choice: EIP-1559 states it as `assert balance >= gas_limit
214
+ * * max_fee_per_gas`, and both engines enforce exactly that — measured to the
215
+ * wei, on both, in
216
+ * `docs/spikes/replayed-and-invalid-transactions-are-rejected-as-the-nodes-own-errors/measurements.md`.
217
+ * A node checking the EFFECTIVE price instead would admit a window of
218
+ * transactions (`gasLimit * (maxFee - effective)` wide) that both engines then
219
+ * refuse in their own words.
220
+ *
221
+ * THIS IS NOT A SECOND IMPLEMENTATION OF THE FEE ARITHMETIC. What a transaction
222
+ * COSTS is the engine's and has exactly one implementation per engine (the
223
+ * `effectiveGasPrice` on the receipt is the engine's own number, never
224
+ * recomputed here — see ./engine.ts and `test/revm-fees.spec.ts`). This is an
225
+ * ADMISSION rule: what the sender must be able to cover for the transaction to be
226
+ * executable at all, which is the node's question because the node decides what
227
+ * goes into the blocks it builds.
228
+ *
229
+ * A TYPE-3 (BLOB) TRANSACTION IS UNDERSTATED HERE by its blob fee
230
+ * (`blobGas * maxFeePerBlobGas`), which is part of the same assertion in EIP-4844.
231
+ * That is the known type-3 gap this node documents rather than closes (the seam
232
+ * carries no blob fields at all), and the engines' own checks are the backstop:
233
+ * the node admits such a transaction and the engine refuses it in its own words.
234
+ */
235
+ function upfrontCost(tx: TypedTransaction): bigint {
236
+ const anyTx = tx as any;
237
+ const perGas: bigint =
238
+ anyTx.maxFeePerGas !== undefined && anyTx.maxFeePerGas !== null
239
+ ? anyTx.maxFeePerGas
240
+ : (anyTx.gasPrice as bigint);
241
+ return (anyTx.value ?? 0n) + tx.gasLimit * perGas;
242
+ }
243
+
244
+ interface StoredBlock {
245
+ block: Block;
246
+ header: SerializedBlock;
247
+ logs: SerializedLog[];
248
+ }
249
+
250
+ /**
251
+ * The no-op the node's serialisation chain passes in BOTH handler positions
252
+ * (`run.then(swallow, swallow)`), which is what keeps the chain alive across a
253
+ * FAILED request: `tail` must always be a promise that FULFILS, since a rejection
254
+ * left on it would reject every request queued behind the one that failed and turn
255
+ * one bad transaction into a dead node. It takes no arguments because it uses
256
+ * neither the value nor the reason; both are the caller's, and both have already
257
+ * been delivered to whoever awaited that request.
258
+ */
259
+ function swallow(): void {}
260
+
261
+ /**
262
+ * ONE SUBMITTED TRANSACTION, as the node carries it from `eth_sendRawTransaction*`
263
+ * (or the `evm_*As` cheats) to the block it is mined in: the parsed transaction,
264
+ * its wire bytes (`dumpState` and `eth_getTransactionByHash` report them) and
265
+ * WHO SENT IT.
266
+ *
267
+ * The sender is here — rather than being asked of `tx` at each of the three places
268
+ * that need it — because it is only sometimes recoverable FROM the transaction:
269
+ * `senderMode:'trusted'` states it instead (ADR 0002), and it may then differ from
270
+ * whatever the signature recovers to. `parseTx` decides it ONCE per transaction,
271
+ * and that one value becomes the engine's `TransactionRequest.sender`, the
272
+ * receipt's `from`, and the `from` on the stored transaction.
273
+ */
274
+ interface SubmittedTx {
275
+ readonly tx: TypedTransaction;
276
+ readonly raw: Uint8Array;
277
+ readonly sender: Address;
278
+ }
279
+
280
+ export async function createNode(options: NodeOptions = {}): Promise<SlimNode> {
281
+ const chainId = options.chainId ?? 31337;
282
+ const stateMode = options.stateMode ?? 'none';
283
+ const senderMode: SenderMode = options.senderMode ?? 'recover';
284
+ const miningConfig = options.miningConfig ?? {type: 'auto'};
285
+ const baseFeePerGas = options.baseFeePerGas ?? 1_000_000_000n;
286
+ const gasPrice = options.gasPrice ?? 1_000_000_000n;
287
+ const maxPriorityFeePerGas = options.maxPriorityFeePerGas ?? 1_000_000_000n;
288
+ const blockGasLimit = options.blockGasLimit ?? 30_000_000n;
289
+
290
+ const common = new Common({
291
+ chain: {...Mainnet, chainId, name: 'webevm'},
292
+ hardfork: Hardfork.Cancun,
293
+ customCrypto: {keccak256: (m: Uint8Array) => keccak_256(m)},
294
+ });
295
+
296
+ // State backing: SimpleStateManager (no trie, fast — default) or
297
+ // MerkleStateManager (real trie + state root — opt-in, slower, conformance-able).
298
+ // The 'none' manager is our SUBCLASS: storage is per-account with per-checkpoint
299
+ // OVERLAYS (upstream copies the whole flat storage map on every message frame),
300
+ // and it implements the `clearStorage(address)` that upstream ships as an empty
301
+ // no-op — without which a contract created at an address that already holds
302
+ // storage inherits it. See ./state-manager.ts.
303
+ const sm =
304
+ stateMode === 'trie'
305
+ ? new MerkleStateManager()
306
+ : new OverlayStorageStateManager();
307
+
308
+ /**
309
+ * THE SERIALISATION POINT: the tail of a promise chain that every public entry
310
+ * point queues its work onto, so this node runs exactly ONE piece of work at a
311
+ * time. It is declared HERE, beside `sm`, because the thing it protects is that
312
+ * object and nothing else.
313
+ *
314
+ * ## What was shared, and why it corrupts
315
+ *
316
+ * A state manager is a STACK of checkpoint levels. `checkpoint()` pushes a
317
+ * level, a write lands in the TOP one, `commit()` merges the top level into the
318
+ * one below and pops it, `revert()` pops it and throws it away. Neither
319
+ * `commit` nor `revert` knows WHO opened the level it is acting on — there is no
320
+ * handle, no owner and no identity — so the stack is only meaningful while a
321
+ * single execution owns it.
322
+ *
323
+ * Both halves of the node open levels on THIS one stack. `engine.transact`
324
+ * (`runTx`) checkpoints, executes and commits; the default engine's
325
+ * `engine.call` checkpoints and reverts, which is what makes an `eth_call` PURE
326
+ * and is a requirement of that EVM, not an option (see ./engine.ts). Both are
327
+ * `async` and `@ethereumjs/evm` yields to the microtask queue while it
328
+ * interprets, so before this existed a read arriving mid-transaction produced:
329
+ *
330
+ * ```
331
+ * tx checkpoint [base, tx]
332
+ * call checkpoint [base, tx, call] <- the read arrives mid-execution
333
+ * tx write -> lands in the TOP level, which is the CALL's
334
+ * tx commit -> merges that level down and pops it
335
+ * call revert -> pops the merged level: the transaction's write is GONE
336
+ * ```
337
+ *
338
+ * Measured through this node's own RPC surface: a whole transaction lost (a
339
+ * plain transfer loses the sender's NONCE, so every later transaction from that
340
+ * account is refused as "nonce too high"), state TORN at a message-frame
341
+ * boundary (the EVM checkpoints per frame, so the read's level can land between
342
+ * an inner frame's checkpoint and its commit, leaving a state no execution could
343
+ * produce), an `eth_call`'s OWN write committed rather than reverted, and —
344
+ * because this is not about reads — two overlapping TRANSACTIONS losing a write
345
+ * the same way, both reporting success and both holding a receipt.
346
+ *
347
+ * ## Why the lock is HERE rather than around `engine.call`
348
+ *
349
+ * Because write-versus-write interleaves too, so a lock inside the read path
350
+ * would fix half of it. And because it must be INSIDE the node: the Worker
351
+ * transport forwards straight to `node.request` and comlink delivers
352
+ * concurrently, so a lock in a transport protects only consumers who use that
353
+ * transport. It is per NODE, which is per STATE MANAGER by construction —
354
+ * `createNode` builds its own `sm` and takes no state manager option, and an
355
+ * injected engine binds to the first node it is given to and refuses a second.
356
+ *
357
+ * ## Why EVERY request and not only the executing ones
358
+ *
359
+ * A read that never touches the EVM never checkpoints and so can never corrupt
360
+ * anything — but it reads the live stack INCLUDING uncommitted levels, so it
361
+ * reports a state no block contains. Measured, with a single transfer in flight:
362
+ * `eth_getBalance` saw the sender DEBITED from tick 5 and
363
+ * `eth_getTransactionCount` saw the nonce ADVANCED from tick 6, while
364
+ * `eth_blockNumber` still said 0 — and that reading is exactly what an
365
+ * overlapping `eth_call` could then destroy. The node's own block/receipt maps
366
+ * are written per-transaction inside the mining loop too, so a mid-execution
367
+ * `eth_getTransactionReceipt` can name a `blockHash` no lookup resolves yet.
368
+ * The cost is real and is stated in the ADR: a cheap read issued during a
369
+ * 209 ms `eth_estimateGas` search used to answer in 0.1 ms and now waits for it.
370
+ * A per-method exemption list was rejected because it is a promise that has to
371
+ * be re-proven every time a method is added, by somebody who will not know that
372
+ * is what they are doing.
373
+ *
374
+ * ## The shape
375
+ *
376
+ * `tail` is ALWAYS a promise that fulfils — the assignment below swallows both
377
+ * outcomes — so a failing request cannot poison the chain and cannot stop the
378
+ * queue behind it. Nothing inside the node re-enters a serialised entry point
379
+ * (the internal `request`, `mineBlock`, `dumpState`, `loadState` and
380
+ * `currentStateRoot` are all called directly, and only the returned object's
381
+ * members are wrapped), so a single chain cannot deadlock against itself.
382
+ *
383
+ * ## The one way a CONSUMER can deadlock it, and why it is NOT detected
384
+ *
385
+ * Control leaves the node twice while the chain is held, and both times into a
386
+ * consumer's code. They are not the same risk:
387
+ *
388
+ * - an `onNewHead` callback is emitted WITHOUT being awaited, so a request it
389
+ * issues queues behind the current one and runs when the chain drains. That
390
+ * is the game-loop pattern (refetch on every head) and it is ALLOWED.
391
+ * - a `persistence.save()` hook IS awaited — so that the dump it is handed is a
392
+ * snapshot of a settled state and so that the request does not resolve before
393
+ * the write is durable — which means a hook that AWAITS a call back into the
394
+ * node waits for itself forever. That rule is documented, on
395
+ * `PersistenceAdapter.save` where an adapter is written, and enforced nowhere.
396
+ *
397
+ * IT IS DELIBERATELY NOT ENFORCED, and this is the interesting part. The obvious
398
+ * guard — a flag raised around the awaited hook, with `serialise` refusing while
399
+ * it is set — WAS BUILT AND REMOVED, because it cannot work. The flag is held
400
+ * across the hook's I/O, the `await` yields the event loop for that whole
401
+ * duration, and JavaScript offers no way (no `AsyncLocalStorage` in a browser) to
402
+ * tell a request issued by the hook's own stack from one issued by anybody else
403
+ * in that window. Measured on a 20 ms save: a plain `setInterval` poller that had
404
+ * never heard of persistence got four rejections, each telling it that IT had
405
+ * caused a deadlock. A false refusal with a confident wrong diagnosis is worse
406
+ * than the hang it replaces, and it fires for every consumer who has persistence
407
+ * and a poller, which is this package's main use. So the honest arrangement is
408
+ * the one below: everyone queues, and the one pathological hook is a documented
409
+ * rule rather than a guess dressed as a check. See ADR 0012.
410
+ */
411
+ let tail: Promise<void> = Promise.resolve();
412
+ function serialise<T>(job: () => Promise<T>): Promise<T> {
413
+ const run = tail.then(job);
414
+ tail = run.then(swallow, swallow);
415
+ return run;
416
+ }
417
+
418
+ // Touched-account set for the trie-mode dump (storage is read back via the
419
+ // trie's own dumpStorage). We record the addresses each tx touches at the NODE
420
+ // level (sender / to / created) rather than monkeypatching the state manager —
421
+ // MerkleStateManager's cache/flush path is sensitive to method wrapping.
422
+ const touchedAccounts = new Set<string>();
423
+
424
+ const ZERO_ROOT = ZERO_HASH;
425
+ async function currentStateRoot(): Promise<string> {
426
+ if (stateMode !== 'trie') return ZERO_ROOT;
427
+ const msm = sm as MerkleStateManager;
428
+ await msm.flush(); // write cached trie nodes before reading the root
429
+ return hex(await msm.getStateRoot());
430
+ }
431
+
432
+ // Flush cache into the trie after a direct state mutation (trie mode only) so
433
+ // the next getStateRoot() reflects it. No-op in 'none' mode (the Map IS state).
434
+ async function commitIfTrie(): Promise<void> {
435
+ if (stateMode !== 'trie') return;
436
+ await sm.checkpoint();
437
+ await sm.commit();
438
+ }
439
+
440
+ // Read-modify-write an account (creating an empty one if absent), used by the
441
+ // evm_set* cheat methods. Commits into the trie in trie mode.
442
+ async function mutateAccount(
443
+ addr: ReturnType<typeof createAddressFromString>,
444
+ fn: (acc: Account) => void,
445
+ ): Promise<void> {
446
+ const acc = (await sm.getAccount(addr)) ?? new Account();
447
+ fn(acc);
448
+ await sm.putAccount(addr, acc);
449
+ touchedAccounts.add(addr.toString());
450
+ await commitIfTrie();
451
+ }
452
+
453
+ // Minimal mock blockchain: `runTx` (inside the default engine) only needs
454
+ // getBlock (for BLOCKHASH) + shallowCopy. In 'none' mode we never compute a
455
+ // canonical state root.
456
+ const blockStore = new Map<number, StoredBlock>();
457
+ const blockByHash = new Map<string, number>();
458
+ const receipts = new Map<string, SerializedReceipt>();
459
+ const transactions = new Map<string, SerializedTx>();
460
+ let allLogs: SerializedLog[] = []; // flat, ordered log index for eth_getLogs
461
+
462
+ const mockBlockchain: any = {
463
+ getBlock: async (n: bigint | Uint8Array) => {
464
+ let num: number;
465
+ if (n instanceof Uint8Array) num = blockByHash.get(hex(n)) ?? 0;
466
+ else num = Number(n);
467
+ const sb = blockStore.get(num) ?? blockStore.get(latestNumber);
468
+ return sb!.block;
469
+ },
470
+ putBlock: async () => {},
471
+ shallowCopy() {
472
+ return mockBlockchain;
473
+ },
474
+ };
475
+
476
+ const vm: VM = await createVM({
477
+ common,
478
+ stateManager: sm,
479
+ blockchain: mockBlockchain,
480
+ });
481
+
482
+ // THE ENGINE: what `eth_call` / `eth_estimateGas` / `eth_fillTransaction` read
483
+ // on AND what the mining path executes transactions on. Default = this VM's own
484
+ // `@ethereumjs/evm`, on both halves. An injected engine is connected HERE, during
485
+ // construction, so an engine that cannot serve this node's configuration throws
486
+ // now rather than at the first opcode.
487
+ //
488
+ // `??` is the ONLY place the default is chosen, and it reads an ABSENT option,
489
+ // never a failure: an engine that was supplied and cannot come up fails the
490
+ // construction (see connectEngine). There is deliberately no path from
491
+ // "your engine did not work" to "here is a node on the default engine".
492
+ //
493
+ // ONE ENGINE, BOTH HALVES. There is no per-operation selection here and no
494
+ // capability check: an `Engine` implements `call` AND `transact`, `connectEngine`
495
+ // refuses one that does not, and `node.engine` therefore names the EVM that
496
+ // answered this node's reads and executed its transactions alike.
497
+ const engine: Engine =
498
+ options.engine ?? createEthereumjsEngine({vm, stateManager: sm});
499
+ await connectEngine(engine, {
500
+ stateManager: sm,
501
+ common,
502
+ stateMode,
503
+ // Block hashes for BLOCKHASH, read LIVE (no block exists yet at this point)
504
+ // and SYNCHRONOUSLY, because an engine answers BLOCKHASH mid-opcode.
505
+ getBlockHash: (blockNumber: bigint) => {
506
+ const sb = blockStore.get(Number(blockNumber));
507
+ return sb ? hexToBytes(sb.header.hash as `0x${string}`) : undefined;
508
+ },
509
+ });
510
+
511
+ // THE ENGINE'S secp256k1, IF IT BROUGHT ONE. Read ONCE, after `connect`, so a
512
+ // transaction never pays a property lookup and — more to the point — so which
513
+ // implementation recovers this node's senders is fixed for the node's lifetime
514
+ // rather than able to change under it. `undefined` means the node recovers the
515
+ // way it always did (`tx.getSenderAddress()`); it is NOT filled in with a
516
+ // default, because the fallback IS `@ethereumjs/tx`'s own recovery and wrapping
517
+ // it as an engine method would only add a layer. See ./sender-recovery.ts.
518
+ const engineEcrecover =
519
+ typeof engine.ecrecover === 'function'
520
+ ? engine.ecrecover.bind(engine)
521
+ : undefined;
522
+
523
+ let latestNumber = 0;
524
+ let parentHash = hexToBytes(ZERO_HASH);
525
+
526
+ // Initial balances FIRST (so the genesis state root, in trie mode, reflects them).
527
+ if (options.initialBalances) {
528
+ for (const [addr, bal] of Object.entries(options.initialBalances)) {
529
+ await sm.putAccount(createAddressFromString(addr), new Account(0n, bal));
530
+ touchedAccounts.add(createAddressFromString(addr).toString());
531
+ }
532
+ }
533
+ // Full genesis pre-state (balance/nonce/code/storage) — e.g. a GeneralStateTest
534
+ // `pre` section. Applied before block 0 so the trie-mode genesis root reflects
535
+ // it and a post-tx getStateRoot() can be compared to the fixture's hash.
536
+ if (options.initialState) {
537
+ for (const [addr, acc] of Object.entries(options.initialState)) {
538
+ const address = createAddressFromString(addr);
539
+ await sm.putAccount(
540
+ address,
541
+ new Account(acc.nonce ?? 0n, acc.balance ?? 0n),
542
+ );
543
+ if (acc.code && acc.code !== '0x')
544
+ await sm.putCode(address, hexToBytes(acc.code));
545
+ for (const [slot, val] of Object.entries(acc.storage ?? {})) {
546
+ await sm.putStorage(
547
+ address,
548
+ setLengthLeft(bigIntToBytes(BigInt(slot)), 32),
549
+ hexToBytes(val),
550
+ );
551
+ }
552
+ touchedAccounts.add(address.toString());
553
+ }
554
+ // Commit the cache into the trie so the genesis root is correct in trie mode.
555
+ if (stateMode === 'trie') {
556
+ await sm.checkpoint();
557
+ await sm.commit();
558
+ }
559
+ }
560
+
561
+ const blockEnv = options.blockEnv;
562
+
563
+ /**
564
+ * THE GAS LIMIT OF EVERY BLOCK THIS NODE BUILDS, named once so that the block
565
+ * builder and the check that refuses a transaction too large for it cannot
566
+ * drift apart. `blockEnv.gasLimit` is the explicit per-block statement and
567
+ * `blockGasLimit` the node-wide one, in that order, which is the precedence the
568
+ * header below uses, because they are the same number.
569
+ *
570
+ * IT IS A REAL LIMIT, NOT A FORMALITY. The node used to hand `@ethereumjs/vm`
571
+ * a `skipBlockGasLimitValidation`, so a transaction asking for more gas than
572
+ * the block had was mined anyway, against a limit the block did not have, and
573
+ * only on that engine (revm expresses the same relaxation as a simulation
574
+ * switch and refuses to combine any of them with committing, so it rejected the
575
+ * very same transaction with `CallerGasLimitMoreThanBlock`). The flag is gone.
576
+ * A consumer who wants enormous gas limits raises `blockGasLimit`, which makes
577
+ * the permissiveness a VISIBLE property of the block that both engines honour
578
+ * by construction, and an honest one, since `GASLIMIT` then reports that same
579
+ * number to a contract.
580
+ */
581
+ const minedBlockGasLimit = blockEnv?.gasLimit ?? blockGasLimit;
582
+
583
+ // Genesis block.
584
+ //
585
+ // IT TAKES `blockEnv`'s COINBASE AND PREVRANDAO, and nothing else from it. Those
586
+ // two describe the environment this CHAIN runs under, so a block 0 reporting a
587
+ // zero miner while every block after it reports the configured one would be the
588
+ // same RPC-vs-EVM disagreement the fields are stored to remove, one block wide.
589
+ // `number`, `timestamp` and `gasLimit` stay the node's own: genesis IS block 0,
590
+ // and `blockEnv.number` places a MINED block rather than renumbering the chain's
591
+ // genesis (`minedBlockGasLimit` above is likewise the MINED block's limit).
592
+ const genesis = createBlock(
593
+ {
594
+ header: {
595
+ number: 0n,
596
+ gasLimit: blockGasLimit,
597
+ baseFeePerGas,
598
+ timestamp: BigInt(Math.floor(Date.now() / 1000)),
599
+ ...(blockEnv?.coinbase
600
+ ? {coinbase: createAddressFromString(blockEnv.coinbase)}
601
+ : {}),
602
+ difficulty: 0n,
603
+ ...(blockEnv?.prevRandao
604
+ ? {mixHash: hexToBytes(blockEnv.prevRandao)}
605
+ : {}),
606
+ },
607
+ },
608
+ {common},
609
+ );
610
+ storeBlock(genesis, [], [], await currentStateRoot());
611
+
612
+ // Pending raw txs awaiting the next mined block (manual/interval modes). Each
613
+ // carries its SENDER, decided once at parse time by `parseTx`: the node derives
614
+ // the sender (or is told it), never the engine.
615
+ const pending: SubmittedTx[] = [];
616
+
617
+ // newHeads subscribers.
618
+ const headSubs = new Set<(h: {number: number; hash: string}) => void>();
619
+
620
+ // THE INTERVAL TIMER IS ARMED AT THE BOTTOM OF THIS FUNCTION, not here, at the
621
+ // `miningConfig.type === 'interval'` block just above the `return`. The reason
622
+ // is ordering: a timer armed at this point can fire while the
623
+ // REST OF CONSTRUCTION is still running, and the construction-time
624
+ // `loadState(saved)` that the persistence option performs is deliberately not
625
+ // serialised (nothing can reach the node yet, because it has not been returned).
626
+ // Those two together are the one interleaving the serialisation point does not
627
+ // cover, so the timer starts after the node is fully built instead.
628
+ let intervalTimer: ReturnType<typeof setInterval> | undefined;
629
+
630
+ /**
631
+ * THE BLOCK'S LOGS BLOOM: the OR of its receipts' own blooms, which is what a
632
+ * block bloom IS. Derived here rather than carried out of the mining loop so
633
+ * that `loadState` can rebuild it for a dump written before `SerializedBlock`
634
+ * had the field — same function, same answer, both sides of a round trip.
635
+ *
636
+ * IT IS NOT READ OFF `block.header.logsBloom`, unlike the coinbase and the
637
+ * mixHash beside it in `storeBlock`: the header is built (and frozen) BEFORE the
638
+ * block's transactions execute, so the only truthful bloom is this one.
639
+ */
640
+ function bloomOfReceipts(txHashes: string[]): string {
641
+ const acc = new Uint8Array(256);
642
+ for (const h of txHashes) {
643
+ const r = receipts.get(h);
644
+ if (!r) continue;
645
+ const bits = hexToBytes(r.logsBloom);
646
+ for (let i = 0; i < acc.length && i < bits.length; i++) acc[i] |= bits[i];
647
+ }
648
+ return hex(acc);
649
+ }
650
+
651
+ function storeBlock(
652
+ block: Block,
653
+ txHashes: string[],
654
+ logs: SerializedLog[],
655
+ stateRoot: string,
656
+ ) {
657
+ const number = Number(block.header.number);
658
+ const hash = hex(block.hash());
659
+ const header: SerializedBlock = {
660
+ number,
661
+ hash,
662
+ parentHash: hex(block.header.parentHash),
663
+ timestamp: Number(block.header.timestamp),
664
+ gasUsed: numHex(block.header.gasUsed),
665
+ gasLimit: numHex(block.header.gasLimit),
666
+ baseFeePerGas: numHex(block.header.baseFeePerGas ?? baseFeePerGas),
667
+ stateRoot,
668
+ // THE BLOCK'S OWN COINBASE AND MIXHASH, PERSISTED. They are read off the
669
+ // `Block` the EVM just ran — not off `blockEnv` — so "what the RPC reports"
670
+ // and "what COINBASE / PREVRANDAO returned" are one value with one source,
671
+ // and they are stored HERE because `loadState` rebuilds the block from this
672
+ // record: a reader that went to `sb.block` would answer correctly until a
673
+ // reload and zero afterwards.
674
+ miner: block.header.coinbase.toString(),
675
+ mixHash: hex(block.header.mixHash),
676
+ logsBloom: bloomOfReceipts(txHashes),
677
+ transactions: txHashes,
678
+ logsCount: logs.length,
679
+ };
680
+ blockStore.set(number, {block, header, logs});
681
+ blockByHash.set(hash, number);
682
+ latestNumber = number;
683
+ parentHash = block.hash();
684
+ }
685
+
686
+ async function executeAndMine(
687
+ txs: SubmittedTx[],
688
+ ): Promise<{blockNumber: number; blockHash: string; txHashes: string[]}> {
689
+ const number = blockEnv?.number ?? BigInt(latestNumber + 1);
690
+ const blockBaseFee = blockEnv?.baseFeePerGas ?? baseFeePerGas;
691
+ const block = createBlock(
692
+ {
693
+ header: {
694
+ number,
695
+ gasLimit: minedBlockGasLimit,
696
+ baseFeePerGas: blockBaseFee,
697
+ parentHash,
698
+ timestamp:
699
+ blockEnv?.timestamp ?? BigInt(Math.floor(Date.now() / 1000)),
700
+ ...(blockEnv?.coinbase
701
+ ? {coinbase: createAddressFromString(blockEnv.coinbase)}
702
+ : {}),
703
+ // post-Merge: difficulty must be 0; prevRandao lives in mixHash.
704
+ difficulty: 0n,
705
+ ...(blockEnv?.prevRandao
706
+ ? {mixHash: hexToBytes(blockEnv.prevRandao)}
707
+ : {}),
708
+ },
709
+ },
710
+ {common},
711
+ );
712
+ const blockHash = hex(block.hash());
713
+ const blockNumber = Number(number);
714
+
715
+ const txHashes: string[] = [];
716
+ const blockLogs: SerializedLog[] = [];
717
+ let cumulativeGasUsed = 0n;
718
+ let txIndex = 0;
719
+
720
+ for (const {tx, raw, sender} of txs) {
721
+ // THE MINING PATH GOES THROUGH THE ENGINE. What comes back is the neutral
722
+ // `TransactionResult` — everything a receipt needs from an EVM and nothing
723
+ // else — so every line below is the NODE's own half: the block it landed in,
724
+ // the running `cumulativeGasUsed`, log positions, and the receipt itself.
725
+ // THE SENDER IS PASSED, NOT LEFT TO BE FOUND. It is the node's own value
726
+ // (recovered, or claimed in `senderMode:'trusted'`), and the receipt's `from`
727
+ // below is the SAME value — so "who the engine executed as" and "who the
728
+ // receipt names" cannot drift apart by engine.
729
+ //
730
+ // ...AND WHETHER IT MAY SEND IT AT ALL IS ANSWERED FIRST, HERE, against the
731
+ // state this transaction is about to run on and in the node's own words, so
732
+ // that a replayed, unaffordable or unreachable-nonce transaction is refused
733
+ // identically on every engine instead of in whichever vocabulary the
734
+ // installed one happens to speak. Nothing has been committed for this
735
+ // transaction when it throws: no receipt is built, no log is recorded, and
736
+ // the block below is never stored.
737
+ await refuseIfSenderCannotSend(tx, sender);
738
+ const res = await engine.transact({tx, sender, block});
739
+ cumulativeGasUsed += res.gasUsed;
740
+ const h = txHashOf(tx);
741
+ const from = sender.toString();
742
+ const to = (tx as any).to ? (tx as any).to.toString() : null;
743
+ const created = res.createdAddress ? hex(res.createdAddress) : null;
744
+ // Track touched accounts for the trie-mode dump (sender, recipient, created,
745
+ // and any account that emitted a log — that set covers what changed).
746
+ touchedAccounts.add(from);
747
+ if (to) touchedAccounts.add(to);
748
+ if (created) touchedAccounts.add(created);
749
+ for (const log of res.logs) touchedAccounts.add(hex(log.address));
750
+
751
+ const rcptLogs: SerializedLog[] = res.logs.map((log, i) => {
752
+ const sl: SerializedLog = {
753
+ address: hex(log.address),
754
+ topics: log.topics.map((t) => hex(t)),
755
+ data: hex(log.data),
756
+ blockNumber,
757
+ blockHash,
758
+ transactionHash: h,
759
+ transactionIndex: txIndex,
760
+ logIndex: blockLogs.length + i,
761
+ };
762
+ return sl;
763
+ });
764
+ blockLogs.push(...rcptLogs);
765
+
766
+ const receipt: SerializedReceipt = {
767
+ transactionHash: h,
768
+ transactionIndex: txIndex,
769
+ blockNumber,
770
+ blockHash,
771
+ from,
772
+ to,
773
+ contractAddress: created,
774
+ cumulativeGasUsed: numHex(cumulativeGasUsed),
775
+ gasUsed: numHex(res.gasUsed),
776
+ effectiveGasPrice: numHex(res.effectiveGasPrice),
777
+ status: res.status,
778
+ type: (tx as any).type ?? 0,
779
+ logs: rcptLogs,
780
+ logsBloom: hex(res.logsBloom),
781
+ };
782
+ receipts.set(h, receipt);
783
+
784
+ const stx: SerializedTx = {
785
+ hash: h,
786
+ raw: hex(raw),
787
+ from,
788
+ to,
789
+ nonce: Number((tx as any).nonce),
790
+ value: numHex((tx as any).value ?? 0n),
791
+ input: hex((tx as any).data ?? new Uint8Array()),
792
+ type: (tx as any).type ?? 0,
793
+ blockNumber,
794
+ blockHash,
795
+ transactionIndex: txIndex,
796
+ gas: numHex((tx as any).gasLimit),
797
+ gasPrice:
798
+ (tx as any).gasPrice !== undefined
799
+ ? numHex((tx as any).gasPrice)
800
+ : null,
801
+ maxFeePerGas:
802
+ (tx as any).maxFeePerGas !== undefined
803
+ ? numHex((tx as any).maxFeePerGas)
804
+ : null,
805
+ maxPriorityFeePerGas:
806
+ (tx as any).maxPriorityFeePerGas !== undefined
807
+ ? numHex((tx as any).maxPriorityFeePerGas)
808
+ : null,
809
+ };
810
+ transactions.set(h, stx);
811
+ txHashes.push(h);
812
+ txIndex++;
813
+ }
814
+
815
+ allLogs.push(...blockLogs);
816
+ storeBlock(block, txHashes, blockLogs, await currentStateRoot());
817
+ // emit newHeads
818
+ for (const cb of headSubs) cb({number: blockNumber, hash: blockHash});
819
+
820
+ return {blockNumber, blockHash, txHashes};
821
+ }
822
+
823
+ async function mineBlock() {
824
+ const batch = pending.splice(0, pending.length);
825
+ return executeAndMine(batch);
826
+ }
827
+
828
+ /**
829
+ * Decode a raw tx AND DECIDE ITS SENDER, once. When `claimedFrom` is supplied
830
+ * (the `evm_*As` methods, `senderMode:'trusted'` only) we SKIP ecrecover and take
831
+ * the caller-supplied address as the sender; otherwise we recover it, as a real
832
+ * node does.
833
+ *
834
+ * THE SENDER IS A VALUE FROM HERE ON. It travels with the transaction (see
835
+ * {@link SubmittedTx}) to the receipt's `from` and across the engine seam as
836
+ * `TransactionRequest.sender`, so exactly ONE place in the node answers "who sent
837
+ * this" and no engine is trusted to answer it again. Recovery is therefore EAGER
838
+ * (at submit, not at mine): a transaction whose signature cannot be recovered is
839
+ * rejected by the `eth_sendRawTransaction*` call that submitted it rather than by
840
+ * a later `mine()`, which is where a `'recover'` node would have failed anyway.
841
+ *
842
+ * WHAT THIS PRIMITIVE IS: "execute this tx as this sender, do not recover".
843
+ * That is all. It is deliberately NOT an impersonation feature — impersonation
844
+ * (an address registry + unsigned `eth_sendTransaction`, anvil/hardhat style) is
845
+ * account POLICY, and this package has no accounts by design. Two DIFFERENT
846
+ * callers want this one primitive:
847
+ *
848
+ * (a) A NORMAL, genuinely-signed tx that just wants to bypass a redundant
849
+ * ecrecover. The client signed it, so it already knows the sender;
850
+ * re-deriving it on a local chain is pure waste. The signature is REAL,
851
+ * merely unverified.
852
+ * (b) A HIGHER LAYER implementing impersonation on top: it has no key, so it
853
+ * FABRICATES a signature, serialises the tx, and passes the claimed
854
+ * sender. Nothing here needs to know that happened.
855
+ *
856
+ * WHY it is worth a cheat method: ecrecover is a FIXED cost per tx and it is the
857
+ * single dominant cost of a small one. Measured 2026-08-11
858
+ * (`docs/spikes/sender-recovery-uses-the-engines-ecrecover/measurements.md`) at
859
+ * ~6.2x on the isolated transaction path (2.09 -> 0.33 ms/tx, signing outside the
860
+ * window) and ~3.6x end-to-end through a viem-style client (2.37 -> 0.66 ms/tx;
861
+ * the residual is the CLIENT's own signing, which only case (b) avoids). Gas and
862
+ * status are byte-identical either way.
863
+ *
864
+ * THE GAP DEPENDS ON THE ENGINE NOW, and it has NARROWED. With an engine that
865
+ * brings its own secp256k1 (`Engine.ecrecover` in ./types.ts —
866
+ * `webevm/revm` does, at zero additional bytes) the recovery itself is
867
+ * ~4.3x cheaper, so `'recover'` costs 0.65 ms/tx isolated instead of 2.02 and the
868
+ * ratio falls to ~2.8x (~1.8x end to end). It stays worth having; it has stopped
869
+ * being the dominant lever. The figures this paragraph used to carry (~13x, ~2.3x)
870
+ * were measured on `runTx` in isolation before the storage re-layer of ADR 0009,
871
+ * and had drifted by roughly half — not because recovery got slower, but because
872
+ * everything around it got faster.
873
+ *
874
+ * HOW: the claimed address becomes this transaction's sender, full stop — nothing
875
+ * on the transaction is touched. Everything else about it stays REAL — same wire
876
+ * bytes, same `tx.hash()`, same signature on the wire — so receipts, block
877
+ * contents and `eth_getTransactionByHash` are unchanged. The ONLY thing dropped is
878
+ * the proof that the signer authorised this sender.
879
+ *
880
+ * IT USED TO SHADOW `tx.getSenderAddress()` on the parsed instance, because
881
+ * `runTx` reads the sender through exactly that one call. That worked only while
882
+ * the node itself ran `runTx`: once transactions cross the engine seam, a pinned
883
+ * method is an undocumented convention an engine has to interrogate the same way,
884
+ * and an engine recovering its own sender would silently execute as the SIGNER —
885
+ * charging that account, advancing its nonce, returning a plausible receipt. So
886
+ * the sender is data now, and the shadowing is gone rather than kept as a second
887
+ * mechanism saying the same thing.
888
+ *
889
+ * ---- CALLER CONTRACT, case (b) / fabricated signatures ONLY ----
890
+ *
891
+ * 1. TX BYTES MUST BE UNIQUE PER SENDER. `from` is NOT part of a transaction —
892
+ * it is the OUTPUT of recovery — so the hash is computed from the bytes
893
+ * alone. Two fabricated txs with the same dummy signature, nonce, `to` and
894
+ * data produce the SAME hash even for different claimed senders, and would
895
+ * silently overwrite each other in the receipt/tx maps. Derive the dummy `r`
896
+ * from the sender address (or otherwise vary the bytes per sender). anvil hit
897
+ * exactly this and fixed it by folding the sender into hash computation
898
+ * (foundry #4210). Genuinely-signed txs — case (a) — are unaffected: real
899
+ * signatures already differ per signer.
900
+ *
901
+ * 2. FABRICATED TXS ARE NOT PORTABLE TO A `'recover'` NODE. `dumpState` stores
902
+ * each tx's raw bytes, so a dump containing fabricated signatures carries txs
903
+ * no authenticated node could ever validate. Fine for a local chain; do not
904
+ * treat such a dump as a replayable chain history. Again, case (a) dumps are
905
+ * unaffected — those signatures are real.
906
+ *
907
+ * SAFETY: gated on `senderMode:'trusted'`. In the default `'recover'` mode these
908
+ * methods do not exist and we throw -32601 rather than silently trusting input.
909
+ */
910
+ function parseTx(rawHex: unknown, claimedFrom?: unknown): SubmittedTx {
911
+ const raw = hexToBytes(String(rawHex));
912
+ if (claimedFrom === undefined) {
913
+ const tx = createTxFromRLP(raw, {common});
914
+ // THE CURVE STEP, ON THE ENGINE WHEN THE ENGINE HAS ONE. The DECISION
915
+ // (which message is signed, EIP-2's low-`s` rule, what the wire's `v`
916
+ // means) stays here either way — see ./sender-recovery.ts, and
917
+ // `Engine.ecrecover` in ./types.ts for why it is the seam's one optional
918
+ // operation. With no engine ecrecover this is `@ethereumjs/tx`'s own
919
+ // recovery, unchanged, and the two are proven to authenticate identically
920
+ // (test/helpers/sender-recovery.ts) — on the transactions they ACCEPT and
921
+ // on the ones they must REFUSE.
922
+ return {
923
+ tx,
924
+ raw,
925
+ sender: engineEcrecover
926
+ ? recoverSender(tx, common, engineEcrecover)
927
+ : tx.getSenderAddress(),
928
+ };
929
+ }
930
+ if (senderMode !== 'trusted') {
931
+ throw new RpcError(
932
+ -32601,
933
+ "method not available: trusted-sender sends require senderMode:'trusted' " +
934
+ '(create the node with {senderMode:"trusted"} to skip ecrecover). That mode ' +
935
+ 'TRUSTS the caller-supplied sender, so ANY caller can impersonate ANY ' +
936
+ 'address — never enable it where untrusted callers can reach the node.',
937
+ );
938
+ }
939
+ // Throws on a malformed address rather than executing as someone unexpected.
940
+ const from = createAddressFromString(String(claimedFrom));
941
+ // The transaction is parsed FROZEN, like every other one: nothing about it is
942
+ // rewritten to carry the claimed sender, because the sender does not live on it.
943
+ const tx = createTxFromRLP(raw, {common});
944
+ return {tx, raw, sender: from};
945
+ }
946
+
947
+ /**
948
+ * REFUSE A TRANSACTION NO BLOCK THIS NODE BUILDS COULD CONTAIN, in the node's
949
+ * own words, before any engine sees it.
950
+ *
951
+ * WHY THE NODE SAYS IT AND NOT THE ENGINE. Both engines enforce this rule
952
+ * themselves now that the default engine no longer skips it (see ./engine.ts),
953
+ * and NEITHER can say it legibly: `@ethereumjs/vm` says "tx has a higher gas
954
+ * limit than the block" and revm says `Transaction(CallerGasLimitMoreThanBlock)`.
955
+ * Neither carries a number, and above all neither mentions `blockGasLimit`, the
956
+ * knob that lifts it, which only the node knows about. The block is the NODE's
957
+ * half of the seam on every engine (it builds it, it configures its gas limit),
958
+ * so "does this transaction fit in a block I will build" is the node's question
959
+ * to answer, and answering it here is what makes the refusal IDENTICAL on both
960
+ * engines rather than merely present on both. The engines' own checks stay as
961
+ * the backstop underneath: this is the same rule (`tx.gasLimit >
962
+ * block.header.gasLimit`, per transaction, not cumulative), so a transaction
963
+ * that passes here passes there.
964
+ *
965
+ * WHY AT SUBMIT rather than at mine: the same reason sender recovery is eager
966
+ * (see {@link parseTx}). The transaction is rejected by the
967
+ * `eth_sendRawTransaction*` call that submitted it, rather than sitting in
968
+ * `pending` and taking a whole later `mine()` batch down with it. Nothing about
969
+ * the answer changes with time: every block this node builds has the same
970
+ * {@link minedBlockGasLimit}.
971
+ */
972
+ function refuseIfOverBlockGasLimit(tx: TypedTransaction): void {
973
+ const gasLimit = (tx as any).gasLimit as bigint;
974
+ if (gasLimit <= minedBlockGasLimit) return;
975
+ // -32000 (the JSON-RPC server-error range geth uses for a transaction its
976
+ // pool refuses) rather than 3 `execution reverted`: nothing executed, and a
977
+ // client that reads a revert here would look for return data that does not
978
+ // exist.
979
+ throw new RpcError(
980
+ -32000,
981
+ `transaction gas limit ${gasLimit} exceeds the block gas limit ${minedBlockGasLimit}, so no block this node builds could contain it. ` +
982
+ `It is REFUSED rather than mined against a limit the block does not have (a real node refuses it too, and this node's other EVM engine always did). ` +
983
+ `To allow it, raise the limit: createNode({blockGasLimit: ${gasLimit}n}). The default is 30000000n, or blockEnv.gasLimit if you set the block environment explicitly. ` +
984
+ `The block then really is that large: GASLIMIT reports the configured value to a contract, and eth_getBlockByNumber reports it too.`,
985
+ );
986
+ }
987
+
988
+ /**
989
+ * REFUSE A TRANSACTION THE SENDER'S OWN ACCOUNT FORBIDS — a replay, a nonce this
990
+ * node will never reach, or a bill the sender cannot cover — in the node's own
991
+ * words, before the engine sees it.
992
+ *
993
+ * WHY THE NODE SAYS IT AND NOT THE ENGINE, which is the same argument
994
+ * {@link refuseIfOverBlockGasLimit} makes and the reason this sits beside it.
995
+ * Both engines enforce these three rules already, and neither can say them in a
996
+ * way a client can use: `@ethereumjs/vm` answers a replay with `the tx doesn't
997
+ * have the correct nonce. account has nonce of: 1 tx has nonce of: 0` followed
998
+ * by a dump of the whole block and transaction, and revm answers it with
999
+ * `Transaction(NonceTooLow { tx: 0, state: 1 })`. Same node, same transaction,
1000
+ * two unrelated sentences — and the revm one is a wasm-shaped string arriving
1001
+ * where a client expects prose, the transaction-path twin of the mistake
1002
+ * recorded in the `rejectionMessage` JSDoc of ./revm.ts. The node owns the
1003
+ * STATE on every engine (ADR 0010) and it owns the transaction's parsing, so
1004
+ * "may this sender send this transaction now" is the node's question, and
1005
+ * answering it here is what makes the refusal IDENTICAL across engines rather
1006
+ * than merely present on both. The engines' own checks stay as the backstop
1007
+ * underneath: these are the same three rules, so a transaction that passes here
1008
+ * passes there.
1009
+ *
1010
+ * IT ALSO FIXES THE ORDER, which no engine agrees about: a transaction that is
1011
+ * both replayed and unaffordable is reported as a nonce failure by geth and by
1012
+ * this node, and could be reported as either by an engine. One order here means
1013
+ * one answer whatever is installed.
1014
+ *
1015
+ * WHY AT MINE-TIME rather than at submit, unlike its two siblings: these answers
1016
+ * CHANGE WITH TIME. In `manual`/`interval` mining a consumer submits nonce 0 and
1017
+ * nonce 1 back to back, and at submit the second is a nonce this node has not
1018
+ * reached; by the time the batch is mined, the first has advanced it. The same
1019
+ * goes for the money. So the reading is taken at the last possible moment —
1020
+ * immediately before the engine would execute it — against the state the
1021
+ * transaction is actually about to run on.
1022
+ *
1023
+ * THE VOCABULARY IS geth's leading clause (`nonce too low` / `nonce too high` /
1024
+ * `insufficient funds for gas * price + value`), because a client already knows
1025
+ * it: viem maps those phrases onto typed errors. Inventing a private dialect for
1026
+ * rules the whole ecosystem already names would cost every consumer a
1027
+ * translation and buy nothing. What follows the clause is this node's own
1028
+ * honest-edge half — what happened and what to do about it — including the one
1029
+ * thing a real node would NOT say: that there is no mempool here, so a
1030
+ * too-high nonce is refused rather than queued.
1031
+ */
1032
+ async function refuseIfSenderCannotSend(
1033
+ tx: TypedTransaction,
1034
+ sender: Address,
1035
+ ): Promise<void> {
1036
+ // ONE READ of the sender's account, for both rules: a missing account is a
1037
+ // sender at nonce 0 holding nothing, which is exactly how every other read on
1038
+ // this node reports it (`eth_getTransactionCount`, `eth_getBalance`).
1039
+ const account = await sm.getAccount(sender);
1040
+ const stateNonce = account?.nonce ?? 0n;
1041
+ const txNonce = tx.nonce;
1042
+ const address = sender.toString();
1043
+ if (txNonce < stateNonce) {
1044
+ throw new RpcError(
1045
+ -32000,
1046
+ `nonce too low: address ${address}, tx: ${txNonce}, state: ${stateNonce}. ` +
1047
+ `The sender has already used that nonce, so this transaction is a REPLAY ` +
1048
+ `and is REFUSED rather than mined a second time. Sign it again with nonce ` +
1049
+ `${stateNonce} — eth_getTransactionCount reports the sender's next nonce.`,
1050
+ );
1051
+ }
1052
+ if (txNonce > stateNonce) {
1053
+ throw new RpcError(
1054
+ -32000,
1055
+ `nonce too high: address ${address}, tx: ${txNonce}, state: ${stateNonce}. ` +
1056
+ `This node has NO MEMPOOL, so a transaction that is not executable NOW is ` +
1057
+ `refused rather than queued until the gap is filled: waiting will not mine ` +
1058
+ `it. Send the missing transactions first, or sign this one with nonce ` +
1059
+ `${stateNonce} — eth_getTransactionCount reports the sender's next nonce.`,
1060
+ );
1061
+ }
1062
+ const balance = account?.balance ?? 0n;
1063
+ const upfront = upfrontCost(tx);
1064
+ if (balance < upfront) {
1065
+ throw new RpcError(
1066
+ -32000,
1067
+ `insufficient funds for gas * price + value: address ${address} have ` +
1068
+ `${balance} want ${upfront}. The sender must be able to pay for its WHOLE ` +
1069
+ `gas limit at the maximum fee it offered, plus the value it sends, BEFORE ` +
1070
+ `the transaction runs — even though it is charged less than that once the ` +
1071
+ `gas it really used is known. Lower the value, the gas limit or ` +
1072
+ `maxFeePerGas, or fund the sender.`,
1073
+ );
1074
+ }
1075
+ }
1076
+
1077
+ /**
1078
+ * REFUSE A TRANSACTION THAT COULD NOT REACH ITS FIRST OPCODE, in the node's own
1079
+ * words, before any engine sees it.
1080
+ *
1081
+ * The second of the two refusals a transaction earns ON ITS OWN, which is why it
1082
+ * sits beside {@link refuseIfOverBlockGasLimit} and at the same moment: both
1083
+ * read the transaction and nothing else, so neither answer can change while the
1084
+ * transaction waits in `pending`, and refusing eagerly means the
1085
+ * `eth_sendRawTransaction*` call that submitted it is the one that fails. The
1086
+ * two that DO depend on the chain's state — the nonce and the money — are
1087
+ * checked at the last possible moment instead, in {@link refuseIfSenderCannotSend}.
1088
+ *
1089
+ * THE FLOOR IS THE TRANSACTION'S OWN `getIntrinsicGas()`, NOT the shared
1090
+ * `intrinsicGas()` of ./intrinsic-gas.ts, and the difference is load-bearing:
1091
+ * the shared formula has no ACCESS-LIST term, because an `eth_call` carries no
1092
+ * access list, so it is 6,200 gas short for a type-1 transaction naming one
1093
+ * address and two keys. Both engines charge the access list, so a check built on
1094
+ * the shared formula would wave such a transaction through and let the engine
1095
+ * refuse it in its own vocabulary — the exact divergence this refusal exists to
1096
+ * remove. Measured, on four transaction shapes and against BOTH engines' actual
1097
+ * floors, in
1098
+ * `docs/spikes/replayed-and-invalid-transactions-are-rejected-as-the-nodes-own-errors/measurements.md`.
1099
+ * The two figures answer two different questions and both are the node's: what a
1100
+ * READ must be budgeted (and an engine's execution gas topped up by), versus what
1101
+ * a TRANSACTION must be able to pay before it starts.
1102
+ */
1103
+ function refuseIfBelowIntrinsicGas(tx: TypedTransaction): void {
1104
+ const gasLimit = tx.gasLimit;
1105
+ const minimum = tx.getIntrinsicGas();
1106
+ if (gasLimit >= minimum) return;
1107
+ throw new RpcError(
1108
+ -32000,
1109
+ `intrinsic gas too low: have ${gasLimit}, want ${minimum}. ` +
1110
+ `A transaction pays a 21000 base plus its calldata (and its access list, and ` +
1111
+ `32000 more to create a contract) before its first opcode runs, so this gas ` +
1112
+ `limit could not start it and no block this node builds could contain it. ` +
1113
+ `Raise the gas limit to at least ${minimum} — eth_estimateGas reports what a ` +
1114
+ `transaction needs, given the same calldata AND the same access list, which ` +
1115
+ `it charges too.`,
1116
+ );
1117
+ }
1118
+
1119
+ /** Queue-or-execute a submitted tx; returns the hash, or the receipt if `sync`. */
1120
+ async function submit(
1121
+ submitted: SubmittedTx,
1122
+ sync: boolean,
1123
+ ): Promise<unknown> {
1124
+ refuseIfOverBlockGasLimit(submitted.tx);
1125
+ refuseIfBelowIntrinsicGas(submitted.tx);
1126
+ const h = txHashOf(submitted.tx);
1127
+ if (miningConfig.type === 'auto') {
1128
+ await executeAndMine([submitted]);
1129
+ } else {
1130
+ pending.push(submitted);
1131
+ if (sync) await mineBlock();
1132
+ }
1133
+ if (!sync) return h;
1134
+ const r = receipts.get(h);
1135
+ return r ? receiptToRpc(r) : null;
1136
+ }
1137
+
1138
+ // ---------- block lookup helpers ----------
1139
+ function resolveBlockTag(tag: unknown): number {
1140
+ if (
1141
+ tag === 'latest' ||
1142
+ tag === 'pending' ||
1143
+ tag === 'safe' ||
1144
+ tag === 'finalized' ||
1145
+ tag == null
1146
+ )
1147
+ return latestNumber;
1148
+ if (tag === 'earliest') return 0;
1149
+ if (typeof tag === 'string') return Number(BigInt(tag));
1150
+ if (typeof tag === 'number') return tag;
1151
+ return latestNumber;
1152
+ }
1153
+
1154
+ /**
1155
+ * The stored block, as `eth_getBlockByNumber` / `eth_getBlockByHash` report it.
1156
+ *
1157
+ * IT READS THE SERIALISED HEADER AND NOTHING ELSE, deliberately. `sb.block` is
1158
+ * right there and carries the same coinbase and mixHash, but it is the object
1159
+ * `loadState` REBUILDS, so a field taken from it would be reported correctly by
1160
+ * a live node and as zero by the same node after a reload — which is worse than
1161
+ * a uniform zero, because nothing tells a consumer which side of the trip they
1162
+ * are on. Every value below is therefore one a dump carries.
1163
+ *
1164
+ * `stateRoot` is the one REAL value among the roots (in `'trie'` mode);
1165
+ * `sha3Uncles`, `transactionsRoot` and `receiptsRoot` stay honest zero
1166
+ * placeholders, named as such in the README, because this node builds no tries
1167
+ * over its transactions or receipts. `logsBloom` used to be in that list and is
1168
+ * not any more: it is the OR of the block's receipt blooms, so the standard
1169
+ * pre-filter (test the header bloom, then call `eth_getLogs`) finds what is
1170
+ * there instead of silently finding nothing.
1171
+ */
1172
+ function blockToRpc(sb: StoredBlock, fullTx: boolean) {
1173
+ const h = sb.header;
1174
+ return {
1175
+ number: numHex(h.number),
1176
+ hash: h.hash,
1177
+ parentHash: h.parentHash,
1178
+ nonce: '0x0000000000000000',
1179
+ sha3Uncles: ZERO_HASH,
1180
+ logsBloom: h.logsBloom ?? EMPTY_LOGS_BLOOM,
1181
+ transactionsRoot: ZERO_HASH,
1182
+ stateRoot: h.stateRoot,
1183
+ receiptsRoot: ZERO_HASH,
1184
+ // A dump written before these fields existed carries neither, and absent
1185
+ // means ZERO rather than `undefined`: an old state loads into a block that
1186
+ // really had a zero coinbase, not into an RPC result missing a field.
1187
+ miner: h.miner ?? ZERO_ADDRESS,
1188
+ mixHash: h.mixHash ?? ZERO_HASH,
1189
+ difficulty: '0x0',
1190
+ totalDifficulty: '0x0',
1191
+ extraData: '0x',
1192
+ size: '0x0',
1193
+ gasLimit: h.gasLimit,
1194
+ gasUsed: h.gasUsed,
1195
+ timestamp: numHex(h.timestamp),
1196
+ baseFeePerGas: h.baseFeePerGas,
1197
+ uncles: [],
1198
+ transactions: fullTx
1199
+ ? h.transactions.map((th) => txToRpc(transactions.get(th)!))
1200
+ : h.transactions,
1201
+ };
1202
+ }
1203
+
1204
+ function txToRpc(t: SerializedTx) {
1205
+ // The 1559 fee fields are OMITTED for a legacy transaction rather than emitted as
1206
+ // `null`, which is what geth does. The difference is not cosmetic: consumers branch with
1207
+ // `'maxFeePerGas' in tx`, so a present-but-null field sends them down the 1559 path and
1208
+ // they then blow up on `BigInt(null)`. A key that exists only when it means something
1209
+ // keeps that idiom honest.
1210
+ return {
1211
+ hash: t.hash,
1212
+ nonce: numHex(t.nonce),
1213
+ blockHash: t.blockHash,
1214
+ blockNumber: numHex(t.blockNumber),
1215
+ transactionIndex: numHex(t.transactionIndex),
1216
+ from: t.from,
1217
+ to: t.to,
1218
+ value: t.value,
1219
+ gas: t.gas,
1220
+ gasPrice: t.gasPrice,
1221
+ ...(t.maxFeePerGas == null ? {} : {maxFeePerGas: t.maxFeePerGas}),
1222
+ ...(t.maxPriorityFeePerGas == null
1223
+ ? {}
1224
+ : {maxPriorityFeePerGas: t.maxPriorityFeePerGas}),
1225
+ input: t.input,
1226
+ type: numHex(t.type),
1227
+ chainId: numHex(chainId),
1228
+ };
1229
+ }
1230
+
1231
+ function receiptToRpc(r: SerializedReceipt) {
1232
+ return {
1233
+ transactionHash: r.transactionHash,
1234
+ transactionIndex: numHex(r.transactionIndex),
1235
+ blockHash: r.blockHash,
1236
+ blockNumber: numHex(r.blockNumber),
1237
+ from: r.from,
1238
+ to: r.to,
1239
+ contractAddress: r.contractAddress,
1240
+ cumulativeGasUsed: r.cumulativeGasUsed,
1241
+ gasUsed: r.gasUsed,
1242
+ effectiveGasPrice: r.effectiveGasPrice,
1243
+ status: r.status ? '0x1' : '0x0',
1244
+ type: numHex(r.type),
1245
+ logs: r.logs.map(logToRpc),
1246
+ logsBloom: r.logsBloom,
1247
+ };
1248
+ }
1249
+
1250
+ function logToRpc(l: SerializedLog) {
1251
+ return {
1252
+ address: l.address,
1253
+ topics: l.topics,
1254
+ data: l.data,
1255
+ blockNumber: numHex(l.blockNumber),
1256
+ blockHash: l.blockHash,
1257
+ transactionHash: l.transactionHash,
1258
+ transactionIndex: numHex(l.transactionIndex),
1259
+ logIndex: numHex(l.logIndex),
1260
+ removed: false,
1261
+ };
1262
+ }
1263
+
1264
+ // ---------- eth_call / estimateGas through the ENGINE's READ half (no signing) ----
1265
+ /**
1266
+ * The node's single pure-read helper, and the read half of the engine seam: it
1267
+ * normalises RPC params into a {@link ReadCallRequest} and hands them to the
1268
+ * engine's `call`.
1269
+ * Three dispatcher cases use it (`eth_call`, `eth_estimateGas` and
1270
+ * `eth_fillTransaction`'s estimation).
1271
+ *
1272
+ * Keeping a read PURE is the engine's job, not this function's — the default
1273
+ * `@ethereumjs/evm` engine checkpoints/reverts and resets EIP-2929 warmth
1274
+ * because that EVM requires it; an engine that cannot commit pays for neither.
1275
+ * See ./engine.ts.
1276
+ */
1277
+ async function evmCall(
1278
+ params: any,
1279
+ budget?: bigint,
1280
+ ): Promise<ReadCallResult> {
1281
+ const from = params.from
1282
+ ? createAddressFromString(params.from)
1283
+ : createAddressFromString('0x0000000000000000000000000000000000000000');
1284
+ const to = params.to ? createAddressFromString(params.to) : undefined;
1285
+ const data = params.data
1286
+ ? hexToBytes(params.data)
1287
+ : params.input
1288
+ ? hexToBytes(params.input)
1289
+ : new Uint8Array();
1290
+ const value = params.value ? BigInt(params.value) : 0n;
1291
+ // THE DEFAULT READ BUDGET IS A CONSTANT, DELIBERATELY NOT `blockGasLimit`.
1292
+ // They are the same number by default (30,000,000) and it would be easy to
1293
+ // read the second off the first, but they answer different questions and are
1294
+ // DECIDED APART. That is recorded here because a `blockGasLimit` a consumer
1295
+ // may now have to raise (it is what buys back the block-gas-limit relaxation
1296
+ // the engines used to disagree about; see `refuseIfOverBlockGasLimit` above)
1297
+ // makes the link actively harmful:
1298
+ // - A BLOCK GAS LIMIT is a property of the chain a transaction is mined into,
1299
+ // visible to a contract as `GASLIMIT`. A READ BUDGET is how long an
1300
+ // `eth_call` with no `gas` may run before it halts. Linking them means
1301
+ // `createNode({blockGasLimit: 10_000_000_000n})` silently buys every
1302
+ // unbudgeted `eth_call` a 300x longer runaway, and the browser tab that
1303
+ // locks up is nowhere near the option that caused it.
1304
+ // - The constant is also QUOTED as a fixed number by the revm engine's
1305
+ // hardfork refusals (`REVM_REFUSED_HARDFORKS.osaka` compares it against
1306
+ // EIP-7825's 16,777,216 cap in src/revm.ts), which a per-node value would
1307
+ // make wrong for some nodes and right for others.
1308
+ // A caller who wants a bigger budget passes `gas` on the call itself, which is
1309
+ // the standard `eth_call` field for exactly this and needs no configuration.
1310
+ //
1311
+ // `budget` OVERRIDES BOTH, and exactly one caller passes it: the
1312
+ // `estimateGas` search below, which is asking a different question from
1313
+ // "how long may this call run". It probes a candidate gas LIMIT, and the
1314
+ // gas that reaches the frame under that limit is the limit MINUS the
1315
+ // intrinsic cost the transaction pays first — so the search computes the
1316
+ // budget itself and this function must not re-derive one from `params.gas`,
1317
+ // which for `eth_estimateGas` is a CAP on the limit rather than a budget.
1318
+ const gasLimit =
1319
+ budget ?? (params.gas ? BigInt(params.gas) : DEFAULT_READ_BUDGET);
1320
+ return engine.call({
1321
+ from,
1322
+ to,
1323
+ data,
1324
+ value,
1325
+ gasLimit,
1326
+ block: blockStore.get(latestNumber)!.block,
1327
+ });
1328
+ }
1329
+
1330
+ /**
1331
+ * THE SMALLEST GAS LIMIT AT WHICH THIS REQUEST SUCCEEDS — a SEARCH, not a
1332
+ * measurement, and the difference is the whole point of this function.
1333
+ *
1334
+ * ## Why measuring is the wrong answer
1335
+ *
1336
+ * This method used to run the request once and report what it CONSUMED
1337
+ * (`executionGasUsed` + intrinsic gas), which is exact and is not what the
1338
+ * caller asked for. A client turns this number into a transaction's gas LIMIT,
1339
+ * and under EIP-150's 63/64 rule a `CALL` or `CREATE` forwards at most 63/64 of
1340
+ * the gas remaining at that point: a transaction whose limit equals its total
1341
+ * consumption therefore starves its own sub-call by the 1/64 the outer frame
1342
+ * keeps. Consumption is a LOWER BOUND on the limit, never the limit.
1343
+ *
1344
+ * That is not theoretical. Deploying through the standard CREATE2 factory
1345
+ * (`0x4e59b448...`, a plain call whose body does one `CREATE2`) with a limit
1346
+ * taken from this method returned a receipt with `status: 0x0` and no created
1347
+ * contract, while the factory itself, the funding transfer and a proxy pointing
1348
+ * at the address that was never deployed all mined fine — so the failure landed
1349
+ * nowhere near its cause: a proxy delegatecalling an address with no code, which
1350
+ * answers `0x` rather than failing. The same shape is recorded from the other
1351
+ * side in `test/helpers/post-state.ts`, where an estimate-sized limit made an
1352
+ * inner `SSTORE` run out of gas while the receipt still said success.
1353
+ *
1354
+ * So this searches for the smallest limit at which the request SUCCEEDS, which
1355
+ * is what geth's `eth_estimateGas` has always done and for exactly this reason.
1356
+ *
1357
+ * ## The shape, and what each step costs
1358
+ *
1359
+ * 1. ONE RUN AT THE UPPER BOUND (the caller's `gas` if it named one, capped at
1360
+ * the block gas limit — see below). If the request fails there it fails
1361
+ * everywhere, and this method throws instead of returning a plausible number
1362
+ * that would fail on submission.
1363
+ * 2. ONE PROBE AT THE MEASURED CONSUMPTION. A request that makes no sub-call and
1364
+ * no create succeeds at exactly what it consumed, so the common case (a
1365
+ * transfer, an `SSTORE`, a deployment) is answered EXACTLY, in one extra
1366
+ * execution, and the search below never runs. This is the short-circuit, and
1367
+ * it is a probe rather than a static "does this request call out?" test
1368
+ * because only the EVM knows: the answer lives in the callee's bytecode.
1369
+ * 3. A SEARCH in `(consumption, upper bound]`, which brackets the answer from
1370
+ * BELOW at the scale of the 63/64 rule before bisecting, so a window that
1371
+ * starts 30,000,000 wide is never walked down from the top. Bounded by
1372
+ * {@link MAX_ESTIMATE_PROBES}; on exhaustion it returns the smallest limit it
1373
+ * has PROVEN to succeed, which over-estimates rather than under-estimates.
1374
+ *
1375
+ * ## Consumption as the lower bound, and the one case it is not one
1376
+ *
1377
+ * `low` starts at the measured consumption and is treated as KNOWN-FAILING
1378
+ * (step 2 has just proven it), which is safe for every transaction whose cost
1379
+ * does not depend on the gas it is given. A transaction that reads `GAS` and
1380
+ * spends what it finds consumes MORE at a higher limit, so its consumption at
1381
+ * the upper bound is not a lower bound on the minimum successful limit. geth
1382
+ * documents the same caveat and makes the same choice: the alternative is to
1383
+ * start the search at the intrinsic floor and pay ~11 more executions on every
1384
+ * estimate, to serve a transaction whose "minimum" limit is meaningless anyway.
1385
+ * The result stays a limit at which the transaction SUCCEEDS, which is the
1386
+ * property that matters.
1387
+ *
1388
+ * ## The intrinsic terms are the search's floor, not an addend to its result
1389
+ *
1390
+ * `overhead` is what the transaction pays before its first opcode: the shared
1391
+ * intrinsic formula (base + calldata + the EIP-3860 initcode term) PLUS the
1392
+ * request's EIP-2930 access list, which the engine never sees (`ReadCallRequest`
1393
+ * carries none on either engine), charged here by the one caller that has a
1394
+ * request to read it off. Every candidate limit is probed as
1395
+ * `budget = limit - overhead`, so the frame gets exactly the gas the mined
1396
+ * transaction would give it, and every number this method can return is at least
1397
+ * `overhead`. That last clause is load-bearing: `refuseIfBelowIntrinsicGas`
1398
+ * points callers HERE for "the number a transaction needs", so the node must
1399
+ * never refuse a limit it has just recommended.
1400
+ */
1401
+ async function estimateGas(p: any): Promise<bigint> {
1402
+ const dataHex: string = p.data ?? p.input ?? '0x';
1403
+ const isCreate = !p.to;
1404
+ const overhead =
1405
+ intrinsicGas(dataHex, isCreate, common) + accessListGas(p.accessList);
1406
+
1407
+ // THE UPPER BOUND, and why it is capped at the block gas limit even when the
1408
+ // caller named a larger `gas`: a limit above it is REFUSED at submit by
1409
+ // `refuseIfOverBlockGasLimit`, so recommending one would be the node handing
1410
+ // back a number it will not accept. `gas` on an `eth_estimateGas` request is
1411
+ // geth's cap on the SEARCH ("do not consider limits above this"), which is a
1412
+ // different thing from `gas` on an `eth_call` ("let it run this long").
1413
+ const supplied = p.gas != null ? BigInt(p.gas) : undefined;
1414
+ const cap =
1415
+ supplied === undefined || supplied > minedBlockGasLimit
1416
+ ? minedBlockGasLimit
1417
+ : supplied;
1418
+
1419
+ // Nothing to search: the cap cannot pay for the transaction's own bytes, so
1420
+ // no limit within it reaches an opcode. Said in the vocabulary of the refusal
1421
+ // that would meet such a limit at submit, and NOT as `execution reverted`:
1422
+ // nothing executed, and a client reading a revert here would look for return
1423
+ // data that does not exist.
1424
+ if (cap < overhead) {
1425
+ throw new RpcError(
1426
+ -32000,
1427
+ `gas required exceeds allowance (${cap}): this transaction pays ${overhead} gas ` +
1428
+ `for its 21000 base, its calldata and its access list before its first opcode ` +
1429
+ `runs, so no gas limit within the allowance could start it. ` +
1430
+ (supplied !== undefined && supplied <= minedBlockGasLimit
1431
+ ? `The allowance is the \`gas\` you passed on the request; raise it or omit it.`
1432
+ : `The allowance is this node's block gas limit; raise it with createNode({blockGasLimit: ...}).`),
1433
+ );
1434
+ }
1435
+
1436
+ const probe = (limit: bigint) => evmCall(p, limit - overhead);
1437
+
1438
+ // 1) THE UPPER BOUND, run first: a request that cannot succeed with all the
1439
+ // gas there is cannot succeed at all, and the caller learns that here rather
1440
+ // than from a receipt.
1441
+ const top = await probe(cap);
1442
+ if (top.error) {
1443
+ // TWO WAYS TO FAIL AT THE TOP, AND THEY ARE DIFFERENT PROBLEMS. A request
1444
+ // that BURNED THE WHOLE ALLOWANCE and produced no callee bytes ran out of
1445
+ // gas: nothing reverted, there is no revert data to decode, and the caller's
1446
+ // problem is the allowance rather than the contract. geth says `gas required
1447
+ // exceeds allowance` to that, at -32000, which is what the `cap < overhead`
1448
+ // refusal above already says — so this branch keeps the two consistent
1449
+ // instead of flattening one of them into a revert a client would then hunt
1450
+ // for return data on.
1451
+ //
1452
+ // THE TEST IS STRUCTURAL, not a vocabulary: "did it consume everything it
1453
+ // was given, with nothing to show for it". Both engines report the whole
1454
+ // budget as spent when a frame halts for want of gas (revm's
1455
+ // `totalGasSpent` less the intrinsic the engine added back, the default
1456
+ // engine's `executionGasUsed`), and neither's WORDS for it are the other's
1457
+ // — matching on `out of gas` would be one engine's string asserted on both,
1458
+ // the mistake `rejectionMessage` in ./revm.ts exists to avoid. A REVERT
1459
+ // keeps its bytes and its gas, and a refusal BEFORE execution (an
1460
+ // unaffordable value) spends none, so both fall through to the clause below.
1461
+ // `budget > 0` because a zero budget makes "spent everything" vacuously
1462
+ // true, and a caller who passed `gas` equal to the intrinsic floor exactly
1463
+ // is better served by the engine's own words.
1464
+ const budget = cap - overhead;
1465
+ if (
1466
+ budget > 0n &&
1467
+ top.executionGasUsed >= budget &&
1468
+ top.returnValue.length === 0
1469
+ ) {
1470
+ throw new RpcError(
1471
+ -32000,
1472
+ `gas required exceeds allowance (${cap}): the transaction consumed the ENTIRE ` +
1473
+ `allowance and still did not succeed, so it needs more gas than the allowance ` +
1474
+ `permits (or it cannot succeed at all — an invalid opcode also spends everything). ` +
1475
+ `Nothing reverted, so there is no revert reason to decode. ` +
1476
+ (supplied !== undefined && supplied <= minedBlockGasLimit
1477
+ ? `The allowance is the \`gas\` you passed on the request; raise it or omit it.`
1478
+ : `The allowance is this node's block gas limit, which is also the most a transaction ` +
1479
+ `it mines may ask for; raise it with createNode({blockGasLimit: ...}). `) +
1480
+ `The engine reported: ${String(top.error)}.`,
1481
+ );
1482
+ }
1483
+ const reason = revertReason(top.returnValue);
1484
+ // The LEADING CLAUSE stays `execution reverted` and the return data stays
1485
+ // on `data`, because that pair is what a client decodes (viem turns it into
1486
+ // a typed revert error and reads the reason out of the bytes) and because
1487
+ // the node flattens every engine failure into it on the read path. What is
1488
+ // added is the part only this method knows: that the failure is not a
1489
+ // shortage of gas (the branch above owns that case), so there is no number
1490
+ // to report.
1491
+ throw new RpcError(
1492
+ 3,
1493
+ `execution reverted: the transaction fails at EVERY gas limit up to ${cap}, ` +
1494
+ `so there is no limit that would make it succeed and no estimate to report. ` +
1495
+ (reason !== undefined
1496
+ ? `Revert reason: ${reason}. `
1497
+ : top.returnValue.length > 0
1498
+ ? `It reverted with data (see \`data\`), which is not a standard Error(string). `
1499
+ : `It returned no revert data. `) +
1500
+ `The engine reported: ${String(top.error)}.`,
1501
+ hex(top.returnValue),
1502
+ );
1503
+ }
1504
+
1505
+ // 2) WHAT IT CONSUMED, and the probe that tests whether consumption is also a
1506
+ // workable limit. `consumed >= cap` means the request needs everything the
1507
+ // cap allows, and the cap has just been proven to work, so it IS the answer.
1508
+ const consumed = top.executionGasUsed + overhead;
1509
+ if (consumed >= cap) return cap;
1510
+ if (!(await probe(consumed)).error) return consumed;
1511
+
1512
+ // 3) THE SEARCH, in two phases. `low` FAILS and `high` SUCCEEDS at every
1513
+ // point, so `high` is at all times a limit this transaction has been PROVEN
1514
+ // to succeed at — including when the probe budget runs out mid-search.
1515
+ let low = consumed;
1516
+ let high = cap;
1517
+ let probes = 0n;
1518
+
1519
+ // PHASE 1 — BRACKET THE ANSWER FROM BELOW, at the scale of the rule that
1520
+ // causes the gap. A frame that hands 63/64 of its gas to a sub-call is short
1521
+ // by about 1/64 of what it held, and by about another 1/64 per nesting level
1522
+ // below that, so the first candidate above the measured consumption is
1523
+ // `low + low/64` and the step DOUBLES until it brackets the answer. Starting
1524
+ // at the top of the window instead (a plain bisection of `consumption`..`the
1525
+ // block gas limit`) means executing the request at 15,000,000 gas to learn
1526
+ // what a probe 3,000 gas above consumption would have said.
1527
+ let step = low / 64n;
1528
+ if (step < 1n) step = 1n;
1529
+ while (probes < MAX_ESTIMATE_PROBES && low + step < high) {
1530
+ const candidate = low + step;
1531
+ probes++;
1532
+ if ((await probe(candidate)).error) {
1533
+ low = candidate;
1534
+ step *= 2n;
1535
+ } else {
1536
+ high = candidate;
1537
+ break;
1538
+ }
1539
+ }
1540
+
1541
+ // PHASE 2 — BISECT WHAT PHASE 1 BRACKETED, which is the ordinary binary
1542
+ // search and the only part that can make the answer EXACT.
1543
+ while (probes < MAX_ESTIMATE_PROBES && low + 1n < high) {
1544
+ const mid = low + (high - low) / 2n;
1545
+ probes++;
1546
+ if ((await probe(mid)).error) low = mid;
1547
+ else high = mid;
1548
+ }
1549
+ return high;
1550
+ }
1551
+
1552
+ // ---------- the EIP-1193 dispatcher ----------
1553
+ async function request(args: RequestArguments): Promise<unknown> {
1554
+ const params = (args.params ?? []) as any[];
1555
+ switch (args.method) {
1556
+ case 'eth_chainId':
1557
+ return numHex(chainId);
1558
+ case 'net_version':
1559
+ return String(chainId);
1560
+ case 'eth_blockNumber':
1561
+ return numHex(latestNumber);
1562
+
1563
+ case 'eth_getBlockByNumber': {
1564
+ const sb = blockStore.get(resolveBlockTag(params[0]));
1565
+ return sb ? blockToRpc(sb, Boolean(params[1])) : null;
1566
+ }
1567
+ case 'eth_getBlockByHash': {
1568
+ const num = blockByHash.get(String(params[0]).toLowerCase());
1569
+ const sb = num != null ? blockStore.get(num) : undefined;
1570
+ return sb ? blockToRpc(sb, Boolean(params[1])) : null;
1571
+ }
1572
+
1573
+ case 'eth_call': {
1574
+ const r = await evmCall(params[0] ?? {});
1575
+ if (r.error)
1576
+ throw new RpcError(3, 'execution reverted', hex(r.returnValue));
1577
+ return hex(r.returnValue);
1578
+ }
1579
+ case 'eth_estimateGas':
1580
+ // THE SMALLEST GAS LIMIT AT WHICH THIS REQUEST SUCCEEDS, found by
1581
+ // re-executing it. The whole method is {@link estimateGas} above,
1582
+ // including why it is a search rather than the run-and-measure it used to
1583
+ // be, and where the request's EIP-2930 access list is charged.
1584
+ return numHex(await estimateGas(params[0] ?? {}));
1585
+
1586
+ case 'eth_fillTransaction': {
1587
+ // Fill the missing fields of a tx request and return {tx, raw} like geth
1588
+ // does (the `raw` is the UNSIGNED serialization — the node has no keys; a
1589
+ // client signs client-side). viem's prepareTransactionRequest probes this
1590
+ // to fill nonce/gas/fees in one round-trip; it reads the filled fields off
1591
+ // `tx` and re-signs itself, so an unsigned `raw` is correct here.
1592
+ const p = params[0] ?? {};
1593
+ const from = p.from
1594
+ ? createAddressFromString(p.from)
1595
+ : createAddressFromString(
1596
+ '0x0000000000000000000000000000000000000000',
1597
+ );
1598
+ const acc = await sm.getAccount(from);
1599
+ const nonce = p.nonce != null ? BigInt(p.nonce) : (acc?.nonce ?? 0n);
1600
+ const value = p.value != null ? BigInt(p.value) : 0n;
1601
+ const dataHex: string = p.data ?? p.input ?? '0x';
1602
+ const isCreate = !p.to;
1603
+ // Gas: the SAME search `eth_estimateGas` runs, unless the caller fixed it.
1604
+ // It has to be the same one: what this method fills is a gas LIMIT, and a
1605
+ // limit equal to measured consumption starves a sub-call under EIP-150's
1606
+ // 63/64 rule exactly as it does there (see {@link estimateGas}).
1607
+ //
1608
+ // WITH THE ACCESS LIST DELIBERATELY DROPPED, which is this method's one
1609
+ // documented difference and is unchanged: the transaction it FILLS AND
1610
+ // RETURNS carries no access list (it builds a type-0 or type-2 envelope
1611
+ // and drops the field), so charging for a list its own answer does not
1612
+ // contain would hand back a gas limit for a different transaction. See
1613
+ // `accessListGas` in ./intrinsic-gas.ts.
1614
+ const gas: bigint =
1615
+ p.gas != null
1616
+ ? BigInt(p.gas)
1617
+ : await estimateGas({...p, gas: undefined, accessList: undefined});
1618
+ // Fee fields: legacy iff caller passed gasPrice (and no 1559 fields),
1619
+ // otherwise EIP-1559 with the node's constant fee market.
1620
+ const isLegacy =
1621
+ p.gasPrice != null &&
1622
+ p.maxFeePerGas == null &&
1623
+ p.maxPriorityFeePerGas == null;
1624
+ const type = isLegacy ? 0 : 2;
1625
+ const txData: any = {
1626
+ nonce,
1627
+ gasLimit: gas,
1628
+ value,
1629
+ data: hexToBytes(dataHex.startsWith('0x') ? dataHex : '0x' + dataHex),
1630
+ to: p.to ?? undefined,
1631
+ type,
1632
+ };
1633
+ if (isLegacy) {
1634
+ txData.gasPrice = p.gasPrice != null ? BigInt(p.gasPrice) : gasPrice;
1635
+ } else {
1636
+ txData.maxFeePerGas =
1637
+ p.maxFeePerGas != null
1638
+ ? BigInt(p.maxFeePerGas)
1639
+ : baseFeePerGas + maxPriorityFeePerGas;
1640
+ txData.maxPriorityFeePerGas =
1641
+ p.maxPriorityFeePerGas != null
1642
+ ? BigInt(p.maxPriorityFeePerGas)
1643
+ : maxPriorityFeePerGas;
1644
+ txData.chainId = chainId;
1645
+ }
1646
+ const unsigned = createTx(txData, {common});
1647
+ // Build the RPC transaction object viem reads its filled fields off of.
1648
+ const tx = {
1649
+ from: from.toString(),
1650
+ to: p.to ?? null,
1651
+ nonce: numHex(nonce),
1652
+ gas: numHex(gas),
1653
+ value: numHex(value),
1654
+ input: hex(txData.data),
1655
+ type: numHex(type),
1656
+ chainId: numHex(chainId),
1657
+ gasPrice: isLegacy ? numHex(txData.gasPrice) : null,
1658
+ maxFeePerGas: isLegacy ? null : numHex(txData.maxFeePerGas),
1659
+ maxPriorityFeePerGas: isLegacy
1660
+ ? null
1661
+ : numHex(txData.maxPriorityFeePerGas),
1662
+ // placeholders viem deletes from the formatted tx (blockHash etc.)
1663
+ hash: ZERO_HASH,
1664
+ blockHash: null,
1665
+ blockNumber: null,
1666
+ transactionIndex: null,
1667
+ v: '0x0',
1668
+ r: ZERO_HASH,
1669
+ s: ZERO_HASH,
1670
+ };
1671
+ return {raw: hex(unsigned.serialize()), tx};
1672
+ }
1673
+
1674
+ case 'eth_getBalance': {
1675
+ const acc = await sm.getAccount(createAddressFromString(params[0]));
1676
+ return numHex(acc?.balance ?? 0n);
1677
+ }
1678
+ case 'eth_getTransactionCount': {
1679
+ const acc = await sm.getAccount(createAddressFromString(params[0]));
1680
+ return numHex(acc?.nonce ?? 0n);
1681
+ }
1682
+ case 'eth_getCode': {
1683
+ const code = await sm.getCode(createAddressFromString(params[0]));
1684
+ return hex(code);
1685
+ }
1686
+ case 'eth_getStorageAt': {
1687
+ const addr = createAddressFromString(params[0]);
1688
+ const slot = setLengthLeft(bigIntToBytes(BigInt(params[1])), 32);
1689
+ const val = await sm.getStorage(addr, slot);
1690
+ return hex(setLengthLeft(val, 32));
1691
+ }
1692
+
1693
+ // ---- Runtime state cheats (anvil/hardhat-style; for tests/local tooling) ----
1694
+ // These MUTATE state directly (no tx). Honest about being non-standard: they
1695
+ // are `evm_*`-namespaced. In trie mode each commits into the trie so the next
1696
+ // getStateRoot() reflects the change.
1697
+ case 'evm_setBalance': {
1698
+ // params: [address, valueHex]
1699
+ const addr = createAddressFromString(params[0]);
1700
+ await mutateAccount(addr, (acc) => {
1701
+ acc.balance = BigInt(params[1]);
1702
+ });
1703
+ return true;
1704
+ }
1705
+ case 'evm_setNonce': {
1706
+ // params: [address, nonceHex]
1707
+ const addr = createAddressFromString(params[0]);
1708
+ await mutateAccount(addr, (acc) => {
1709
+ acc.nonce = BigInt(params[1]);
1710
+ });
1711
+ return true;
1712
+ }
1713
+ case 'evm_setCode': {
1714
+ // params: [address, codeHex]
1715
+ const addr = createAddressFromString(params[0]);
1716
+ await sm.putCode(addr, hexToBytes(params[1]));
1717
+ touchedAccounts.add(addr.toString());
1718
+ await commitIfTrie();
1719
+ return true;
1720
+ }
1721
+ case 'evm_setStorageAt': {
1722
+ // params: [address, slotHex, valueHex(32-byte)]
1723
+ const addr = createAddressFromString(params[0]);
1724
+ const slot = setLengthLeft(bigIntToBytes(BigInt(params[1])), 32);
1725
+ await sm.putStorage(
1726
+ addr,
1727
+ slot,
1728
+ setLengthLeft(hexToBytes(params[2]), 32),
1729
+ );
1730
+ touchedAccounts.add(addr.toString());
1731
+ await commitIfTrie();
1732
+ return true;
1733
+ }
1734
+ case 'evm_setAccount': {
1735
+ // params: [address, {balance?, nonce?, code?, storage?}] — set all at once.
1736
+ const addr = createAddressFromString(params[0]);
1737
+ const a = params[1] ?? {};
1738
+ await mutateAccount(addr, (acc) => {
1739
+ if (a.balance != null) acc.balance = BigInt(a.balance);
1740
+ if (a.nonce != null) acc.nonce = BigInt(a.nonce);
1741
+ });
1742
+ if (a.code != null && a.code !== '0x')
1743
+ await sm.putCode(addr, hexToBytes(a.code));
1744
+ for (const [slot, val] of Object.entries(a.storage ?? {})) {
1745
+ await sm.putStorage(
1746
+ addr,
1747
+ setLengthLeft(bigIntToBytes(BigInt(slot)), 32),
1748
+ setLengthLeft(hexToBytes(val as string), 32),
1749
+ );
1750
+ }
1751
+ await commitIfTrie();
1752
+ return true;
1753
+ }
1754
+
1755
+ case 'eth_gasPrice':
1756
+ return numHex(gasPrice);
1757
+ case 'eth_maxPriorityFeePerGas':
1758
+ return numHex(maxPriorityFeePerGas);
1759
+ case 'eth_feeHistory': {
1760
+ const count = Number(BigInt(params[0] ?? '0x1'));
1761
+ // `reward` must carry ONE entry per requested percentile, per block. Returning a
1762
+ // single entry regardless of `rewardPercentiles` breaks any caller that asks for
1763
+ // several and indexes them: rocketh requests [10, 50, 80] and reads index 1 and 2,
1764
+ // which came back `undefined` and blew up as "Cannot mix BigInt and other types"
1765
+ // far from here. This node has a flat fee model, so every percentile is the same
1766
+ // value - but the SHAPE has to match the request.
1767
+ const percentiles = Array.isArray(params[2]) ? params[2] : [];
1768
+ const rewardPerBlock = (
1769
+ percentiles.length > 0 ? percentiles : [50]
1770
+ ).map(() => numHex(maxPriorityFeePerGas));
1771
+ return {
1772
+ oldestBlock: numHex(Math.max(0, latestNumber - count + 1)),
1773
+ baseFeePerGas: Array.from({length: count + 1}, () =>
1774
+ numHex(baseFeePerGas),
1775
+ ),
1776
+ gasUsedRatio: Array.from({length: count}, () => 0.5),
1777
+ reward: Array.from({length: count}, () => rewardPerBlock),
1778
+ };
1779
+ }
1780
+
1781
+ case 'eth_sendRawTransaction': {
1782
+ return submit(parseTx(params[0]), false);
1783
+ }
1784
+ case 'eth_sendRawTransactionSync': {
1785
+ // The fast path: send + mine + return receipt in ONE call. Default
1786
+ // behaviour pairs with auto mining (no receipt polling = the latency win).
1787
+ return submit(parseTx(params[0]), true);
1788
+ }
1789
+
1790
+ // ---- Trusted-sender variants (senderMode:'trusted' ONLY) ----
1791
+ // Same as the eth_* pair above but take an explicit `from` and SKIP
1792
+ // ecrecover. `evm_`-namespaced because they are a cheat, not a standard
1793
+ // method: the signature on the wire is never verified.
1794
+ case 'evm_sendRawTransactionAs': {
1795
+ return submit(parseTx(params[0], params[1]), false);
1796
+ }
1797
+ case 'evm_sendRawTransactionSyncAs': {
1798
+ return submit(parseTx(params[0], params[1]), true);
1799
+ }
1800
+
1801
+ case 'eth_getTransactionReceipt': {
1802
+ const r = receipts.get(String(params[0]).toLowerCase());
1803
+ return r ? receiptToRpc(r) : null;
1804
+ }
1805
+ case 'eth_getTransactionByHash': {
1806
+ const t = transactions.get(String(params[0]).toLowerCase());
1807
+ return t ? txToRpc(t) : null;
1808
+ }
1809
+
1810
+ case 'eth_getLogs': {
1811
+ // PERF NOTE: this does a full linear scan + filter over `allLogs` (every
1812
+ // log ever emitted) on EVERY call — O(total_logs) per query, recomputed
1813
+ // each time, no index/cache. `allLogs` is appended in block order. For a
1814
+ // local chain this is fine (in-memory, sub-ms for thousands of logs); it
1815
+ // only matters for a long-lived session with huge log counts + frequent
1816
+ // polling. An optional index (block-range pre-slice / address / topic0)
1817
+ // is deferred — see tasks/slim-node-eth-getlogs-index.md. Keep this scan as
1818
+ // the authoritative semantics if/when an index is added.
1819
+ const f = params[0] ?? {};
1820
+ const from = f.fromBlock != null ? resolveBlockTag(f.fromBlock) : 0;
1821
+ const to =
1822
+ f.toBlock != null ? resolveBlockTag(f.toBlock) : latestNumber;
1823
+ const addrFilter = f.address
1824
+ ? (Array.isArray(f.address) ? f.address : [f.address]).map(
1825
+ (a: string) => a.toLowerCase(),
1826
+ )
1827
+ : null;
1828
+ const topics: (string | string[] | null)[] = f.topics ?? [];
1829
+ const out = allLogs.filter((l) => {
1830
+ if (l.blockNumber < from || l.blockNumber > to) return false;
1831
+ if (addrFilter && !addrFilter.includes(l.address.toLowerCase()))
1832
+ return false;
1833
+ for (let i = 0; i < topics.length; i++) {
1834
+ const want = topics[i];
1835
+ if (want == null) continue;
1836
+ const have = l.topics[i];
1837
+ if (have == null) return false;
1838
+ if (Array.isArray(want)) {
1839
+ if (
1840
+ !want.map((w) => w.toLowerCase()).includes(have.toLowerCase())
1841
+ )
1842
+ return false;
1843
+ } else if (want.toLowerCase() !== have.toLowerCase()) return false;
1844
+ }
1845
+ return true;
1846
+ });
1847
+ return out.map(logToRpc);
1848
+ }
1849
+
1850
+ case 'eth_subscribe': {
1851
+ if (params[0] !== 'newHeads')
1852
+ throw new RpcError(
1853
+ -32601,
1854
+ `subscription type not supported: ${params[0]}`,
1855
+ );
1856
+ // Return an id; consumers using comlink should prefer onNewHead callback.
1857
+ const id = '0x' + Math.floor(Math.random() * 2 ** 48).toString(16);
1858
+ return id;
1859
+ }
1860
+ case 'eth_unsubscribe':
1861
+ return true;
1862
+
1863
+ // ---- account/signing methods are intentionally NOT here ----
1864
+ case 'eth_sendTransaction':
1865
+ case 'eth_accounts':
1866
+ case 'eth_sign':
1867
+ case 'eth_signTransaction':
1868
+ case 'personal_sign':
1869
+ case 'personal_unlockAccount':
1870
+ case 'wallet_addEthereumChain':
1871
+ case 'wallet_switchEthereumChain':
1872
+ throw new RpcError(
1873
+ -32601,
1874
+ `method not supported (execution-only node — sign client-side and use eth_sendRawTransaction): ${args.method}`,
1875
+ );
1876
+
1877
+ default:
1878
+ throw new RpcError(-32601, `method not found: ${args.method}`);
1879
+ }
1880
+ }
1881
+
1882
+ // ---------- dump / load ----------
1883
+ async function dumpState(): Promise<SerializedState> {
1884
+ const accounts: Record<string, string> = {};
1885
+ const code: Record<string, string> = {};
1886
+ const storage: Record<string, Record<string, string>> = {};
1887
+
1888
+ if (stateMode === 'trie') {
1889
+ // Trie mode dumps accounts + code via the touched-account set. NOTE: it does
1890
+ // NOT dump contract STORAGE — the EVM journals storage on an internal
1891
+ // shallowCopy of the state manager that bypasses any interception, and the
1892
+ // trie's own dumpStorage exposes only keccak-HASHED slot keys (not the raw
1893
+ // slots loadState needs). Full-storage persistence is a 'none'-mode feature
1894
+ // (where the live Map IS the committed state). Trie mode is for the REAL
1895
+ // state root (conformance block roots), not for IndexedDB persist.
1896
+ for (const addr of touchedAccounts) {
1897
+ const address = createAddressFromString(addr);
1898
+ const acc = await sm.getAccount(address);
1899
+ if (acc === undefined) continue;
1900
+ accounts[addr] = hex(acc.serialize());
1901
+ const c = await sm.getCode(address);
1902
+ if (c.length > 0) code[addr] = hex(c);
1903
+ }
1904
+ } else {
1905
+ // 'none' mode: the account and code stacks are still plain Maps whose TOP
1906
+ // frame is the live set, and storage is per-account with per-checkpoint
1907
+ // OVERLAYS, flattened by liveStorage(). Dump both directly (no trie walk).
1908
+ //
1909
+ // THE SERIALISED FORMAT IS NOT THE INTERNAL LAYOUT and must not follow it:
1910
+ // this output is persisted data (IndexedDB, loadState fixtures) with existing
1911
+ // state behind it. It stays `{address: {slot: value}}` in 0x-hex, and
1912
+ // `test/storage-overlay.spec.ts` asserts it byte-identical to a dump taken
1913
+ // from the pre-overlay flat layout.
1914
+ const live = sm as OverlayStorageStateManager;
1915
+ const accMap = live.accountStack[live.accountStack.length - 1];
1916
+ const codeMap = live.codeStack[live.codeStack.length - 1];
1917
+ for (const [addr, acc] of accMap) {
1918
+ if (acc !== undefined) accounts[addr] = hex(acc.serialize());
1919
+ }
1920
+ for (const [addr, c] of codeMap) code[addr] = hex(c);
1921
+ for (const [addr, slots] of live.liveStorage()) {
1922
+ for (const [slot, val] of slots)
1923
+ (storage[addr] ??= {})[slot] = hex(val);
1924
+ }
1925
+ }
1926
+
1927
+ const blocks: SerializedBlock[] = [];
1928
+ for (let i = 0; i <= latestNumber; i++) {
1929
+ const sb = blockStore.get(i);
1930
+ if (sb) blocks.push(sb.header);
1931
+ }
1932
+
1933
+ return {
1934
+ version: 1,
1935
+ chainId,
1936
+ stateMode,
1937
+ accounts,
1938
+ code,
1939
+ storage,
1940
+ blocks,
1941
+ receipts: Object.fromEntries(receipts),
1942
+ transactions: Object.fromEntries(transactions),
1943
+ };
1944
+ }
1945
+
1946
+ async function loadState(state: SerializedState): Promise<void> {
1947
+ // Rehydrate accounts/code/storage directly into SimpleStateManager.
1948
+ for (const [addr, accHex] of Object.entries(state.accounts)) {
1949
+ const acc = createAccountFromRLP(hexToBytes(accHex));
1950
+ await sm.putAccount(createAddressFromString(addr), acc);
1951
+ }
1952
+ for (const [addr, c] of Object.entries(state.code)) {
1953
+ await sm.putCode(createAddressFromString(addr), hexToBytes(c));
1954
+ }
1955
+ for (const [addr, slots] of Object.entries(state.storage)) {
1956
+ for (const [slot, val] of Object.entries(slots)) {
1957
+ await sm.putStorage(
1958
+ createAddressFromString(addr),
1959
+ hexToBytes(slot),
1960
+ hexToBytes(val),
1961
+ );
1962
+ }
1963
+ }
1964
+
1965
+ // Rebuild block list / receipts / tx / logs index.
1966
+ receipts.clear();
1967
+ transactions.clear();
1968
+ blockStore.clear();
1969
+ blockByHash.clear();
1970
+ allLogs = [];
1971
+ for (const [h, r] of Object.entries(state.receipts)) receipts.set(h, r);
1972
+ for (const [h, t] of Object.entries(state.transactions))
1973
+ transactions.set(h, t);
1974
+
1975
+ for (const sh of state.blocks) {
1976
+ // THE REBUILT BLOCK CARRIES THE COINBASE AND THE MIXHASH, because it is not
1977
+ // only the RPC that reads it: `eth_call` executes against the STORED `Block`
1978
+ // object of the latest block, so a reconstruction that dropped them would
1979
+ // hand a contract a zero COINBASE / PREVRANDAO after a reload while the same
1980
+ // node's mined blocks used the configured ones. `difficulty` is pinned to 0
1981
+ // here for the same reason it is pinned when mining: post-Merge, PREVRANDAO
1982
+ // lives in `mixHash` and the difficulty must be zero beside it.
1983
+ //
1984
+ // AND ITS OWN HASH HAS TO COME OUT RIGHT, which is the second thing this
1985
+ // list is load-bearing for and the easier one to break. `parentHash` for the
1986
+ // next mined block is taken from THIS object's `hash()` (below), and the
1987
+ // default engine answers BLOCKHASH from it through `mockBlockchain`, so the
1988
+ // header built here must be field-for-field the one `storeBlock` recorded or
1989
+ // a reloaded chain names a parent no lookup resolves. That is an INVARIANT
1990
+ // between three places, not a local property: a header field added to the
1991
+ // mined block in `executeAndMine` has to be recorded in `SerializedBlock` and
1992
+ // restored here, or the hash silently diverges on the far side of a reload.
1993
+ // `test/rpc-block.spec.ts` mines a block after a reload and checks its parent
1994
+ // resolves, which is that invariant stated where a consumer would meet it.
1995
+ const block = createBlock(
1996
+ {
1997
+ header: {
1998
+ number: BigInt(sh.number),
1999
+ gasLimit: BigInt(sh.gasLimit),
2000
+ gasUsed: BigInt(sh.gasUsed),
2001
+ baseFeePerGas: BigInt(sh.baseFeePerGas),
2002
+ parentHash: hexToBytes(sh.parentHash),
2003
+ timestamp: BigInt(sh.timestamp),
2004
+ ...(sh.miner ? {coinbase: createAddressFromString(sh.miner)} : {}),
2005
+ difficulty: 0n,
2006
+ ...(sh.mixHash ? {mixHash: hexToBytes(sh.mixHash)} : {}),
2007
+ },
2008
+ },
2009
+ {common},
2010
+ );
2011
+ // Collect this block's logs from receipts (preserves order).
2012
+ const logs: SerializedLog[] = [];
2013
+ for (const th of sh.transactions) {
2014
+ const r = receipts.get(th);
2015
+ if (r) logs.push(...r.logs);
2016
+ }
2017
+ // A dump from before `SerializedBlock` had a bloom gets one REBUILT rather
2018
+ // than defaulted to zero: its receipts carry their own blooms, so the block
2019
+ // bloom is derivable, and an old state that pre-filtered to nothing would be
2020
+ // the very defect this field was added to close.
2021
+ const header: SerializedBlock =
2022
+ sh.logsBloom === undefined
2023
+ ? {...sh, logsBloom: bloomOfReceipts(sh.transactions)}
2024
+ : sh;
2025
+ blockStore.set(sh.number, {block, header, logs});
2026
+ blockByHash.set(sh.hash, sh.number);
2027
+ allLogs.push(...logs);
2028
+ latestNumber = sh.number;
2029
+ parentHash = block.hash();
2030
+ }
2031
+ }
2032
+
2033
+ // ---------- persistence auto-load on creation ----------
2034
+ if (options.persistence) {
2035
+ const saved = await options.persistence.load();
2036
+ if (saved && saved.chainId === chainId) await loadState(saved);
2037
+ }
2038
+
2039
+ // The dump is taken inside the chain, so it is a snapshot of a settled state,
2040
+ // and the hook is AWAITED inside it too, so a request does not resolve before
2041
+ // its state is durable (`test/persistence-reload.spec.ts` reloads the page on
2042
+ // the strength of that). A request arriving while the hook runs simply queues.
2043
+ async function persistIfNeeded() {
2044
+ if (!options.persistence) return;
2045
+ await options.persistence.save(await dumpState());
2046
+ }
2047
+
2048
+ /**
2049
+ * ARM INTERVAL MINING, once the node is otherwise built.
2050
+ *
2051
+ * COALESCED, which a plain `setInterval` is not. The timer keeps firing while
2052
+ * the chain is busy, so without this a period shorter than the work in flight
2053
+ * (say `intervalMs: 50` against the 209 ms `eth_estimateGas` search ADR 0012
2054
+ * measures) appends a mine per tick and they drain afterwards as a burst of
2055
+ * empty blocks — and if mining outruns the period the queue never stops growing.
2056
+ * At most ONE tick is ever waiting: the flag is cleared when the job STARTS, so
2057
+ * a tick that arrives during a mine still schedules the next one.
2058
+ *
2059
+ * It goes THROUGH the serialisation point like every other way a block gets
2060
+ * mined, because a timer is a concurrency source the consumer never sees: it
2061
+ * fires whenever the event loop reaches it, which before this meant in the
2062
+ * middle of whatever `eth_call` happened to be executing.
2063
+ */
2064
+ let minePending = false;
2065
+ if (miningConfig.type === 'interval') {
2066
+ intervalTimer = setInterval(() => {
2067
+ if (minePending) return;
2068
+ minePending = true;
2069
+ // The flag is cleared as the job STARTS rather than when it finishes, so a
2070
+ // tick arriving during a mine still schedules the next one, and a mine that
2071
+ // THROWS cannot strand the flag and silently stop interval mining.
2072
+ void serialise(() => {
2073
+ minePending = false;
2074
+ return mineBlock();
2075
+ });
2076
+ }, miningConfig.intervalMs);
2077
+ }
2078
+
2079
+ // wrap mine() to persist
2080
+ async function mineAndPersist() {
2081
+ const r = await mineBlock();
2082
+ await persistIfNeeded();
2083
+ return r;
2084
+ }
2085
+
2086
+ // wrap request so state-changing methods persist after mining
2087
+ const baseRequest = request;
2088
+ async function persistingRequest(args: RequestArguments): Promise<unknown> {
2089
+ const out = await baseRequest(args);
2090
+ if (
2091
+ (args.method === 'eth_sendRawTransaction' ||
2092
+ args.method === 'eth_sendRawTransactionSync' ||
2093
+ args.method === 'evm_sendRawTransactionAs' ||
2094
+ args.method === 'evm_sendRawTransactionSyncAs') &&
2095
+ miningConfig.type === 'auto'
2096
+ ) {
2097
+ await persistIfNeeded();
2098
+ }
2099
+ return out;
2100
+ }
2101
+
2102
+ // THE PUBLIC SURFACE, AND THE ONLY PLACE THE LOCK IS TAKEN. Everything above
2103
+ // this line calls the node's internals DIRECTLY and never through here, which is
2104
+ // what makes one promise chain safe: `persistingRequest` reaches `baseRequest`,
2105
+ // `mineAndPersist` reaches `mineBlock` and `persistIfNeeded` reaches `dumpState`,
2106
+ // none of them re-entering a wrapper. Add an entry point below and it must be
2107
+ // serialised too; call one of these wrappers from inside the node and it will
2108
+ // wait for itself forever.
2109
+ //
2110
+ // `dispose` is deliberately NOT serialised: it stops the interval timer and drops
2111
+ // the newHeads subscribers, touches no state, and would be useless at the back of
2112
+ // a queue it is meant to wind down. Note what that does NOT mean: it does not
2113
+ // CANCEL anything already queued. Work accepted before `dispose` still runs to
2114
+ // completion, including a `persistence.save()`, and only the timer stops adding
2115
+ // more. A caller that needs the node quiet should stop issuing requests and await
2116
+ // the ones it holds.
2117
+ return {
2118
+ request: (args: RequestArguments) =>
2119
+ serialise(() => persistingRequest(args)),
2120
+ mine: () => serialise(mineAndPersist),
2121
+ dumpState: () => serialise(dumpState),
2122
+ loadState: (state: SerializedState) => serialise(() => loadState(state)),
2123
+ stateMode,
2124
+ senderMode,
2125
+ // Identity only: the engine object itself stays internal, so the reading is a
2126
+ // plain value that survives a Worker/comlink boundary unchanged.
2127
+ engine: {id: engine.id},
2128
+ async getStateRoot() {
2129
+ if (stateMode !== 'trie') {
2130
+ throw new RpcError(
2131
+ -32004,
2132
+ "no state root in 'none' mode — create the node with stateMode:'trie' for a real Merkle-Patricia root",
2133
+ );
2134
+ }
2135
+ // SERIALISED like the rest, because this one READS BY WRITING: in trie mode
2136
+ // `currentStateRoot` flushes the state manager's cache into the trie, so a
2137
+ // root taken mid-transaction would both report an uncommitted state and
2138
+ // push it into the trie on the way.
2139
+ return serialise(currentStateRoot);
2140
+ },
2141
+ onNewHead(cb) {
2142
+ headSubs.add(cb);
2143
+ return () => headSubs.delete(cb);
2144
+ },
2145
+ async dispose() {
2146
+ if (intervalTimer) clearInterval(intervalTimer);
2147
+ headSubs.clear();
2148
+ },
2149
+ };
2150
+ }