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