diff --git a/.claude/skills/satin-review/SKILL.md b/.claude/skills/satin-review/SKILL.md
index da59e8e49..5f51a5eae 100644
--- a/.claude/skills/satin-review/SKILL.md
+++ b/.claude/skills/satin-review/SKILL.md
@@ -1,29 +1,29 @@
---
name: satin-review
-description: Guide for reviewing the Satin engine pull request (#386) in megaeth-labs/mega-evm, which holds the whole engine now that the stacked pull requests have merged into it. Use when reviewing #386 or the Satin engine, or when the user says "review satin". Gives the scope and the review range, which modules are stable and which #407 still changes, the module map with the invariants to check, the reading order, how to rate a finding, the revert-or-halt rule with its deliberate exceptions, and the decisions already made. Temporary: removed before the Satin pull request merges.
+description: Guide for reviewing the Satin engine pull request (#386) in megaeth-labs/mega-evm, which holds the whole engine: the stacked pull requests merged into it, and #407 merges into it before it is retargeted. Use when reviewing #386 or the Satin engine, or when the user says "review satin". Gives the scope and the review range, the design changes #407 made to what the stacked pull requests describe, the module map with the invariants to check, the reading order, how to rate a finding, the revert-or-halt rule with its deliberate exceptions, and the decisions already made. Temporary: removed before the Satin pull request merges.
---
# Reviewing the Satin engine (pull request #386)
This guide is temporary.
It is deleted before the Satin pull request merges, so nothing else may link to it.
-It is a map: where each part of the engine lives, what to check there, what is still changing, and what is already decided.
-Implementation detail lives in [`AGENTS.md`](../../../AGENTS.md) and the specification in [`docs/spec/upgrades/satin.md`](../../../docs/spec/upgrades/satin.md); this guide links them and does not restate them.
+It is a map: where each part of the engine lives, what to check there, what changed after the stacked pull requests were described, and what is already decided.
+Implementation detail lives in [`AGENTS.md`](../../../AGENTS.md) and the specification in [`docs/spec/upgrades/satin.md`](../../../docs/spec/upgrades/satin.md); this guide links them, and restates a rule only to say what changed.
[`REVIEW.md`](../../../REVIEW.md) is the repository's own review rubric; its consensus-critical list overlaps the checks below.
-The guide describes the code at `cz/feat/satin-w2`; #407 updates it when it merges.
+The guide describes the code at `cz/feat/satin-w2` once #407 has merged into it.
## What is under review
- The Satin engine, in pull request #386 (`cz/feat/satin-w2`), judged at its final state.
- The stacked pull requests #387, #388, #390, #399 and #400 (with #404, merged into #400's branch) have merged into it; each description explains its part as it was merged, and a later part may have changed an earlier one.
+ The stacked pull requests #387, #388, #390, #399 and #400 (with #404, merged into #400's branch) merged into it, and #407 (`cz/feat/satin-w9`) merges into it next; each description explains its part as it was merged, and a later part may have changed an earlier one.
+ "Design changes a reviewer must know" below lists what #407 changed.
- The review range is the pull request's own diff.
Its base, `cz/feat/satin-review-base`, is `satin` before the Satin skeleton: `a8f8c7c9`, the CI-only commit before it.
So GitHub's "Files changed" holds the skeleton (#385) and every later series: the whole engine.
The local equivalent is `git diff a8f8c7c9...
`, `` being the head of #386.
- Most of its deletions are the legacy engine the skeleton removed (183 files): skim them, or hide them with `--diff-filter=d`.
+ Most of its deletions are the legacy engine, its tests and its tools (184 files): skim them, or hide them with `--diff-filter=d`.
- #386 targets the review base only while it is reviewed.
- It is retargeted to `satin` before it merges, after #407 has merged into it, and it must never be merged into the review base.
-- One pull request still changes part of the engine: #407 (`cz/feat/satin-w9` into this branch), which merges before #386 merges into `satin`; see "What is still moving".
+ It is retargeted to `satin` before it merges, and it must never be merged into the review base.
- Judge the final code.
A defect an earlier commit introduced and a later one fixed is not a defect; history only explains why something is as it is.
A test deleted or parked in an intermediate commit is not a finding either: test completeness is judged on the whole.
@@ -31,9 +31,8 @@ The guide describes the code at `cz/feat/satin-w2`; #407 updates it when it merg
Satin is a new spec: simpler semantics win over parity with the legacy engine.
- Out of scope: the legacy engine (`main`, frozen), which runs every block before Satin activates.
Satin never executes or decodes legacy-era data, so "Satin cannot handle legacy data" is not a defect, and code kept only for that purpose is dead code.
-- Fork code: the `megaeth-labs/revm` and `megaeth-labs/op-revm` forks are pinned dependencies with their own review; their diff is not part of this pull request.
- On this branch they are pinned at the tags `v40.0.3-mega.4` and `v20.0.0-mega.3`.
- #407 pins them by commit (`rev`) instead; the fork pull requests megaeth-labs/revm#76 (stacked on megaeth-labs/revm#75) and megaeth-labs/op-revm#8 are the review of those commits.
+- Fork code: the `megaeth-labs/revm` fork at `2fc8edf33b2ffddb195cebc17be9adabfd95417c` and the `megaeth-labs/op-revm` fork at `f599efdabc3e5b36a280f1aa72978751bd64c160`, which the patch blocks pin by `rev`, are pinned dependencies with their own review: megaeth-labs/revm#76, stacked on megaeth-labs/revm#75, and megaeth-labs/op-revm#8.
+ Their diff is not part of this pull request.
A finding about a fork function is about how mega-evm uses it, unless it shows the fork breaking its own documented default behaviour.
The fork functions the engine relies on are listed in [`AGENTS.md`, "Dependencies on the forks"](../../../AGENTS.md#dependencies-on-the-forks).
- Where code belongs: upstream revm first, then the fork, then mega-evm.
@@ -43,32 +42,125 @@ The guide describes the code at `cz/feat/satin-w2`; #407 updates it when it merg
## What is still moving
-#407 changes part of the engine before #386 merges.
-It meters writes and frame starts in the revm fork's instruction hooks on a per-frame byte pool, changes the gas detention and write-record rules with it, and deletes the inspector admission gate.
-The work still to land in it runs inspectors on revm's own inspected lifecycle, removing the engine's inspected copies of the frame lifecycle, its step guard and the inspector's rewrite settlement; gives the pre-block calls one fixed gas budget; and restores the KV and state-growth limits, the 98/100 per-frame shares and the refunds for an account created and destroyed in the same transaction.
-That work also makes a write that crosses a frame's budget and the transaction's limit at once name the budget in its stop.
-Review the stable modules now and a changing one after #407 merges into this branch; if you read a changing module earlier, report a defect only if #407 would not remove it.
-This table is updated when #407 merges.
-Paths are relative to `crates/mega-evm/` unless they start with another top-level directory.
-
-| Module | Files | Status |
-| --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
-| Block executor and block rules | `src/block/` except `limit.rs`, `eips.rs` and `genesis.rs` | Stable, except the inspector admission gate in `executor.rs` and `factory.rs` |
-| System contracts and the system address | `src/system/` except `keyless/`; `crates/system-contracts/` | Stable, except the pre-block call's gas budget in `sequencer_registry.rs` |
-| Pricing | `src/evm/prices.rs`, `src/evm/history.rs`, `src/evm/precompiles.rs`, `src/external/` | Stable |
-| Node surface and the witness | `src/lib.rs`, `src/evm/factory.rs`, `src/evm/state.rs`, `src/test_utils/witness.rs`, `crates/mega-state-test/src/witness.rs` | Stable; `src/lib.rs` drops the exports of what #407 deletes |
-| Tools, benches and CI | `bin/mega-evme/`, `benches/`, `.github/workflows/`, `scripts/`, `mutants/` | Stable; #407 changes how `mega-evme` attaches its tracer and how CI reads a `rev` pin |
-| Limits | `src/limit/`, `src/block/limit.rs`, `src/constants.rs` | Changing: the byte pool replaces the lanes; KV and state-growth limits per transaction, frame and block |
-| Execution and frames | `src/evm/`: `execution.rs`, `context.rs`, `frame.rs`, `host.rs`, `instructions.rs`, `result.rs`, `mod.rs` | Changing: writes and frame starts in the fork's hooks; the per-frame shares; the destruction refunds |
-| Gas detention | `src/access/` | Changing: stipend-funded work is compute; a halting frame's burn is read off the fork |
-| Inspector contract | `src/evm/inspector.rs` and the admission gate | Changing: deleted; inspectors run on revm's inspected lifecycle, and block execution admits any inspector |
-| Keyless deployment | `src/system/keyless/` | Changing |
-| Gas schedule | `src/evm/schedule.rs` | Changing: the history allowance and the frame byte share enter the schedule |
-| Pre-block calls | `src/block/eips.rs` | Changing: one fixed gas budget |
-| Genesis and stateless validation | `src/block/genesis.rs`, `src/evm/validation.rs` | Changing: how a repeated `satinTime`, or one in object form, reads; how intrinsic gas separates history from state |
-| Outcome tooling | `crates/state-test/`, `crates/mega-state-test/` except `src/witness.rs` | Changing: an outcome digest, and runs under tighter limits |
-| Tests | `tests/` of the changing modules, `src/test_utils/neutral.rs` | Changing with them |
-| Specification and guides | `docs/spec/upgrades/satin.md`, `AGENTS.md`, `REVIEW.md` | Changing with the rules above |
+Nothing, once #407 merges into this branch.
+#407 holds everything its description listed as still to be added: inspectors on revm's own inspected lifecycle, a rewritten result taken as given, one fixed gas budget for the pre-block calls, the cleanups, and the KV-update and state-growth limits with their 98/100 frame shares and the destruction table's give-backs.
+It also counts a creator's nonce record when the creation returns, which its description did not list.
+Until #407 merges, the final code of the modules it changes is on its head (`cz/feat/satin-w9`).
+With #407 merged, every module is at its final state for this review: there is no longer a table of stable and changing modules, nor a rule to hold back findings in a changing one.
+What follows this pull request changes no rule.
+The fork pins move from the reviewed commits to the merged commits of megaeth-labs/revm#76 and megaeth-labs/op-revm#8, and to release tags once the line is final.
+Performance work is left for later: the optimisations #407 recorded are made together once the structural work is done, measured against CodSpeed's report.
+
+## Design changes a reviewer must know
+
+The stacked pull requests' descriptions predate #407, which changed parts of what they describe.
+Each change is stated here in plain words with its reason; the specification has the rule and `AGENTS.md` the mechanism.
+
+### Where the engine meets revm
+
+- **Inspectors run on revm's own inspected lifecycle, and the engine has no inspector-specific code.**
+ The engine's inspected copies of the frame lifecycle, its step guard and `src/evm/inspector.rs` are gone: every per-frame mechanism sits in the frame start, run result and return (`frame_init`, `frame_run_result`, `frame_return_result`) that revm's plain and inspected loops share.
+ A result an inspector rewrites is settled by the caller as revm settles it, with no correction of the engine's, and an answer it gives in place of a frame never reaches the engine's frame start, so the depth guard, the interceptors and gas detention see none of it.
+ Block execution admits any inspector.
+ Why: a second copy of the lifecycle had to be kept in step with revm's and made an inspected run differ from a plain one, and which inspectors run on block production is the node's choice.
+- **The fork's loop hooks.**
+ revm's frame run returns an action set on a frame before it runs, without running an instruction or calling the inspector's `step`, and its inspected frame start hands a frame built with one to no `initialize_interp`: a `keylessDeploy` call's creation and answer, and the stop of a caller a child left over a limit, come back through revm's own run.
+ The run-result hook (`EvmTr::frame_run_result`) is called once a frame's run returns, before the inspector's `call_end`, `create_end` and `frame_end` and before `frame_return_result`; gas detention turns a crossing into the stop there, so inspectors and tracers see the stop the caller gets.
+ Why: both are points in the middle of revm's own loop that mega-evm cannot reach from outside, which is what the fork is for, and with them the engine has no frame run of its own.
+- **Writes and frame starts are metered in the fork's instruction hooks.**
+ `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge the opcode makes is made.
+ The four calls and the two creations call `frame_starting` once the forward is taken: the caller is charged the history of the start's records out of what it kept, and the frame's own part is declared on the start (`FrameStart::charge`) for the fork to refund when the frame fails.
+ Why: a write the opcode's own failure takes back is never counted, and the engine no longer rebuilds revm's state from outside with instruction wrappers.
+
+### What is counted
+
+- **Data size, KV updates and state growth are pools on revm's gas tracker.**
+ Each is a pool on every frame's `GasTracker`, which the fork forwards to a child at a start and settles on the child's return as it settles the EIP-8037 reservoir; the transaction's limits are held beside the pools, on what the transaction keeps.
+ The engine's per-frame record lanes, its journal wrapper and its ledger are gone, and the context's journal is revm's own.
+ Why: a frame's budget then fails and succeeds with the frame's own gas, by revm's settlement, instead of a second account kept beside the journal.
+- **Write records follow the net change.**
+ An account's record exists while its nonce, balance or code differs from what the transaction loaded, and a slot's while its value differs from its original.
+ The per-frame deduplication is gone, a `SELFDESTRUCT` records the account it clears as well as its beneficiary, and a creation is charged exactly the records it makes.
+ Why: the record measures the state the transaction keeps, by revm's own notion of a change; the per-frame count over-counted, and charged history gas for writes that leave nothing.
+- **A frame start is held to the limits once revm decided it.**
+ Its records and transfer log are read off the journal before revm decides the start, and counted on the started frame's pools once it has.
+ A frame revm built returns the stop before its first instruction, and an answer revm gave without building a frame gives way to the stop on the untouched forward, a success's value move taken back.
+ A creation onto an occupied address fails on the collision, and is not stopped for what its start would count.
+ Why: the limit judges what the start did, instead of a prediction of revm's refusals that duplicated revm's rules in the engine; the opcode's history charge is still priced from the journal's state before revm decides, which on the plain path is exact because the opcode makes revm's refusal checks first.
+- **A creator's nonce record is counted on the creator when the creation returns with the nonce bumped.**
+ The creation's budget is the share taken at the opcode, before that record, which is Rex6's order.
+ The record is held to the creator's budget, not the creation's, and survives the creation's failure; a keyless signer's is counted on the call at its settlement, and the keyless creation's share is of the call's whole pools, which the call draws nothing from before it.
+ The frame-start hook only prices: it charges the start's history and counts nothing (`hold_creator` in `src/evm/execution.rs` counts the record).
+ A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, its declared part coming back only as for any start whose frame keeps nothing, and its records are those revm then made; the specification says nothing of inspectors, and `AGENTS.md` states this.
+ Why: the bump is a fact only once revm made it, and the creator's pools are in reach again only at the return, so nothing is counted before revm decides and nothing has to be given back.
+- **A frame a failure below it left over the transaction's limit is stopped as it resumes.**
+ A failed frame's counts go back to what the frames kept when it started, a record of theirs it took back included, while an Oracle hint it admitted stays counted; a hint sent into the room such a take-back freed leaves the transaction over its data-size limit, and the frame it returns into returns the transaction's stop before its next instruction (`AdditionalLimit::hold_caller`), whether the frame below reverted, halted or was itself stopped.
+ Why: without it a caller that catches the failure could end the transaction above its limit.
+- **KV updates and state growth are limited again**, per transaction (`TX_KV_UPDATE_LIMIT` = 500,000 write records, `TX_STATE_GROWTH_LIMIT` = 1,000 new accounts and slots), per frame (98/100 of what the parent has left) and per block (`BLOCK_KV_UPDATE_LIMIT` = 500,000, `BLOCK_STATE_GROWTH_LIMIT` = 1,000, packing budgets as the block's data size is).
+ The KV count is the write-record count.
+ State growth rises by one where EIP-8037 charges the state gas of one new account or slot, and for the caller a failed deposit creates, which pays no state gas; it falls when a slot whose original is zero is written back to zero; a frame's net is signed, and a negative net never enlarges a child's budget.
+ An EIP-7702 list that would cross either limit is skipped whole, and the transaction's own frame is stopped before it runs.
+ Why: these are Rex6's limits, and gas does not stand in for the count: 1,000 fresh slots cost 97,920,000 state gas, which a gas limit can cover; at Satin's constants data size binds before the KV count, and the KV check is still made.
+- **The destruction table.**
+ The first effective `SELFDESTRUCT` of an account created in the same transaction gives back what the transaction made of it: each part absent at the transaction's start and present before the destruction — the account leaf, its deployed code, each slot written non-zero — is refilled at the state gas it was charged, to the destroying frame; the leaf and each such slot lower state growth by one and have their write records and those records' history taken back, and the code's data size and history gas are taken back.
+ A slot's value at the start is its original in the transaction, so a slot of the created account first accessed after the creation is zero there whatever the state held; a leaf is absent when no account stood at the address: the database answered none (`None`, not an empty account), or an earlier transaction on the same journal destroyed it (`Accounts::was_absent_at_start` in `src/limit/record.rs`).
+ A part present at the start is an ordinary deletion; a failure of the destroying frame, or of a frame that contains it, discards all of it.
+ From the mark the account adds no further state growth or record, and every state charge on it is priced at nothing (`Host::state_gas_price`), so a later `SSTORE` or a deposit of its constructor's code is never charged state gas rather than charged and refilled; the table's own give-back prices outside that rule (`MegaContext::priced_state_gas`).
+ The neutral configuration counts the table and prices state gas as the fixture's fork does, which gives none back, so equivalence mode's transactions that create and destroy an account report other usage than before the table, and nothing else differs.
+ The op-revm baseline pins the divergence (`test_a_creation_that_destroys_itself_diverges_from_op_revm`).
+ Why: a part the transaction made does not remain for a node to store, so the count and the charge stay aligned; EIP-8037 refills nothing for this destruction and Rex6 refunded no storage gas, so this departs from both on purpose.
+- **A fact about a transaction's start is read off that transaction's journal.**
+ revm's account flags of a database load (`LoadedAsNotExisting`), of a touch and of a destruction are set once per journal and outlive the transaction that set them when a journal runs several transactions without finalizing; the engine reads such a fact with what the journal records of the running transaction — the original info, the transaction id of what it loaded, its entries (`JournalEntry::AccountDestroyed`'s status, `AccountTouched`) and the local created and destroyed flags — and never off such a flag alone.
+ So what the engine decides on such a journal follows what revm charges there, as it does on a fresh one: the destruction table's leaf, the keyless empty-deposit rule and its answer (`Accounts::is_destroyed`), and the authorities an EIP-7702 list created (`applied_authorities` in `src/evm/execution.rs`, which counts one where revm charged it a new account).
+ Why: a node's block executor finalizes each transaction, but `transact_one` on the public API does not, and a count must not part from its charge on either path.
+
+### Gas
+
+- **The 98/100 forwards.**
+ A call or a creation forwards at most `remaining − remaining × 2 / 100` of the caller's regular gas, in place of EIP-150's 63/64 (the schedule's `call_stipend_reduction`, 50), and a value call's 2,300 stipend is added after the cap.
+ Every child receives `remaining − remaining × 2 / 100` of the caller's reservoir, whatever regular gas the call asks for; the transaction's own frame and a system call's outermost frame take the whole reservoir, and a keyless deployment's creation forwards `min(gasLimitOverride, remaining)` of regular gas with the reservoir share.
+ The three pools give a child `remaining × 98 / 100`, rounded down, so the two formulas differ at some values.
+ Why: the regular forward is Rex6's, and the reservoir share keeps a caller's own work within reach of what it calls, since state and history gas draw the reservoir first; EIP-8037 passes the reservoir whole, which would let a callee spend all of it.
+- **The history allowance replaces the storage-gas stipend.**
+ A value `CALL` or `CALLCODE` below the transaction's own frame gives the frame it starts 160 bytes of history (`HISTORY_ALLOWANCE_BYTES`, 14,080 gas at the cost per history byte, the schedule's `call_history_allowance`), on which only a log's history charge draws.
+ It never enters the frame's gas and is on no ledger.
+ Why: a `receive()` reached through Solidity's `transfer()` can still emit one event, and an allowance that is not gas leaves nothing to burn on return.
+- **One fixed gas budget for the pre-block calls.**
+ Each runs on `PRE_BLOCK_CALL_GAS_LIMIT` = 31,566,720, whatever the block's gas limit: 30,000,000 of regular gas and a reservoir of sixteen fresh slots at the minimum bucket.
+ Why: a pre-block call does not draw on the block's gas; Rex6's `max(block gas limit, 30,000,000)` was widened for storage gas a crowded bucket multiplied, which a system call no longer pays; a pre-block call on MegaETH's chains writes at most six fresh slots, and none of the three contracts reads `GAS`.
+
+### Gas detention
+
+- **Compute counts the work run on a value call's stipend, and never what a halting frame burns.**
+ The stipend is not forwarded gas, so what a callee runs on it is compute, and what it leaves of it does not lower compute when it comes back.
+ What a halting frame burned is read off the fork's failed-charge record and is not compute, so no halt takes a detained transaction past its limit.
+ Why: the old figure let a callee spend the stipend uncounted after a read, and counting the gas a halting frame had left overshot the limit.
+- **A value call's own charges come first.**
+ Its static 100, its memory, the 11,300 value transfer and a cold access are decided as any opcode's charges are, and one that crosses the limit stops the calling frame before anything moves, whether or not the caller can fund the value; only then is a precompile decided from its price.
+ Why: an opcode's own charges are held where they are made, and the outcome must not depend on whether the value could be funded; the specification now says so where it states the precompile exception.
+- **The volatile-data rules.**
+ `BLOBHASH` is not volatile: it reads the transaction's own blob hashes.
+ `SLOTNUM` is a read of the block environment, and its refusal carries access type 12, which the contract's enum does not declare, so a handler decodes the argument as a `uint8`.
+ A call to the EIP-2935 history contract is a read of the block environment, through the `NUMBER` its `get` path executes before it loads the slot; an `SLOAD` of the storage the EIP-2935 and EIP-4788 pre-block calls wrote is state the block starts with, and is no read.
+ A `CREATE` or `CREATE2` is neither marked nor refused for loading its creator or created address, the block beneficiary included.
+ Why: volatile data is data the block, the sequencer or the oracle changes under the transaction; the blob hashes are the transaction's own, the history contract's answer depends on the block number it reads, the pre-block storage is fixed before the first transaction, and a creation's loads are the creation opcode's own checks under EIP-8037, as a value call's check of its caller's balance is.
+
+### The stop and the configuration
+
+- **Limit stops are revert-class in four dimensions, in a fixed order.**
+ A crossing of data size (kind 0), KV updates (kind 1), state growth (kind 3) or gas detention's compute limit (kind 2) reverts the crossing frame with `MegaLimitExceeded(kind, limit)`, and its caller may catch it.
+ An operation that crosses several counted dimensions at one site stops on the first of data size, KV updates, state growth; compute is decided at the regular charge, before the write is counted.
+ Inside a dimension the frame budget is tested first, and the stop names the budget whenever the budget is crossed, the transaction limit only when it is not.
+ Why: the order across dimensions and the discriminants are Rex6's, so a Rex6 decoder reads the stop, and a frame that crosses its budget is told the budget it crossed.
+- **Limits files of the first shape still run.**
+ A limits file written before the KV-update and state-growth limits returned, such as one given to `mega-evme --override.limits`, reads with the default spec's values for the four newer fields; every field that shape had stays required, and an unknown field is refused.
+ Why: a tool's existing files keep working; consensus never reads such a file.
+- **Smaller changes of the node surface.**
+ A Satin key given twice in a genesis `config` object is read as its last copy by every reader, because a node and the reference CLI parse the file into a JSON value that keeps only the last copy.
+ `satinTime` is also read from `{"$serde_json::private::Number": ""}`, decimal digits alone, the form `serde_json` hands a number over in with `arbitrary_precision` on.
+ A witness replay's exports must be a subset of the building node's and may be a proper one, because the building node's also hold what candidates it executed and dropped asked for.
+ Satin's configuration fixes off the fork's switch back to revm 40.0.3's journal semantics, which exists for the legacy engine.
+ The handler splits a system call's gas itself, at most `SYSTEM_CALL_REGULAR_GAS_LIMIT` = 30,000,000 of it regular, and reads the reservoir a result settled with (`AdditionalLimit::reservoir_remaining`), which the fork no longer does.
## Running the checks
@@ -80,35 +172,41 @@ Four notes that are easy to miss:
- after any test change, run `scripts/price_grid.sh --pr`;
- the execution-spec gate needs Ethereum's fixture releases, at the versions `.github/workflows/exec-spec-satin.yml` downloads.
-Evidence that a change alters no result: `state-test --mode satin --json-outcome` at two commits, detached, sorted and compared byte for byte, plus the gates and the byte-price grid.
+Evidence that a change alters no result: `state-test --json-digest` at two commits, detached, over both fixture releases, in equivalence mode, in Satin mode and in Satin mode under tighter limits (the `--limit-*` options), each sorted and compared byte for byte, plus the gates and the byte-price grid.
+The digest hashes each transaction's whole outcome, its gas by ledger and its usage counts included, so it catches a shift between ledgers that `--json-outcome` does not.
A golden or snapshot changes only for a stated reason: regenerate it and read the diff.
## Reading order
-1. The consensus core: limits (the vocabulary of lane, stop and crossing), then execution and frames with gas detention, then the block executor, then the system contracts and system address.
+1. The consensus core: limits (the vocabulary of pool, record, stop and crossing), then execution and frames with gas detention, then the block executor, then the system contracts and system address.
2. The gas schedule and pricing.
3. The inspector contract.
4. The node surface, validation and the witness.
-5. Tools, tests, goldens and CI. Skim the goldens and snapshots; read what changes them.
+5. Tools, tests, goldens and CI.
+ Skim the goldens and snapshots; read what changes them.
-Until #407 merges, take the stable modules of the table above first, in this order, and the changing ones after it.
Skim without reading: the SALT bucket-hasher internals, the generated pricing table, the tracer snapshots, the receipt goldens and the keyless differential digest.
-The module documentation at the top of the main source files states the same invariants as the lists below, often more exactly; each entry names which to read first.
+The module documentation at the top of the main source files states the same invariants as the lists below, often more exactly; where an entry names what to read first, start there.
A test name or a line count is not a reason to trust the code: read the code against the spec.
## Glossary of the terms the checks use
- **Live system address**: the address the `SequencerRegistry` names (`_currentSystemAddress`).
- `MEGA_SYSTEM_ADDRESS` in code is only the default a test's registry names (`test_utils::MemoryDatabase::sequencer_registry`).
+ `MEGA_SYSTEM_ADDRESS` in code is only the address the registry named when Rex5 created it, which a chain's registry holds until a rotation.
- **Pre-block caller**: `0xff…fe`, the EIP-4788 system address, the caller of the pre-block system calls.
It is a different address from the live system address.
- **MST** (Mega System Transaction): a signed legacy transaction from the live system address to a whitelisted system contract (today the Oracle), promoted to a deposit by the engine.
- **System-originated** (spec §19, `originates_from_the_protocol` in `src/system/tx.rs`), decided from the transaction's own fields:
an MST before or after promotion; any transaction whose caller is the pre-block caller; any deposit carrying the source hash the promotion stamps, `keccak256("MEGA_SYSTEM_TRANSACTION")`, whoever sends it.
- Such work is exempt from history gas, per-transaction limits and detention, and priced at the minimum bucket.
-- **Lane**: the per-frame record of data size and write records; a success merges into the caller's lane, a failure discards it.
-- **Stop**: what a limit does. The frame that crosses it reverts with `MegaLimitExceeded(kind, limit)`, its caller resumes and may catch it.
-- **Answered frame**: a frame that gets a result without running (an interceptor, the engine, an inspector's hook).
+ Such work is exempt from history gas, every per-transaction limit and frame budget, and detention, and priced at the minimum bucket; its usage is still counted.
+- **Pool**: a frame's budget in data size, KV updates or state growth, held on its `GasTracker`; the fork forwards a child its share at the start and settles the child's pools on its return, as it does the reservoir.
+- **Write record**: one per account or storage slot the transaction keeps changed, by the net change; 40 bytes of data size and of history; the KV count.
+- **State growth**: the net count of new accounts and new slots the transaction keeps.
+- **Stop**: what a limit does.
+ The frame that crosses it reverts with `MegaLimitExceeded(kind, limit)`, and its caller resumes and may catch it.
+- **Answered frame**: a frame that gets a result without running (a precompile, a call to an account with no code, an interceptor, the engine, an inspector's hook).
+- **Start charge**: the history gas a frame start charges its caller for the records the started frame makes, declared on the start and refunded by the fork when the frame fails.
+- **Failed-charge record**: the regular gas a frame had before a charge that failed, which the fork keeps, so the engine knows exactly what a halting frame burned.
- **Byte-price grid**: the CI job that runs the suite at other costs per state and history byte, because the prices are provisional.
## Module map
@@ -116,64 +214,82 @@ A test name or a line count is not a reason to trust the code: read the code aga
Paths are relative to `crates/mega-evm/` unless they start with another top-level directory.
For each module: where it is, what to check, the spec sections, and the `AGENTS.md` subsection with the detail.
-### Limits: data size, write records, the stop (changing in #407)
+### Limits: data size, KV updates, state growth, the stop
-- **Where:** `src/limit/` (byte table, `LimitKind`, `AdditionalLimit`, `FrameLimitTracker`, `Lane`, `StagedRecord`), `src/block/limit.rs` (`ProtocolLimits::for_spec`), `src/constants.rs`.
-- **Read first:** the module docs of `src/limit/mod.rs` and `src/limit/limit.rs`.
+- **Where:** `src/limit/` (the byte table, `LimitKind`, `LimitCheck`, `MegaLimitExceeded` and `EvmTxRuntimeLimits` in `mod.rs`; the write records and the state growth a write and a frame start make in `record.rs`; `AdditionalLimit` in `limit.rs`), `src/block/limit.rs` (`ProtocolLimits::for_spec`, `BlockLimits`, `BlockLimiter`), `src/constants.rs`.
+- **Read first:** the module doc of `src/limit/mod.rs` and the doc of `AdditionalLimit` in `src/limit/limit.rs`.
- **Check:**
- - A record is counted where it is made and taken back with its frame; the one exception is a failed creation's creator-nonce record, which lands on the creator and is held to the creator's limits.
- - The transaction limit is checked before the frame budget, at one site (`AdditionalLimit::check`); every stop comes from `AdditionalLimit::crossed`, which also applies the exemption of system-originated work.
- - A caller resumed after its child's crossing is held to what the transaction has left, and stops in turn if a charge of its own crosses again.
- - `LimitKind` keeps its encoding: data size 0, compute gas 2, and `from_u8` answers `None` for 1 and 3.
- - Limits are per-spec constants, never chain configuration; a bare `MegaContext` defaults to them; `BlockLimits` is builder policy and can only tighten.
- - Nothing limits the KV count, state growth or the block's execution gas; the ledgers and `BlockGasCounters` report them.
+ - A count is drawn where it is made, on the pool of the frame that makes it (`AdditionalLimit::draw`), and a failed frame's draws go back with its gas.
+ - The transaction's limits are held beside the pools, on what the transaction keeps (`AdditionalLimit::usage`): the body, the hints, the authorities' records and the accounts they created, a deposit's created caller, and what the frames keep, restored when a start's frame keeps nothing (`AdditionalLimit::close_start`).
+ - A completed write and a decided start are held in one function (`AdditionalLimit::check`, through `draw`, `count_start` and `hypothetical_start`): in the order data size, KV updates, state growth (`limit::COUNTED`), the frame budget, then the transaction limit; a hint, the authorization list and a caller's hold at a child's return check the same limits directly.
+ - The stop names the budget when the budget is crossed, and the transaction limit only when it is not, which a framed write reaches only in data size, after Oracle hints used what the transaction had left; a start names it too when a deposit-like transaction's created caller stands on a state-growth limit of nothing, which only a tool's limit sets.
+ - Every stop comes from `AdditionalLimit::crossed`, which also applies the exemption of system-originated work and system calls.
+ - A write record follows the net change: an account's while its nonce, balance or code differs from what the transaction loaded, a slot's while its value differs from its original; the sender's account and the fee credits the settlement makes are the body's, not records.
+ - A creator's nonce record is counted on the creator when the creation returns with the nonce bumped, held to the creator's budget, and survives the creation's failure; the creation's budget is the share taken at the opcode, before it.
+ - State growth rises by one at each EIP-8037 account-leaf or fresh-slot charge site and for the caller a failed deposit creates, and a slot written from an original zero back to zero falls by one; a frame's net is signed, a negative net never enlarges a child's budget (`cap_the_shares` in `src/evm/execution.rs`), and a transaction reports `max(net, 0)`.
+ - The first effective `SELFDESTRUCT` of an account created in the transaction applies the destruction table: each part absent at the transaction's start (a slot by its original in the transaction, a leaf by no account standing there) and present before the destruction is refilled at the price it was charged, to the destroying frame, the leaf and each such slot lower state growth by one and lose their write records, and the code's data size and history gas are taken back; from the mark the account adds no further state growth, state gas or write record, and a failure of the destroying frame, or of a frame that contains it, discards it all.
+ - A caller resumed after its child's crossing is held to what the transaction has left, and stops in turn if a count or a charge of its own crosses again; a caller a failure below it left over the transaction's data-size limit, a hint having filled room a take-back freed, returns the transaction's stop before its next instruction (`AdditionalLimit::hold_caller`).
+ - `LimitKind` keeps Rex6's encoding: data size 0, KV updates 1, compute gas 2, state growth 3.
+ - Limits are per-spec constants, never chain configuration; a bare `MegaContext` runs under them; `BlockLimits` is builder policy and can only tighten.
- `KV × 40 ≤ data size` holds after every instruction.
+ - An EIP-7702 list long enough to cross the KV-update or state-growth limit is simulated whole before the first frame, writing and warming nothing; one that would cross is skipped whole, and the transaction's own frame is stopped before it runs (`hold_authorization_list` in `src/evm/execution.rs`); a shorter list cannot cross and is applied as EIP-7702 applies it.
- A hint that would cross the limit is neither counted nor forwarded; an admitted hint stays counted through any stop.
-- **Spec:** §7, §10, §11, §19, §20. **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer).
+- **Spec:** §7, §10, §11, §19, §20.
+- **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer).
-### Execution and frames (changing in #407)
+### Execution and frames
-- **Where:** `src/evm/execution.rs` (`MegaHandler`, the frame lifecycle), `src/evm/context.rs` (`MegaContext`, `spec_cfg`, `admit_code_deposit`), `src/evm/mod.rs`, `src/evm/host.rs`, `src/evm/state.rs`, `src/evm/instructions.rs`, `src/evm/frame.rs`, `src/evm/result.rs`.
-- **Read first:** the module docs of `src/evm/execution.rs` and `src/evm/host.rs`.
+- **Where:** `src/evm/execution.rs` (`MegaHandler`; `MegaEvm`'s frame start and return, `frame_init` and `frame_return_result`, and the run-result hook `frame_run_result`), `src/evm/host.rs` (the completed-write and frame-start hooks), `src/evm/context.rs` (`MegaContext`, `spec_cfg`, `admit_code_deposit`), `src/evm/mod.rs`, `src/evm/state.rs`, `src/evm/instructions.rs`, `src/evm/frame.rs`, `src/evm/result.rs`.
+- **Read first:** the docs of `frame_init` and `frame_return_result` in `src/evm/execution.rs`, and the module doc of `src/evm/host.rs`.
- **Check:**
- - The Host only observes; a staged record is committed after the opcode completes and dropped when it fails.
+ - A write is counted in the Host's completed-write hook (`write_completed`), which revm calls only once the opcode made every charge, so a failed opcode counts nothing; the Host's write methods count nothing, whoever calls them.
+ - A completed write's record is held to the limits before its history is charged, so a record a limit refuses is not charged; at a frame start the order is the other way round, the caller paying at its opcode before revm decides the start and its records are held.
+ - The frame-start hook (`frame_starting`) charges the caller the history of the start's records after the forward is taken, out of what the caller kept, and declares the frame's own part on the fork's start (`FrameStart::charge`); a caller that cannot pay gets the forward back, the halt's record re-written, and starts no frame.
+ - A start's records and transfer log are read off the journal before revm decides the start (the engine's `FrameStart::of` in `src/evm/execution.rs`) and counted on the started frame's pools once it has (`AdditionalLimit::count_start`); a start revm refuses on its caller's account counts nothing and is charged nothing.
+ - A frame revm built whose start crossed a limit ends with the stop before its first instruction (`end_before_it_runs`); an answer revm gave gives way to the stop on its untouched forward, and a success's value move and log are taken back to the start's journal mark (`stop_the_answer_at`, `take_back_a_stopped_answer`).
- Pre-frame charges (a deposit's caller account, EIP-7702 authorities, pre-frame records) either succeed or leave an included out-of-gas halt without a frame, with the journal unwound as revm unwinds it (a creation keeps its nonce bump).
- - A frame whose start would cross a limit is answered with the stop before it is built, so no value moves; `take_back_a_stopped_answer` takes back what an answer rewritten into a crossing had moved.
- - A frame start is counted before revm decides the frame, by predicting its refusals (`caller_refuses_start`, `assert_start_as_counted`); #407 replaces the prediction.
- A deposit that fails validation or cannot pay a pre-frame charge is included as a failed deposit: whole gas limit used, mint credited, nonce bumped.
- - `spec_cfg` fixes the configuration whatever the caller passes (Satin schedule, EIP-8037, EIP-2780, execution cap 200,000,000, EIP-7708, chain-id check on).
- - Per-transaction state resets with the transaction; a system call has its own entry point and reservoir split.
-- **Spec:** §3, §4, §5, §9, §11, §14, §21. **Detail:** [`AGENTS.md`, "How Satin executes today"](../../../AGENTS.md#how-satin-executes-today).
+ - The forwards: regular gas `remaining − remaining × 2 / 100`, plus a value call's stipend after the cap; the reservoir by the same subtraction, the transaction's own frame and a system call's outermost frame taking the whole; each pool `remaining × 98 / 100`, rounded down.
+ - `spec_cfg` fixes the configuration whatever the caller passes (Satin schedule, EIP-8037, EIP-2780, execution cap 200,000,000, EIP-7708, chain-id check on, the contract size limit at 512 KiB and the initcode size limit at 1 MiB, the fork's legacy journal semantics off).
+ - Per-transaction state resets with the transaction; a system call has its own entry point, and the handler splits its gas (`MegaHandler::tx_gas`).
+ - A fact about the transaction's start is read with what the journal records of the transaction (its original info, its entries, its transaction id), never off an account flag revm sets once per journal alone, so on a journal that runs several transactions unfinalized the engine's counts follow what revm charges there.
+- **Spec:** §3, §4, §5, §9, §10, §11, §14, §21.
+- **Detail:** [`AGENTS.md`, "How Satin executes today"](../../../AGENTS.md#how-satin-executes-today).
-### Gas detention (changing in #407)
+### Gas detention
-- **Where:** `src/access/` (`Detention`, `VolatileDataAccess`), the volatile-read wrappers in `src/evm/instructions.rs`, `hold_precompile` and `settle_answer` in `src/evm/execution.rs`, the switch in `src/system/control.rs`.
-- **Read first:** the module doc of `src/access/detention.rs`.
+- **Where:** `src/access/` (`Detention`, `VolatileDataAccess`), the volatile-read wrappers in `src/evm/instructions.rs`, the loads the Host marks or refuses in `src/evm/host.rs`, `hold_precompile`, `settle_answer` and `end_frame` in `src/evm/execution.rs`, the switch in `src/system/control.rs`.
+- **Read first:** the module doc of `src/access/mod.rs`.
- **Check:**
- The split into spendable and withheld gas is applied when a read completes, when a frame starts or resumes, and after an `SSTORE`; only regular charges are held to the spendable part, every other reader sees both.
- - The withheld part goes back to the sender unspent.
- - A crossing leaves the frame's gas as it was before the charge and stops the frame with `MegaLimitExceeded(2, limit)`; the caller gets everything the frame had.
- - A precompile is decided from its price before it runs; one outside the Satin set runs on the allowance.
+ - The withheld part goes back to the sender unspent, except from a failed deposit.
+ - A crossing is classified in the run-result hook (`frame_run_result`, `Detention::on_frame_end`), and only on an out-of-gas: the frame's gas is put back to what it was before the charge, the frame stops with `MegaLimitExceeded(2, limit)`, and its caller gets everything the frame had.
+ - Compute is every regular charge the frames make, the work run on a value call's stipend included, less the state and history gas that spilled onto regular gas, and less what halting frames burned, which is read off the fork's failed-charge record.
+ - A value call's own regular charges are decided first, and stop the calling frame if they cross; a precompile is then decided from its price before it runs, and one the engine cannot price runs on the allowance.
+ - What is volatile: the block environment (`SLOTNUM` and `BLOCKHASH` among it, `BLOBHASH` not), the block beneficiary's account, the Oracle's storage; a call to the EIP-2935 history contract reads the block number, and a `CREATE`'s loads of its creator and created address are no reads.
- A system-originated transaction and a system call are never detained.
- - Compute today excludes what a callee spends of a value call's 2,300 stipend and counts a halting frame's leftover through the halt-noting machinery; #407 changes both, so report a defect in the current rules only if that change would not remove it.
-- **Spec:** §12, §13. **Detail:** [`AGENTS.md`, "Gas detention"](../../../AGENTS.md#gas-detention).
+- **Spec:** §12, §13.
+- **Detail:** [`AGENTS.md`, "Gas detention"](../../../AGENTS.md#gas-detention).
-### Block executor and block rules (stable, except `limit.rs`, `eips.rs` and the inspector gate)
+### Block executor and block rules
- **Where:** `src/block/` (`executor.rs`, `limit.rs`, `result.rs`, `eips.rs`, `l1_block_info.rs`, `factory.rs`, `helpers.rs`).
- **Read first:** the module doc of `src/block/executor.rs`.
- **Check:**
- The activation-block rule is caller-set (`no_user_tx_activation_block`, default `false`); `MegaHardforks::admits_only_deposits` is what a builder computes it from.
- A transaction is an MST when it is a legacy transaction of the system shape from the live system address, decided before it runs; a failed read of the address is an internal error.
- - A deposit and an MST are never refused by the packing budget or building policy and count towards them; the header gas limit (`BlockLimiter::pre_execution_check`) and the DA footprint (`check_da_footprint`) still apply.
- - `commit_transaction_outcome` refuses a stale outcome: the sender's nonce or balance moved since the candidate executed (`StaleOutcome`, internal).
- - Pre-block order: EIP-2935, EIP-4788, in Satin's activation block alone the check of the six system contracts and the EIP-7997 factory, the registry's due change, the read of the L1 block info; a pre-block call that does not succeed makes the block invalid, and a fatal database error is an internal error.
- - A rewriting inspector is refused at every block-execution entry, as an internal error (#407 deletes the gate).
- - The block's ledgers: regular as `max(regular, floor)`, state, history, plus history bytes, data size and write records; reported, not limited (#407 adds block limits on KV and state growth).
+ - The block's packing budgets are data size 13,107,200, KV updates 500,000 and state growth 1,000, checked in that order before a transaction runs (`BlockLimiter::pre_execution_check`): the transaction that reaches one is packed, and every later ordinary transaction is refused.
+ - A deposit and an MST are never refused by the packing budgets or building policy and count towards them; both are held to the header gas limit (`BlockLimiter::pre_execution_check`), and an MST, a legacy envelope, to the DA footprint (`check_da_footprint`), which a deposit is exempt from.
+ - `commit_transaction_outcome` checks the counters again and refuses a stale outcome: the sender's nonce or balance moved since the candidate executed (`StaleOutcome`, internal).
+ - Pre-block order: EIP-2935, EIP-4788, in Satin's activation block alone the check of the six system contracts and the EIP-7997 factory, the registry's due change, the read of the L1 block info.
+ - Every pre-block call runs through one helper (`transact_pre_block_call` in `eips.rs`) on `PRE_BLOCK_CALL_GAS_LIMIT`, whatever the block's gas limit; one that does not succeed makes the block invalid, and a database error the database declares fatal is an internal error.
+ - The pre-block calls count towards no block budget.
+ - Block execution admits any inspector; the node decides which run on block production.
+ - The block's counters: regular gas as `max(regular, floor)`, state and history gas, history bytes, data size, write records and state growth; the three gas ledgers are reported, not limited.
- When the OP base moves, diff the file against the new base's `OpBlockExecutor`.
- **Spec:** §1, §18, §19, §20, §21.
-### System contracts and the system address (stable, except keyless)
+### System contracts and the system address
- **Where:** `src/system/` (`intercept.rs`, `oracle.rs`, `control.rs`, `limit_control.rs`, `keyless/`, `tx.rs`, `predeploys.rs`, `sequencer_registry.rs`), `crates/system-contracts/`.
- **Read first:** the module doc of `src/system/tx.rs`.
@@ -181,64 +297,84 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS.
- Every transaction reads the registry's account and its `_currentSystemAddress` slot, warm, by comparing the code hash, without running the registry's code.
- A transaction from the live system address without the system shape is invalid; a deposit from it, which never has the shape, is a failed deposit, including one carrying the MST source hash.
- A deposit carrying the MST source hash from any **other** sender is not refused: it is system-originated, so it is held to no limit, pays no history gas, is not detained and is priced at the minimum bucket.
- The spec's basis is that no deposit derived from L1 carries the hash. This is the widest exemption in the engine, so check that claim.
+ The spec's basis is that no deposit derived from L1 carries the hash.
+ This is the widest exemption in the engine, so check that claim.
- An MST is validated (chain id, nonce, EIP-3607) before it is promoted to a deposit.
- - Satin deploys, upgrades and seeds no predeploy. The block in which Satin activates (`MegaBlockExecutionCtx::satin_activation_block`, set by the node from its schedule and the parent's timestamp) reads the seven, each a read-only entry, and each must hold exactly Satin's code whatever its nonce, balance and storage; anything else — no account, no code, an older version (the Oracle's 1.0.0 / 1.1.0, the registry's 1.0.0), other code — makes the block invalid with one error, `UnexpectedSystemContractCode`. No other block reads them.
+ - Satin deploys, upgrades and seeds no predeploy.
+ The block in which Satin activates (`MegaBlockExecutionCtx::satin_activation_block`, set by the node from its schedule and the parent's timestamp) reads the seven, each a read-only entry, and each must hold exactly Satin's code whatever its nonce, balance and storage.
+ Anything else — no account, no code, an older version (the Oracle's 1.0.0 / 1.1.0, the registry's 1.0.0), other code — makes the block invalid with one error, `UnexpectedSystemContractCode`.
+ No other block reads them.
- An Oracle read in a system call reads chain storage, never the oracle service.
- - Keyless (changing in #407): the call runs as a native creation of the recovered signer; an empty code deposit at the deploy address is refused with `EmptyCodeDeployed`, a constructor's inner creation returning empty code is not; the answers are the documented error set.
+ - Keyless: the call runs as a native creation of the recovered signer; an empty code deposit at the deploy address is refused with `EmptyCodeDeployed`, a constructor's inner creation returning empty code is not; the answers are the documented error set.
+ - The keyless creation forwards `min(gasLimitOverride, remaining)` of regular gas, the reservoir share of what the call has left and the child share of each of the call's pools; the signer's nonce record is counted on the call at its settlement, once the creation returned.
- The interceptor dispatch order is scheme guard, address, selector, then value policy; an unknown selector is not intercepted.
- Deployed bytecode and code hashes match the attested artifacts (`build.rs`).
- **Spec:** §13, §15, §16, §17, §18, §19.
-### Gas schedule and pricing (stable, except `schedule.rs`)
+### Gas schedule and pricing
- **Where:** `src/evm/schedule.rs`, `src/evm/prices.rs`, `src/evm/history.rs`, `src/evm/precompiles.rs`, `src/external/` (SALT pricing), `state_gas_price` in `src/evm/host.rs`, the Amsterdam opcode activation in `src/evm/instructions.rs`.
- **Check:**
- Every regular entry is Amsterdam's; state creation is paid once, in state gas.
+ - The forwards are schedule entries: `call_stipend_reduction` = 50 (the regular-gas cap), `reservoir_kept_percent` = 2, and `pool_kept_percent` = 2 for each of the three pools; the neutral configuration keeps EIP-150's 63/64 and forwards the whole reservoir.
- State gas = schedule entry × bucket multiplier `m`; regular gas never scales.
A failed capacity lookup is a node fault: the transaction gets no outcome and is not settled, and the node reports an internal error with the cause.
- History gas uses the limit layer's byte table, so a record's history bytes are its data size; the three sites where the totals part are in the `src/limit/mod.rs` module doc, "The byte table".
- A deposit, a protocol-produced transaction and a system call pay no history gas.
- - The history allowance (160 bytes, `storage_call_stipend()` in `src/evm/history.rs`) draws only on a log's charge.
+ - The history allowance (`HISTORY_ALLOWANCE_BYTES`, 160 bytes; `history_allowance_gas()` in `src/evm/history.rs`, the schedule's `call_history_allowance`) draws only on a log's charge.
- The EIP-7623 floor is still computed and validated.
- The constants are provisional; a build with `satin-price-override` must never reach a node.
- **Spec:** §2, §4, §5, §6, §7, §8, §9.
-### Inspector contract (deleted in #407)
+### Inspector contract
-- **Where:** `src/evm/inspector.rs`, and the admission checks in `src/evm/mod.rs`, `src/block/factory.rs`, `src/block/executor.rs`.
+- **Where:** the `evm` module documentation (`src/evm/mod.rs`, "Inspectors") and `src/evm/execution.rs` (`frame_init`, `frame_run_result`, `frame_return_result`; `frame_run` and `InspectorEvmTr` are revm's), `test_utils::ReadOnlyObserver`.
- **Check:**
- - The module documentation of `src/evm/inspector.rs` is the contract (the spec does not describe inspectors); check that each rewrite it permits is settled as it says.
- - An answered frame and a revived call settle as a frame that kept nothing: state and history gas rolled back, refund dropped, lane discarded, the upfront charge given back at the price it was made at.
- - A success rewritten into a failure has its journal taken back to the frame's checkpoint.
+ - The module documentation of `src/evm/mod.rs` is the contract (the spec does not describe inspectors): an inspector runs on revm's inspected lifecycle unchanged, and every per-frame mechanism sits in the frame start, run result or return both loops share.
+ - A rewritten result is taken as given: the caller settles it as revm does, with no correction of the engine's.
+ - An inspector's answer never reaches the engine's frame start, so the depth guard, the interceptors and gas detention see none of it, and it settles on the gas it is built on.
+ - A frame that crosses the compute limit is seen to end with the stop: the stop is made in the fork's run-result hook (`frame_run_result`), before the inspector's `call_end`, `create_end` and `frame_end`.
+ - A `keylessDeploy` call's frame is handed to no `initialize_interp` and gets no `step`: the inspector sees the call start, its creation, and the call end.
+ - A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, its declared part coming back only as for any start whose frame keeps nothing (a frame that fails, or a start revm refuses before it bumps a nonce or moves a value), and its records are those revm then made.
- A pre-block system call runs on the plain system-call path, with no callback.
- - A declared observer must not answer a frame, edit inputs or rewrite a result (checked in debug builds).
+ - `test_utils::ReadOnlyObserver` checks, in debug builds, that an inspector a test declares an observer writes nothing back: a tripwire for tests, not a proof.
+- **Detail:** [`AGENTS.md`, "Contracts of the common execution layer"](../../../AGENTS.md#contracts-of-the-common-execution-layer), the entries on inspectors.
-### Node surface, validation and the stateless witness (stable, except genesis and validation)
+### Node surface, validation and the stateless witness
- **Where:** `src/lib.rs` (explicit exports), `src/block/hardfork.rs`, `src/block/chain.rs`, `src/block/genesis.rs`, `src/evm/validation.rs`, `src/evm/state.rs`, `src/block/l1_block_info.rs`, `src/test_utils/witness.rs`, `crates/mega-state-test/src/witness.rs`.
- **Check:**
- `validate_schedule` refuses a schedule in which a base fork Satin runs on is not active by `satinTime`.
- The genesis format has exactly one key, `satinTime`; Satin carries no parameter, and every other `satin*` key (the old registry and limit keys included) is refused.
+ - A key given twice is read as its last copy by every reader, and `satinTime` is also read from the `arbitrary_precision` object form, decimal digits alone.
- The pool and the engine refuse the same oversize body with the same error (`TX_BODY_OVER_DATA_SIZE_LIMIT`): body + 40 × authorizations over the transaction limit.
- - The witness holds every read: block hashes, SALT bucket ids, the Oracle reads of the block's transactions (none for system calls), the L1 block info, the registry.
+ - The witness holds every read: block hashes, SALT bucket ids, the Oracle reads of the block's transactions (none for system calls), the L1 block info, the registry, and every authority the authorization-list simulation loaded.
- The witness is the sequence of states the block commits: each pre-block step commits its state on its own, read-only entries included, where a commit hook on `State` receives it whole; nothing else hands the pre-block states out.
+ - A witness replay's exports are a subset of the building node's, and may be a proper one.
+ - A node's database answers an address it holds no account for as no account (`None`), never as an empty account: the destruction table gives a leaf back only when no account stood there.
- **Spec:** §1, §21, §22, "Node integrators".
-### Tools, tests, goldens, benches and CI (stable, except the outcome tooling)
+### Tools, tests, goldens, benches and CI
- **Where:** `bin/mega-evme/` (`bin/mega-evme/src/engine.rs` picks the engine from `--spec`: Satin in-tree, legacy specs on a released crate; `run` and `tx` default to the legacy `Rex6`), `crates/mega-state-test/`, `crates/state-test/`, `crates/mega-evm/tests/` (`satin/`, `block/`, `system/`, `fuzz/`, `tracers/`), `crates/mega-evm/benches/`, `.github/workflows/`, `scripts/`, `mutants/suppressions.toml`.
- **Check:**
- No consensus path changed for a tool's sake; tool overrides (`--override.limits`, `with_tx_runtime_limits`, `with_protocol_limits` under `test-utils`) are explicit and never default.
+ - A limits file of the first shape, without the KV-update and state-growth fields, reads with the default spec's values for them; every other field stays required, and an unknown one is refused.
+ - `state-test --json-digest` hashes each transaction's whole outcome, and the `--limit-*` options run Satin mode under tighter limits in each dimension.
- A test pins a spec rule, not the implementation; a new or changed test says which rule it checks (some headers carry a `[S.]` tag: the spec section and item).
- A figure the schedule determines is asserted against its derivation, not pinned; snapshots and goldens own only outputs with no computable expectation.
+ - The limit matrix (`tests/satin/limit_matrix/`) runs every row, none of them ignored.
+ - `mega-evme`'s recorded mainnet blocks are one deterministic archive, `bin/mega-evme/tests/fixtures/blocks.tar.xz`, extracted once per test binary into cargo's target scratch directory, each file moved into place on its own so racing extractions all succeed; `bin/mega-evme/scripts/pack_blocks_fixture.py --check` holds a repack of it byte-identical.
- The suite passes at the byte-price grid's points, not only at the spec's prices.
- The mutation gate is fail-closed: a suppression without a locator may cover only one mutant.
- A fuzz run that checks nothing fails (zero cases, zero comparisons).
## Judging a finding
-1. **Reachability first.** Does the node's block execution or building path reach it? With the default configuration, or only with a non-default limit? Is it decided below, or does #407 change it ("What is still moving")?
+1. **Reachability first.**
+ Does the node's block execution or building path reach it?
+ With the default configuration, or only with a non-default limit?
+ Is it decided below?
2. **Severity**, in this order:
1. not reachable from block execution or building: at most low (tools, test APIs);
2. reachable only with a non-default configuration: one level lower;
@@ -254,51 +390,61 @@ For each module: where it is, what to check, the spec sections, and the `AGENTS.
Read this before rating a finding that says a failure reverts where it should halt, or halts where it should revert.
A refusal the protocol imposes reverts; an execution fault halts.
-Every limit stop — the transaction's data-size limit, a frame's data-size budget, gas detention's compute limit — reverts the frame that crosses it with `MegaLimitExceeded(uint8 kind, uint64 limit)` on the frame's own gas, so the unspent gas goes back to the caller, which resumes and may catch the stop.
+Every limit stop — the transaction's data-size, KV-update and state-growth limits, a frame's budget in those three, gas detention's compute limit — reverts the frame that crosses it with `MegaLimitExceeded(uint8 kind, uint64 limit)` on the frame's own gas, so the unspent gas goes back to the caller, its reservoir and pools included, and the caller resumes and may catch the stop.
An execution fault — a real out-of-gas, a precompile given less than its price, an invalid opcode, a charge the frame cannot pay — halts and consumes the frame's gas, as in revm.
One ABI serves every kind of stop, and there is no third ending: the halt reasons are op-revm's (`MegaHaltReason`), and the engine makes no halt of its own.
-
-The KV and state-growth stops, and naming the frame budget rather than the transaction limit when a write crosses both, are still to land in #407; on this branch such a write names the transaction limit (`AdditionalLimit::check`).
+An operation that crosses several counted dimensions at one site stops on the first of data size (kind 0), KV updates (kind 1) and state growth (kind 3); compute (kind 2) is decided at the regular charge, before the write is counted.
+Inside a dimension the frame budget is tested before the transaction limit, and the stop names the budget whenever the budget is crossed.
The deliberate exceptions:
-| What happens | Why |
-| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| A deposit that fails validation — its body over the data-size limit, or sent from the live system address — or that cannot pay a charge made before its first frame, or whose execution halts, is included as a failed deposit: its whole gas limit billed, its nonce bumped, its mint kept, nothing else applied, no stop reported. | The OP stack's deposit rule: a deposit comes from L1, where its gas was paid, and must be included, so it can be neither rejected nor caught by a caller. |
-| An input over one of Optimism's precompile input-size limits (the BN254 pairing, the BLS12-381 MSMs and pairing) is refused before any gas check: the call halts and burns its forward. | The Optimism precompile specification, inherited with the Karst set: the size check is the precompile's own input check, which fails the call like any bad input. Gas detention prices such an input at zero, so it is never a crossing. |
-| Under gas detention two precompile faults end as the compute stop instead of a halt: a priced precompile whose price is past the allowance and within the forward is not run, even when its input would fail a check made after the gas check; and a precompile the engine cannot price (one a node added or replaced) that runs out of the allowance is the stop, even when its price is past the whole forward. | revm runs a precompile inside the frame's start, so the engine must decide before it runs, and it decides from the price; a check made after the gas check is not visible to it. A precompile without a price can only be run on the allowance, and running out of it is all the engine sees. |
-| A call whose start (its value transfer's records and transfer log) crosses the data-size limit gets the stop on its untouched forward, even when the callee is a precompile that would have failed and burned the forward. | A limit is enforced at the writes it guards, and a start writes before its callee runs. Here the start is counted before revm runs the callee, which then never runs; #407 counts it after revm answered and replaces a failed answer with the stop, to the same end. |
-| A frame answered without running (an interceptor's answer, or a `keylessDeploy` call refused for carrying value) that spent more regular gas than the frame's allowance is the compute stop, and none of its spending is billed, the part within the allowance included, where a frame that ran keeps what it spent before the charge that crossed. | An answer is one step with no point inside it where the allowance ran out, so its whole spending is the charge that crossed, and a charge that crosses is never made. Of the engine's own answers only the `keylessDeploy` refusal spends regular gas, its overhead. |
-| Refusals that are not limit stops revert with their own error, not `MegaLimitExceeded`: `VolatileDataAccessDisabled(uint8)` (the opcode's static gas paid, nothing else), `DisabledByParent()`, `NonZeroTransfer()`, `NotIntercepted()`, keyless deployment's rule errors, and revm's `CallTooDeep` and `OutOfFunds` with empty data. All are catchable, and the outcome's `limit_exceeded` stays empty. | They refuse what the caller asked for, not a resource the transaction ran out of: each names its reason in the ABI its contract, keyless deployment or revm already defines, so a caller can tell it from a stop. |
-| One size rule has three endings: initcode over the size limit is rejected at validation in a creation transaction, halts the creating frame at `CREATE` or `CREATE2`, and reverts a `keylessDeploy` call with `InitCodeTooLarge(size, max)`. Deployed code over the code-size limit halts the creation, while deployed code within it that takes the transaction or the frame over the data-size limit is the stop. | The size halts are Ethereum's (EIP-3860 for initcode, EIP-170 for deployed code) at MegaETH's sizes: rules of the EVM, not MegaETH's resource limits, so they stay halts. A keyless call checks the init code among its rules before any creation starts, and every rule refuses with a revert and its own error. |
+| What happens | Why |
+| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| A deposit that fails validation — its body over the data-size limit, or sent from the live system address — or that cannot pay a charge made before its first frame, or whose own frame halts, is included as a failed deposit: its whole gas limit billed, its nonce bumped, its mint kept, nothing else applied, no stop reported. | The OP stack's deposit rule: a deposit comes from L1, where its gas was paid, and must be included, so it can be neither rejected nor caught by a caller. |
+| An input over one of Optimism's precompile input-size limits (the BN254 pairing, the BLS12-381 MSMs and pairing) is refused before any gas check: the call halts and burns its forward. | The Optimism precompile specification, inherited with the Karst set, makes the size check the precompile's own input check, which fails the call like any bad input, and gas detention prices such an input at zero, so it is never a crossing. |
+| Under gas detention two precompile faults end as the compute stop instead of a halt: a priced precompile whose price is past the allowance and within the forward is not run, even when its input would fail a check made after the gas check; and a precompile the engine cannot price (one a node added or replaced) that runs out of the allowance is the stop, even when its price is past the whole forward. | revm runs a precompile inside the frame's start, so the engine must decide before it runs and decides from the price, which says nothing of a check made after the gas check, while a precompile without a price can only be run on the allowance, and running out of it is all the engine sees. |
+| A call whose start (its value transfer's records and transfer log) crosses a data-size, KV-update or state-growth limit gets the stop on its untouched forward, even when the callee is a precompile that would have failed and burned the forward; a precompile priced past detention's allowance whose start's records also cross is that records' stop, not the compute stop. | A limit is enforced at the writes it guards, and a start writes before its callee runs, so revm's answer, whatever it was, gives way to the stop, and the value has moved before the price is consulted, so the records are decided first. |
+| A frame answered without running (an interceptor's answer, or a `keylessDeploy` call refused for carrying value) that spent more regular gas than the frame's allowance is the compute stop, and none of its spending is billed, the part within the allowance included, where a frame that ran keeps what it spent before the charge that crossed. | An answer is one step with no point inside it where the allowance ran out, so its whole spending is the charge that crossed, and a charge that crosses is never made; of the engine's own answers only the `keylessDeploy` refusal spends regular gas, its overhead. |
+| Refusals that are not limit stops revert with their own error, not `MegaLimitExceeded`: `VolatileDataAccessDisabled(uint8)` (the opcode's static gas paid, nothing else; 12 for `SLOTNUM`, outside the contract's enum), `DisabledByParent()`, `NonZeroTransfer()`, `NotIntercepted()`, keyless deployment's rule errors, and revm's `CallTooDeep` and `OutOfFunds` with empty data, all of them catchable, with the outcome's `limit_exceeded` left empty. | They refuse what the caller asked for, not a resource the transaction ran out of: each names its reason in the ABI its contract, keyless deployment or revm already defines, so a caller can tell it from a stop. |
+| One size rule has three endings: initcode over the size limit is rejected at validation in a non-deposit creation transaction, halts the creating frame at `CREATE` or `CREATE2`, and reverts a `keylessDeploy` call with `InitCodeTooLarge(size, max)`; deployed code over the code-size limit halts the creation, while deployed code within it that takes the transaction or the frame over the data-size limit is the stop. | The size halts are Ethereum's (EIP-3860 for initcode, EIP-170 for deployed code) at MegaETH's sizes, rules of the EVM rather than MegaETH's resource limits, so they stay halts, while a keyless call checks the init code among its rules before any creation starts and every rule refuses with a revert and its own error. |
Not exceptions, but easy to mistake for one:
- A transaction that cannot pay a charge made before its first frame — the account a deposit-like transaction creates for its caller, an EIP-7702 authorization's charges, the history of the records made before the first frame — ends out of gas with no frame: its whole regular budget is consumed and its reservoir returned.
That is EIP-2780's runtime out-of-gas path, a gas fault (`pre_execution` in `src/evm/execution.rs`).
+- An EIP-7702 list that would take the transaction over its KV-update or state-growth limit is skipped whole, and the transaction's own frame is stopped before it runs, naming the transaction limit (kind 1 when both would cross).
+ The crossing happens before any frame, yet it is a limit stop, where Rex6 halted; the intrinsic gas, the body's history and its data size stay, and nothing of the list is kept.
+- A deposit whose own frame is stopped settles as a revert, like any transaction's, and is not a failed deposit.
+- A failed deposit that creates its caller counts that account as one unit of state growth, for the transaction and the block, and no limit stops it: it has already failed.
- A keyless creation that reverts, halts or is stopped makes the `keylessDeploy` call succeed, with `ExecutionReverted`, `ExecutionHalted` or `EmptyCodeDeployed` in its ABI return, a stop's revert data carried inside `ExecutionReverted`.
- The call itself reverts with the stop only when its own charges or the signer's nonce record cross a limit (`answer` in `src/system/keyless/settle.rs`).
+ The call itself reverts with the stop only when its own charges or the signer's nonce record cross a limit; otherwise `answer` in `src/system/keyless/settle.rs` builds its ABI return when the creation returned (`frame_return_result` in `src/evm/execution.rs`).
- Under gas detention, only a regular charge the withheld part would have paid is a crossing; a charge beyond the frame's whole regular gas, and a failed state or history charge, halt as they would without the read.
+- Under gas detention, a value call whose own charges cross stops the calling frame before anything moves, whatever its target and whether or not the caller can fund the value.
+- A creator that its creation's nonce record takes over a limit is stopped when the creation returns, before it runs another instruction, whatever the creation's own result.
+- A frame a failure below it left over the transaction's data-size limit — the failure put back a record of a frame above, and a hint the failed frame sent stays — is stopped as it resumes, before it runs another instruction, whether the frame below reverted, halted or was itself stopped.
+- The destruction table's give-back crosses nothing; the operation's positive effects are held after it, in the order data size, KV updates, state growth, and one that crosses stops the destroying frame, which then keeps nothing of the operation; a regular charge of the `SELFDESTRUCT` that crosses gas detention stops the frame before the opcode completes, and none of the table applies.
## Already decided — do not re-report
Each is a decision with its reason; "in this pull request" means review the code, not the decision.
-An item marked (#407) is one #407 revisits; until it merges, the item describes this branch.
-- (#407) **KV, state-gas and block execution-gas limits are removed**: data size bounds the records and history gas prices them, state gas prices state, so removal changes no result.
+- **KV updates and state growth are limited, per transaction, frame and block; state gas and the block's execution gas are not**: the count, not the gas, stops the 1,001st slot, and the KV check is made though at Satin's constants data size binds first.
- **Consensus limits are one per-spec table** (`ProtocolLimits::for_spec`), not chain configuration: configured values could stop the L1-attributes deposit and cost a silent factory fallback.
-- **No latch**: a crossing is a native revert of the crossing frame, which callers may catch; with data size and detention as the only limits no transaction ends over a limit.
+- **No latch**: a crossing is a native revert of the crossing frame, which callers may catch, and a caller that runs on is held to what the transaction has left, so no transaction keeps more than its limits.
- **An oversize transaction body is refused at validation** (a deposit becomes a failed deposit): the body is known before execution, and at Satin's constants the bound is unreachable (6,732,889 < 13,107,200).
+- **An EIP-7702 list over the KV-update or state-growth limit is skipped whole** and stops the first frame before it runs: Rex6's all-or-nothing rule, as a revert-class stop, because a stop of the first frame does not revert what was applied before it.
+- **The stop names the frame budget when both the budget and the transaction limit are crossed**; when a block is full on several budgets, a node may name them in the order data size, KV updates, state growth, and two nodes need not name the same one.
- **`tx_chain_id_check` is pinned on**: it is revm 40's default, and it makes the system-transaction chain-id guard effective.
- **Every transaction pre-warms the registry read**, so gas does not depend on the envelope type; the non-warming journal read is not a generic upstream candidate.
- **A delayed commit re-checks only the sender's nonce and balance**: other staleness is the builder's documented responsibility, as the system-transaction-first flow requires.
- **An MST is never refused by a packing budget or builder policy**: it serves a user transaction already admitted.
- **Satin has no deploy or upgrade path**: it runs on a chain that ran the legacy forks, and its activation block refuses any predeploy without Satin's code; no contract changes.
- **Keyless refuses only an empty code deposit** at the deploy address; the four producer-less errors are deleted, which changes no deployed byte.
-- (#407) **Creation revival by an inspector is allowed** (Foundry parity), settled as a frame that kept nothing; the upfront refund is given back at the price it was charged at.
+- **A rewritten result is taken as given, as revm takes it**: a revived creation settles as the success the inspector made of it (Foundry parity), and an inspector's answer settles on the gas it is built on.
- **The Amsterdam regular gas table is taken wholesale**: the earlier press-back to Osaka priced creation twice.
-- **`validate_schedule` checks that base forks are active by `satinTime`**; engine-built schedules activate them from the first block, which no Satin block can tell apart. An unknown chain has no schedule (`hardfork_schedule` answers `None`).
-- (#407) **A rewriting inspector in block execution is an internal error**, not a block verdict: the inspector is the node's own choice.
+- **`validate_schedule` checks that base forks are active by `satinTime`**; engine-built schedules activate them from the first block, which no Satin block can tell apart.
+ An unknown chain has no schedule (`hardfork_schedule` answers `None`).
+- **Block execution admits any inspector**: which inspectors run on block production is the node's decision.
- **Explicit crate-root exports; dead helpers and legacy-era remnants are deleted.**
- **Satin carries no fork parameter**, and the fork-parameter mechanism was removed with nothing using it.
- **An absurd state-gas price makes the operation run out of gas**; no reachable divergence.
@@ -306,12 +452,19 @@ An item marked (#407) is one #407 revisits; until it merges, the item describes
- **Precompile prices are looked up by id**: a precompile set replaced around the engine, through the mutable accessors, keeps the built-in prices; the spec states the boundary, and nodes change the set through `with_dyn_precompiles` or the factory builder.
- **A keyless signer that is the block beneficiary is detained**, as in the legacy engine.
- **No MST in the activation block**: it admits only deposits and every MST consumer is a non-deposit; documented in the spec.
-- (#407) **Write records are deduplicated per frame**, not per transaction: documented as an upper bound.
+- **Write records follow the transaction-wide net change**, not Rex6's per-operation count: the record measures the state the transaction keeps, which is what history gas prices.
- **The limit override is an explicit tool opt-out** (`with_tx_runtime_limits`); block execution and validation use the chain's limits.
- **No spec ladder in Satin yet**: it comes with the next spec, with the extension points kept; `AGENTS.md` says how to add it.
- **The fork finalizes the journal on an error** (`bluealloy/revm#3780`, carried early): kept; the fork documents it in megaeth-labs/revm#75.
-- (#407) **Answered-frame settlement stays in mega-evm**, and `OpBlockExecutor` is not composed (it requires `PostExecEvm` and returns `OpTxResult`).
-- **The 98/100 frame budget and dropping a hint from a frame whose volatile access is off are kept**: without a latch the budget protects the caller's own work.
-- (#407) **An inspector answer with effects is mis-accounted** (a mock that transfers value, an isolated run): the settlement assumes none; tools only, kept.
-- **Mechanisms kept as in the legacy engine** (not under review): `MegaAccessControl`, gas detention's two categories and 20M caps, `remainingComputeGas()`, the Oracle, keyless deployment, the Mega System Transaction, the registry and rotation, the high-precision timestamp, SALT bucket pricing, the history allowance, the data-size limit's 98/100 share, the 200M execution cap with 512 KiB code size and the KZG price, the deposit-caller account charge, the DA footprint, and the inspector admission gate (#407 deletes the gate).
+- **`OpBlockExecutor` is not composed**: it requires `PostExecEvm` and returns `OpTxResult`.
+- **The 98/100 shares and dropping a hint from a frame whose volatile access is off are kept**: without a latch the frame budgets and the reservoir share protect the caller's own work.
+- **The neutral configuration forwards as Ethereum does** (EIP-150's 63/64, the whole reservoir): equivalence mode is Ethereum's forward, not Satin's.
+- **An inspector's answer built on `Gas::new(limit)` carries no reservoir and unlimited pools**, so above the execution cap its caller keeps only the 2 per cent of its reservoir it kept, and the caller's budgets are lifted for the rest of its frame: tools only, kept.
+- **Satin does not apply EIP-7610's storage collision**: the engine reads storage slot by slot and cannot see storage it has not loaded; the execution-spec gate skips those fixtures.
+- **The destruction table refills state gas, which EIP-8037 does not**: a part the transaction made does not remain for a node to store.
+- **The table's slot column follows the transaction's original**: a slot of a created account first accessed after the creation is zero at the start whatever the state held, as revm loads it; only a slot accessed before the creation keeps its value, and the specification says so.
+- **The neutral configuration counts the destruction table**, and prices it as the fixture's fork does: equivalence mode's usage of a transaction that creates and destroys an account differs from a count without the table, no fixture checks usage, and no second counting rule is kept for the neutral configuration.
+- **`BLOBHASH` is not volatile**, unlike in Rex6: it reads the transaction's own blob hashes.
+- **The pre-block calls run on one constant budget** (`PRE_BLOCK_CALL_GAS_LIMIT`), not on the block's gas limit.
+- **Mechanisms whose existence is kept from the legacy engine** (whether to have them is not under review; their Satin rules, which the specification states against Rex6, are): `MegaAccessControl`, gas detention's two categories and 20M caps, `remainingComputeGas()`, the Oracle, keyless deployment, the Mega System Transaction, the registry and rotation, the high-precision timestamp, SALT bucket pricing, the history allowance, the 98/100 frame share and Rex6's numbers for the data-size, KV-update and state-growth limits, the 200M execution cap with 512 KiB code size and the KZG price, the deposit-caller account charge, the DA footprint.
- **The upstream revm change `new_answer`** for answers to frames that did not run (`bluealloy/revm#3979`) is opt-in: the handler does not normalise answers, because real inspectors' answers can have effects.
diff --git a/.github/workflows/exec-spec-satin.yml b/.github/workflows/exec-spec-satin.yml
index 104068d6c..caa593fb0 100644
--- a/.github/workflows/exec-spec-satin.yml
+++ b/.github/workflows/exec-spec-satin.yml
@@ -144,27 +144,28 @@ jobs:
- name: Read the fork pin from Cargo.lock
id: pin
run: |
- sources=$(grep -o 'git+https://github.com/megaeth-labs/revm?tag=[^"#]*#[0-9a-f]*' Cargo.lock | sort -u)
+ # A release tag, or a release's commit until its tag is cut.
+ sources=$(grep -oE 'git\+https://github.com/megaeth-labs/revm\?(tag|rev)=[^"#]*#[0-9a-f]*' Cargo.lock | sort -u)
if [ "$(printf '%s\n' "$sources" | grep -c .)" -ne 1 ]; then
printf 'expected exactly one revm fork revision in Cargo.lock, found:\n%s\n' "$sources" >&2
exit 1
fi
- tag=${sources#*tag=}
- tag=${tag%%#*}
+ ref=${sources#*=}
+ ref=${ref%%#*}
commit=${sources##*#}
- echo "fork tag $tag at $commit"
- echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "fork ref $ref at $commit"
+ echo "ref=$ref" >> "$GITHUB_OUTPUT"
echo "commit=$commit" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v4
with:
repository: megaeth-labs/revm
- ref: ${{ steps.pin.outputs.tag }}
+ ref: ${{ steps.pin.outputs.ref }}
path: revm-fork
sparse-checkout: scripts
persist-credentials: false
- - name: Check the tag names the locked revision
+ - name: Check the ref names the locked revision
working-directory: revm-fork
env:
COMMIT: ${{ steps.pin.outputs.commit }}
diff --git a/.github/workflows/exec-spec.yml b/.github/workflows/exec-spec.yml
index 227f3c190..0f9c545b1 100644
--- a/.github/workflows/exec-spec.yml
+++ b/.github/workflows/exec-spec.yml
@@ -60,26 +60,27 @@ jobs:
- name: Read the fork pin from Cargo.lock
id: pin
run: |
- sources=$(grep -o 'git+https://github.com/megaeth-labs/revm?tag=[^"#]*#[0-9a-f]*' Cargo.lock | sort -u)
+ # A release tag, or a release's commit until its tag is cut.
+ sources=$(grep -oE 'git\+https://github.com/megaeth-labs/revm\?(tag|rev)=[^"#]*#[0-9a-f]*' Cargo.lock | sort -u)
if [ "$(printf '%s\n' "$sources" | grep -c .)" -ne 1 ]; then
printf 'expected exactly one revm fork revision in Cargo.lock, found:\n%s\n' "$sources" >&2
exit 1
fi
- tag=${sources#*tag=}
- tag=${tag%%#*}
+ ref=${sources#*=}
+ ref=${ref%%#*}
commit=${sources##*#}
- echo "fork tag $tag at $commit"
- echo "tag=$tag" >> "$GITHUB_OUTPUT"
+ echo "fork ref $ref at $commit"
+ echo "ref=$ref" >> "$GITHUB_OUTPUT"
echo "commit=$commit" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v4
with:
repository: megaeth-labs/revm
- ref: ${{ steps.pin.outputs.tag }}
+ ref: ${{ steps.pin.outputs.ref }}
path: revm-fork
persist-credentials: false
- - name: Check the tag names the locked revision
+ - name: Check the ref names the locked revision
working-directory: revm-fork
env:
COMMIT: ${{ steps.pin.outputs.commit }}
diff --git a/AGENTS.md b/AGENTS.md
index eb470a8c2..6f106e02d 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -50,6 +50,8 @@ cargo run --release -p state-test -- btest /blockchain_tests --ex
# the fixtures named by an absolute path (the test runs in the package's directory)
MEGA_STATE_TEST_FIXTURES=$PWD//state_tests MEGA_STATE_TEST_SAMPLE=0 MEGA_STATE_TEST_FORK=Osaka \
MEGA_STATE_TEST_MODE=satin cargo test --release -p mega-state-test --test witness -- --ignored --nocapture
+# The whole-outcome digest: one line per executed transaction (the canonical record of its MegaTransactionOutcome, hashed; `-full` adds the record), for a base-against-head `sort | cmp`
+cargo run --release -p state-test -- --mode satin --fork Osaka /state_tests --json-digest 2>&1 >/dev/null | grep '^{' | sort > head.digest
# Regenerate the rendered deviation registry after changing crates/mega-state-test/src/deviations.rs
UPDATE_DEVIATIONS=1 cargo test -p mega-state-test --lib deviations
@@ -102,9 +104,17 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat
- `cargo tree -i revm` must show exactly one revm, from the fork: the engine's graph (the default member) never reaches another.
The workspace also locks revm 27.1.0, linked only by `mega-evme`: its `legacy` feature, and its `mega-state-test` 1.7.1 dev-dependency, which is unconditional, so a test build without `legacy` links it too (`cargo tree --workspace -i revm@27.1.0`).
- The fork pins move by editing the patch blocks; commit the regenerated `Cargo.lock` with them.
-- Gas detention builds on the fork's withheld part of a frame's regular gas (`GasTracker::limit_spendable`, `withheld_crossing`, `set_withheld_crossing`), whose crossing record holds the regular gas the frame had before the charge that crossed (`WithheldCrossing::remaining`), and on the fork's precompile price (`Precompile::required_gas`), neither of which upstream revm has.
+- Gas detention builds on the fork's withheld part of a frame's regular gas (`GasTracker::limit_spendable`, `withheld_crossing`, `set_withheld_crossing`), whose crossing record holds the regular gas the frame had before the charge that crossed (`WithheldCrossing::remaining`), on the fork's failed-charge record, the regular gas a frame had before every deduction that failed and before a halt on a cold access it could not pay (`failed_charge_remaining`, `set_failed_charge_remaining`), which tells what a halting frame burned, and on the fork's precompile price (`Precompile::required_gas`), none of which upstream revm has.
+- Writes and frame starts are metered inside revm's instructions, through the fork's two instruction hooks on `Host`, which upstream revm does not have: `SSTORE`, `LOG0`–`LOG4` and `SELFDESTRUCT` call `write_completed` once the write is in the journal and every charge they make has been made, and the four calls and two creations call `frame_starting` once the forward is taken and before the frame's input is built.
+ `CompletedWrite` and `FrameStartKind` are exhaustive on purpose, so the engine's matches over them carry no wildcard arm and a new kind is a compile error here.
+- The actions the engine makes for a frame outside an instruction — a `keylessDeploy` call's creation and its answer, and the stop of a frame a child returned into over a limit — come back through revm's own frame run, plain or inspected: the fork's run returns an action set on a frame's interpreter before it runs without running an instruction or calling the inspector's `step`, and its inspected frame start hands a frame built with one to no `initialize_interp`, so the engine's `frame_run` only forwards to revm's.
+ A frame's own end is decided in the fork's run-result hook (`EvmTr::frame_run_result`), which revm's plain and inspected loops call once a frame's run returns and before the inspector's `call_end`, `create_end` and `frame_end` and `frame_return_result`: gas detention's classification is made there, so an inspector sees the stop the caller gets.
+- The fork pins at a published commit of its byte-pool branch, and op-revm at a published commit that settles the first frame through the revm fork's shared settlement (`execution::settle_first_frame`), both by revision until the fork's review is done.
+ The byte-pool branch carries three resource pools on every frame's gas tracker, which the engine gives their meaning (`PoolId`, `GasTracker::record_pool`, `refill_pool`, `pool_remaining`, `pool_spent`), each forwarded at every start as the schedule's share (`GasId::pool_kept_percent`, the part the caller keeps) and settled as the reservoir is, and the reservoir itself forwarded by its own share (`GasId::reservoir_kept_percent`, `GasTracker::forward_to_child`), the child's return adding what it left to what the caller kept; a start charge the frame-start hook declares on the start (`FrameStart::charge`, `StartCharge`) and the fork refunds when the frame fails; the history allowance a value call gives its child (`GasId::call_history_allowance`, `GasTracker::draw_history_allowance`); a creation's address on its start (`FrameStart::target`) and a `SELFDESTRUCT`'s moved balance on its completed write (`CompletedWrite::SelfDestruct::balance`).
+ The fork does not split a system call's gas or report the reservoir on `ResultGas`: Satin does both itself (`MegaHandler::tx_gas`, `AdditionalLimit::reservoir_remaining`), and its op-revm baselines run op-revm through a reference handler that does the same (`tests/shared/op_reference.rs`).
+ Its switch back to revm 40.0.3's journal semantics (`CfgEnv::legacy_journal_semantics`) is the legacy engine's: Satin's spec and neutral configurations fix it off.
- The op-revm fork prices its size-limited precompiles through that hook, which upstream op-revm does not, so gas detention decides a call to the BN254 pairing or a BLS12-381 MSM or pairing from its price rather than running it on the allowance.
-- The limits hold deployed code at the fork's code-deposit admission (`ContextTr::admit_code_deposit`), which `return_create` asks after every deposit charge and before it commits the creation.
+- The limits hold deployed code at the fork's code-deposit admission (`ContextTr::admit_code_deposit`), which `return_create` asks after every deposit charge and before it commits the creation, lending it the creating frame's tracker, whose pool the code's bytes are drawn from.
## Architecture
@@ -123,39 +133,41 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat
### Core Source Layout (`crates/mega-evm/src/`)
-| Module | Holds |
-| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
-| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame lifecycle (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, and the system-transaction promotion in `MegaHandler` over op-revm's handler (`execution.rs`); the staging Host, the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the `SSTORE`/`LOG`/`SELFDESTRUCT` commit wrappers, the `CALL`/`CALLCODE`/`CREATE`/`CREATE2` write-record charges, the volatile-read wrappers, the out-of-gas notes and the `KECCAK256` and copy wrappers that exist for them, and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, and which calls gas detention may price from it (`precompiles.rs`); synthetic frame results (`frame.rs`); `TrustedObserver`, `DeclaredObserver`, the settlement of a frame that kept nothing, the journal's revert of a success an inspector rewrites into a failure and the guard that keeps an inspector's refused charge from classifying a frame (`inspector.rs`); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch and the system-call reservoir split the spec fixes on, whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the starts revm refuses on the caller's account, and the debug check of every start (`execution.rs`); the system-call entry points, `transact_system_call_with_gas_limit` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) |
-| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory` and the admission gate; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size budget), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its data-size limit (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) |
-| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) |
-| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`, `StagedRecord`; `AdditionalLimit`: the per-frame lanes of data-size bytes, write records, history allowances and the log and code bytes of the history byte count (`frame_limit.rs`), staging, the stops its frames return and the one the transaction reports, the transaction body, deployed code and the EIP-7708 transfer logs on the lanes; `EvmTxRuntimeLimits` (the data-size limit: a transaction cap, the 98% share a child takes of what its parent has left, and an optional frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) |
-| `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) |
-| `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) |
-| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off |
-| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) |
-| `test_utils/` | `MemoryDatabase` (with the predeploys a chain that ran Rex6 holds, which Satin's activation block checks: `rex6_predeploys`, the registry alone with `sequencer_registry`, `SequencerRegistryRoles`), `ErrorInjectingDatabase`, `BytecodeBuilder` (with the programs that move value), `GasInspector`, `transact`, the EIP-7708 transfer log a test expects (`transfer_log`, `is_transfer_log`), the JSON `Scenario` format (one EVM per scenario, as a block runs); the execution-spec gate's neutral configuration (`neutral_cfg`, `neutralize_evm`, over `MegaContext::with_neutral_cfg`); the note a test's price guard leaves for the byte-price grid to count (`note_price_guard`); the witness recorder and the strict replay: a database and environments that record every read, the channel witness built from the states a node has (`CommittedStates`, the commit hook a node takes them with, `WitnessKeys`, `WitnessRecord::from_channels`), and a database and environments that serve exactly a record and refuse everything else (`witness.rs`) |
+| Module | Holds |
+| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `evm/` | `MegaSpecId`; `MegaContext`; `MegaEvm` over revm's `Evm` with its own frame start and return, which revm's plain and inspected loops share (detention's hooks and its hold on answered frames included), the interceptor scheme guard, the keyless dispatch, the hand-made actions of the `keylessDeploy` call's frame and its creation's return into it, the system-transaction promotion in `MegaHandler` over op-revm's handler, the split of a system call's gas at `SYSTEM_CALL_REGULAR_GAS_LIMIT` (`MegaHandler::tx_gas`) and the read of the reservoir a result settled with (`execution.rs`); the completed-write and frame-start hooks — a completed write's record, drawn on the frame's pool, held to the limits and charged its history, a same-transaction destruction's give-back, and a frame start's records, charged to the caller after the forward and declared on the start — the SALT pricing hook, the block-hash, SALT-bucket and oracle-read records a stateless witness needs, the Oracle's storage read through the oracle service, the volatile-read marks and refusals (`host.rs`, `state.rs`); the volatile-read wrappers and the Amsterdam opcode activation (`instructions.rs`); the Satin gas schedule (`schedule.rs`) and the byte prices it is built from (`prices.rs`); what a history byte costs and how many each site appends (`history.rs`); the Satin precompile set with the repriced KZG, which calls gas detention may price from it, and the precompile provider, alloy-evm's, run on the context `MegaContext` wraps (`precompiles.rs`); synthetic frame results (`frame.rs`); what an inspector sees and may rewrite, run on revm's inspected lifecycle unchanged (the module doc); `MegaTransactionOutcome`, `MegaGasUsage` (`result.rs`); `MegaEvmFactory` and its dynamic precompile builder (alloy-evm); the EIP-7708 switch the spec fixes on and the legacy journal switch it fixes off, whether the running execution is a system call whose gas is split (`splits_system_call_gas`), whether the running transaction is the protocol's own, and the code-deposit admission (`context.rs`); the count and hold of a frame's start once revm decided it, on the pool its frame starts with, the cap on a child's share, and a creator's nonce record counted on the creator once its creation returned (`hold_creator`) (`execution.rs`); the system-call entry points, the pre-block calls' on `PRE_BLOCK_CALL_GAS_LIMIT` among them (`mod.rs`); `spec_cfg`, the configuration the spec fixes, exported for a node's `EvmEnv` (`context.rs`); a pool's validation without state through the handler's own phases and `IntrinsicGas`, the intrinsic gas by ledger (`validation.rs`) |
+| `block/` | `MegaHardfork`, `MegaHardforks`, `MegaHardforkConfig` and the load-time schedule validation (`hardfork.rs`); the chain table and the canonical schedules (`chain.rs`); `MegaBlockExecutor` with the Karst block rules, `MegaBlockExecutorFactory`; `ProtocolLimits::for_spec`, the one per-spec table of the limits every node shares (the per-transaction runtime limits and the block's data-size, KV-update and state-growth budgets), `BlockLimits`, the builder's packing policy that can only tighten them, `BlockLimiter` with the block's gas limit, the header's, and its three packing budgets (`limit.rs`); `BlockGasCounters` (the three ledgers and the history bytes), `MegaBlockTxResult` (`result.rs`); the pre-block call helpers and the pre-block budget (`eips.rs`); the activation block's check of the predeploys, the `SequencerRegistry`'s due changes and the commit of each pre-block step's state on its own in `apply_pre_execution_changes`, and the signal that a block is Satin's activation block (`MegaBlockExecutionCtx::satin_activation_block`); `MegaTransactionExt` (`helpers.rs`); the pre-block read of the L1 block info the transactions are priced against, every slot the pricing can read whatever the contract holds before the block (a deposit in the block may empty the fee scalars and turn the pricing to the overhead), committed as a read-only state of its own so a witness built from the committed states holds what op-revm and the executor read on the database itself (`l1_block_info.rs`); the block-hash and SALT-bucket records, emptied when the block starts and exported by the executor (`get_accessed_block_hashes`, `get_accessed_bucket_ids`) for the stateless witness (`evm/state.rs`); `SatinChainConfig`, the one parser of a genesis `config` object's Satin key, `satinTime`, in a provisional format (`genesis.rs`) |
+| `external/` | `ExternalEnvFactory`, `ExternalEnvs`, `SaltEnv`, `OracleEnv`, `EmptyExternalEnv`, the bucket hasher, `TestExternalEnvs`; `BucketMultipliers`, the per-transaction cache the SALT pricing hook reads through (`gas.rs`) |
+| `limit/` | the byte table every mechanism sizes a thing by; `LimitKind`, `LimitCheck`, `MegaLimitExceeded`, `LimitUsage`; the write records and the state growth a write and a frame start make, by the net change of the accounts and slots against their originals, a `SELFDESTRUCT`'s rebuilt from the balance it moved, a creator's read off its nonce bump against the creator as it stood before revm decided the creation (`CreatorBefore`), and the parts of an account created in the transaction that its first effective destruction gives back (`DestroyedParts`) (`record.rs`); `AdditionalLimit`: the draws on a frame's three pools — data size, KV updates, state growth — and the transaction's limits held beside the pools, on what the transaction keeps — its body, its hints, its authorities' records and the accounts they created, a deposit's created caller, and what its frames keep, restored when a start's frame keeps nothing, one entry per start revm decided with a kept start's take-back credit and a creation's creator as it stood before revm decided it — the stops its frames return and the one the transaction reports, the exemption, and the settled transaction's history gas, history bytes and unspent reservoir (`limit.rs`); `EvmTxRuntimeLimits` (the data-size, KV-update and state-growth limits: a transaction cap each, the 98% share a child takes of what its parent has left, and an optional data-size frame cap; gas detention's two caps; the spec's, from `ProtocolLimits::for_spec`, in every context unless a tool or a test sets others); `LimitStop` and `decode_mega_limit_exceeded`, a limit stop read off a transaction's result for an RPC (`mod.rs`) |
+| `access/` | gas detention: `VolatileDataAccess` (`volatile.rs`); `Detention` — the reads committed, the compute limit and the spendable gas it holds each frame to, the classification of a crossing and of an answer, the compute figure across frames and what halts burn, and the volatile-access switch with its refusals and the decoder of a refusal's `uint8` access type (`detention.rs`) |
+| `system/` | the six contracts' addresses, code and ABIs, one module each; the interceptor dispatch and the value policy (`intercept.rs`); the `MegaAccessControl` interceptor steering detention's switch and the `MegaLimitControl` interceptor answering the caller's remaining compute (`control.rs`, `limit_control.rs`), and `SLOT_NUM_ACCESS_TYPE`; the Oracle's hint path, withheld from a frame whose volatile access is off (`oracle.rs`); keyless deployment as a native creation: the dispatch, the call's frame and its first run — the overhead, the nine rules and the charges of the creation's start (`keyless/dispatch.rs`), the creation's return into the call and the ABI answer (`keyless/settle.rs`), the Nick's Method transaction format and the error ABI (`keyless/tx.rs`, `keyless/error.rs`); the system-address transaction and its whitelist (`tx.rs`); the seven predeploys — the six contracts and the EIP-7997 factory — and the check of their code Satin's activation block makes (`predeploys.rs`); the `SequencerRegistry`'s due-change read and its `applyPendingChanges()` pre-block call, and the read of the live system address every transaction makes when it is validated, and the refusal of a transaction from it without the system shape (`sequencer_registry.rs`, `tx.rs`); `live_system_address`, the same read off a database, for a pool (`sequencer_registry.rs`) |
+| `constants.rs` | the provisional numbers (CPSB, slot and account state gas, CPHB, execution cap, contract and initcode size, data-size limits, the default detention caps, the compute bound they are held below, the pre-block calls' gas limit): the Satin gas schedule reads the state-gas and history numbers and the spec configuration reads the caps and the size limits; the pre-block calls read their gas limit; the rest are read by the limit mechanisms. The numbers are provisional until the economics sign-off |
+| `types.rs` | transaction, halt reason, error and envelope aliases, kept because Satin adds nothing to them (its halt set is op-revm's) |
+| `test_utils/` | `MemoryDatabase` (with the predeploys a chain that ran Rex6 holds, which Satin's activation block checks: `rex6_predeploys`, the registry alone with `sequencer_registry`, `SequencerRegistryRoles`), `ErrorInjectingDatabase`, `BytecodeBuilder` (with the programs that move value), `GasInspector`, `transact`, the EIP-7708 transfer log a test expects (`transfer_log`, `is_transfer_log`), the JSON `Scenario` format (one EVM per scenario, as a block runs); the execution-spec gate's neutral configuration (`neutral_cfg`, `neutralize_evm`, over `MegaContext::with_neutral_cfg`); the note a test's price guard leaves for the byte-price grid to count (`note_price_guard`); the witness recorder and the strict replay: a database and environments that record every read, the channel witness built from the states a node has (`CommittedStates`, the commit hook a node takes them with, `WitnessKeys`, `WitnessRecord::from_channels`), and a database and environments that serve exactly a record and refuse everything else (`witness.rs`) |
### How Satin executes today
- `MegaContext` wraps op-revm's context shape (`MegaTransaction` = alloy-op-evm's `OpTx`, `L1BlockInfo`) and adds the spec and the external environments.
+ Its journal is revm's own (`Journal`): what the transaction keeps of the data-size limit is drawn from the byte pool on each frame's gas tracker and counted on the common execution layer (see the contracts below), not beside the journal.
It keeps the configuration twice — the `MegaSpecId` view callers see and the `OpSpecId` view op-revm executes on — and writes both together.
-- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Satin gas schedule, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 on and not disabled, a system call's gas above 30M in its reservoir (the fork's `system_call_state_gas_margin_in_reservoir` on), the chain-id check on (`tx_chain_id_check`, which the legacy engine pinned off), the contract size limit at 512 KiB and the initcode size limit at 1 MiB.
+- The spec fixes part of the configuration, whatever the caller passes (`MegaContext::with_cfg`): the Satin gas schedule, EIP-8037 on, the EIP-2780 intrinsic cost on, `tx_gas_limit_cap` = 200,000,000, EIP-7708 on and not disabled, the chain-id check on (`tx_chain_id_check`, which the legacy engine pinned off), the contract size limit at 512 KiB, the initcode size limit at 1 MiB, and the fork's journal semantics (`legacy_journal_semantics` off).
That function is exported as `spec_cfg`: a node builds its `EvmEnv` through it, so what reads the env before an EVM exists (reth's gas estimation reads the execution cap) reads the configuration the EVM runs with.
- What a transaction pool can decide without state is the handler's own `validate_env` and `validate_initial_tx_gas`, run on an EVM over an empty database (`validate_transaction_stateless`, `evm/validation.rs`).
`validate_env` is split at the state read of the live system address (`MegaHandler::validate_env_as`): the pool passes the address in, read with `system::live_system_address`, and the system address's nonce and code are left to the state, as every sender's are.
It reports the intrinsic gas by ledger (`IntrinsicGas`): regular, state (zero under EIP-2780, which charges the state a transaction adds when it runs), the body's history, and the floor.
op-revm includes a deposit that fails validation as a failed deposit rather than refusing it, so for a deposit or a promoted system-address transaction the error says it would fail.
Gas above the 200M execution cap goes to the EIP-8037 reservoir.
-- The Satin gas schedule (`evm/schedule.rs`) is Amsterdam's with two changes: the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte, and the code-deposit history entry, zero upstream, is priced at the cost per history byte (`HISTORY_GAS_PRICED`).
+- The Satin gas schedule (`evm/schedule.rs`) is Amsterdam's with four changes: the EIP-8037 state-gas entries are rebuilt from `MegaETH`'s own cost per state byte; the code-deposit history entry, zero upstream, is priced at the cost per history byte (`HISTORY_GAS_PRICED`), and a value call's history allowance at `HISTORY_ALLOWANCE_BYTES` of it; a child starts with 98/100 of its caller's reservoir and of each of its three pools (`GasId::reservoir_kept_percent`, `GasId::pool_kept_percent`); and a call or creation forwards at most `remaining − remaining × 2 / 100` of the caller's regular gas, Rex6's rule in place of EIP-150's 63/64 (`GasId::call_stipend_reduction`).
Every regular-gas entry is Amsterdam's, EIP-8038's state-access prices included, so creating state costs the access and the write in regular gas and the new state itself in state gas alone, as upstream.
The static opcode prices, which revm keeps in the instruction table, are Amsterdam's too (`satin_gas_table`): they part from the Osaka base's only in EIP-8038's 200-gas base of `EXTCODESIZE` and `EXTCODECOPY`.
It is built once per process, with a second copy that prices that entry at zero for a transaction exempt from history gas (`satin_gas_params_history_exempt`); the byte prices are an input (`evm/prices.rs`), so a measurement build can run other ones through the std-only `satin-price-override` feature or the `MEGA_SATIN_CPSB` / `MEGA_SATIN_CPHB` environment variables.
`crates/mega-evm/tests/satin/pricing-table.md` lists every entry next to Osaka's and Amsterdam's, what nine probe transactions spent, and what two of those probes spend with the bucket they write into crowded; a test renders it and compares it to the file.
-- The instruction table adds the Amsterdam opcodes the base spec gates off (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`), before the metering wrappers go in; `CLZ` is gated on Osaka and needs no activation.
+- The instruction table adds the Amsterdam opcodes the base spec gates off (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`), before the volatile-read wrappers go in; `CLZ` is gated on Osaka and needs no activation.
`SLOTNUM` pushes `BlockEnv::slot_num`, which the node supplies, and zero for a block that leaves it unset.
- The precompile set is op-revm's Karst set with KZG point evaluation repriced to 100,000, carried as an alloy-evm `PrecompilesMap` so a node can add or replace an address (`MegaEvmFactory::with_dyn_precompiles_builder`).
-- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the three that stage what a state-writing opcode did, the block-hash read the Host records, the state-gas price the Host scales and the loads of volatile data the Host marks or refuses.
+- `MegaEvm` runs transactions through `MegaHandler`, which wraps op-revm's handler, and implements revm's frame lifecycle itself; every `Host` and context method delegates to op-revm's context except the two instruction hooks that meter a completed write and a frame start, the block-hash read the Host records, the state-gas price the Host scales and the loads of volatile data the Host marks or refuses.
Satin's one divergence from op-revm on an ordinary transaction is the history gas it charges: `tests/satin/equivalence.rs` holds every baseline case to op-revm's total plus the history ledger, on op-revm's own state gas, logs and state, and pins what that ledger is made of; a later change that alters behavior on purpose updates that baseline.
+ A transaction that destroys an account it created diverges beside it by the state gas the destruction table gives back, which EIP-8037 does not (`test_a_creation_that_destroys_itself_diverges_from_op_revm`).
- SALT pricing scales every EIP-8037 state gas charge by the capacity of the SALT bucket it lands in: `state gas = schedule entry x m`, where `m` is that capacity in minimum buckets (`evm/host.rs`).
A charge on a slot reads the slot's bucket, a charge on an account leaf reads the account's, and `m` touches the state dimension only — regular gas never scales.
A slot is charged by the `SSTORE` that fills a fresh one; an account leaf by a `CREATE`, `CREATE2` or value `CALL` that adds it, by the transaction's own recipient or the address a creation transaction deploys at, by an applied EIP-7702 authority (its account and its delegation indicator), by the beneficiary a `SELFDESTRUCT` moves a balance to, by the caller a deposit-like transaction creates, and by a keyless deployment's signer when the creation's nonce bump creates it and its deploy address; the bytes a creation deposits are charged in the deployed address's bucket.
@@ -165,9 +177,9 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat
At the minimum bucket every number is the schedule's own, which is why the op-revm baseline and the pricing table did not move when SALT pricing landed.
- History gas prices the bytes a transaction appends to the chain, at `MegaETH`'s cost per history byte and never scaled by SALT — history bytes live in no bucket (`evm/history.rs`).
The byte table is the `limit` module's, the same counts the data-size limit meters, so a record's history bytes are its own data size and the two cannot drift apart: a transaction body of 310 bytes (110 for the envelope and one 40-byte record for each of the five writes every transaction makes — the sender's account and the four accounts its fees are credited to), one byte per calldata byte, 20 per access-list address and 32 per key, 101 per EIP-7702 authorization, a log's 32 for its address and 32 per topic plus its data, one 40-byte record per kept account or storage write, and one byte per byte of deployed code.
- The body, the applied authorities' records and the record the transaction's own frame makes are charged before execution: the body in the EIP-8037 intrinsic state-gas slot, where the reservoir pays it first and it is not held to the execution cap, and the two record charges in pre-execution, where the records are made.
- A gas limit that cannot cover the body is rejected at validation rather than included as an out-of-gas, and the settled result takes the body back out of the state gas it reports.
- Every other charge is made where the record is: the opcode wrappers charge what the Host staged for them, and `CALL`, `CALLCODE`, `CREATE` and `CREATE2` charge their caller for the records the frame they start makes, out of what the caller kept rather than out of what it forwards.
+ The body, the applied authorities' records and the record the transaction's own frame makes are charged before execution: the body where revm builds the transaction's gas (`MegaHandler::tx_gas`), as intrinsic gas — the reservoir pays it first, it is not held to the execution cap, and revm's runtime out-of-gas fallback, which rebuilds the gas through the same phase, keeps it charged — and the two record charges in pre-execution, where the records are made; the first frame carries its record's charge on its input (`charged_start`), which the shared first-frame settlement gives back when it fails.
+ A gas limit that cannot cover the body is rejected at validation rather than included as an out-of-gas.
+ Every other charge is made where the record is: the completed-write hook charges a storage write's record, a log's and a `SELFDESTRUCT`'s records at the end of its opcode, and the frame-start hook charges the caller of a `CALL`, `CALLCODE`, `CREATE` or `CREATE2` for the records the frame it starts makes, out of what the caller kept rather than out of what it forwards, and declares the frame's own on the start (`FrameStart::charge`), which the fork refunds when the frame fails.
What a frame does not keep comes back, at the same price, to whoever paid it.
The pairing is per record: per transaction the two totals part at three sites, each by decision — an Oracle hint's payload is data size that is never history, an EIP-7708 transfer log is data size that is never history either, and the body's five records are an upper bound, so a transfer to the block beneficiary or a fee vault pays a record the body already bound.
A deposit, a transaction the protocol itself produced and a system call pay no history at all (`MegaContext::prices_history`), and an exempt transaction runs a schedule that prices a deposited byte at zero, so the one history charge revm makes itself is off it too.
@@ -180,39 +192,62 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat
- EIP-7708 is on: every value movement — the transaction's value, a value `CALL`, a creation's endowment, a `SELFDESTRUCT`'s balance moved to another account — emits a `Transfer(from, to, amount)` log from `0xff…fe`, which revm journals itself, without a `LOG` opcode, and the receipt carries in execution order among the contracts' own logs.
A `CALLCODE`, a call to itself and a transaction's value to its own sender move nothing to another account and log nothing; a deposit's value is logged and its mint is not; a destruction to itself burns the balance of an account created in the transaction without a log, because the base spec predates EIP-8246 and this revm emits no `Burn` log.
A transfer log is data size like any log, counted by the rule a `LOG3` of one word is — 160 bytes, `TRANSFER_LOG_SIZE` — and nothing else: it is no write record and pays no history gas, because Ethereum prices it at nothing and it is not a byte the transaction chose to write.
- It is counted where the value moves, on the lane of the frame whose journal checkpoint holds the move: a frame start's log with its records, before revm builds the frame and so before its checkpoint, which lets a crossing answer the frame with the stop before any value moves; a `SELFDESTRUCT`'s with its beneficiary's record once the opcode completed, so a crossing stops the destructing frame and its checkpoint takes the move back.
- A frame start is counted before revm decides it, from what revm itself checks as far as the caller's account decides it, read from the journal without loading anything (`caller_refuses_start` in `evm/execution.rs`): a start revm refuses there — a value its caller cannot fund, a creation whose creator's nonce cannot be bumped — moves and writes nothing, so it counts no log and no record, is charged no history, and no limit stops it.
- The one refusal decided after the count is a creation onto an occupied address, which revm reads off the created address's account only when it builds the frame: its records and log are counted, so a crossing they cause stops the creation where revm would have failed it on the collision.
- A start past the call-stack limit, of any scheme or a creation, is answered by the depth guard with revm's own `CallTooDeep` before it is counted, so no start is counted for a nonce revm never bumps.
- A debug build asserts after every frame start that revm refused exactly the starts predicted and journaled exactly the log that was counted; `tests/satin/transfer_logs.rs` pins every site, and a unit test in `evm/history.rs` holds each against the same transaction with the switch off: the same gas on every ledger and the same state, 160 bytes of data size per log.
+ It is counted where the value moves, on the pool of the frame whose journal checkpoint holds the move: a frame start's log with its records, on the started frame; a `SELFDESTRUCT`'s with its records once the opcode completed, so a crossing stops the destructing frame and its checkpoint takes the move back.
+ A frame start's records and log are read off the journal before revm decides the start, as the hook that charged its caller read them, and drawn on the pool the frame starts with once revm decided it, in `MegaEvm::frame_init` (`AdditionalLimit::count_start`), with a journal mark at every start: a frame revm built ends with the stop before any instruction, in `frame_init`, and its revert takes back the move and the log; an answer revm gave without building the frame — a call to an account with no code, to a precompile, failed or not — gives way to the stop on its untouched gas, and a success's committed move and log are taken back to the mark (`take_back_a_stopped_answer`).
+ A start revm refuses on its caller's account moves and writes nothing: a call it answers `OutOfFunds` counts nothing and is stopped by nothing; it was charged nothing at its opcode, which predicts a start's records from the journal's state and sees the caller cannot fund the value.
+ A creation it would answer before bumping its creator's nonce — an endowment the creator cannot fund, a creator whose nonce is at its maximum — is refused by the `CREATE` and `CREATE2` opcodes themselves, before the start's hook under EIP-8037, and otherwise reaches the hook without a created address, for which it predicts no record, so a plain run charges and counts nothing for it; only an inspector that rewrites the creation's input after the hook reaches revm's refusal, which bumps nothing and so counts nothing: the declared part of what the opcode charged comes back with the refused start, and the history of the creator's record, which is not declared, stays charged.
+ A creation onto an occupied address, which revm fails after the nonce bump, is held to nothing at its start: it fails on the collision, its records and log go with the failure, and the nonce record is counted on the creator once the creation returned, held to the creator's limits.
+ The one decision taken before revm's is gas detention's answer to a precompile whose price crosses the compute limit, given without running it (`hold_precompile`): it is not given to a value call whose caller cannot fund the value, which revm refuses first.
+ A start past the call-stack limit, of any scheme or a creation, is answered by the depth guard with revm's own `CallTooDeep` before it is counted.
+ A start's log is predicted from the journal's state, as revm's transfer decides it (another account, a value the caller can fund); `tests/satin/transfer_logs.rs` pins every site, and a unit test in `evm/history.rs` holds each against the same transaction with the switch off: the same gas on every ledger and the same state, 160 bytes of data size per log.
- The data-size limit holds a transaction to `EvmTxRuntimeLimits::tx_data_size_limit` and every frame to a budget: the transaction's own frame gets what its body leaves, and a child 98% of what its parent has left, under an optional frame cap.
- The bytes are the byte table's, counted where they are made: the body before any frame, the authorities' records before the first frame, a frame start's records when it starts (none for a start revm refuses on its caller's account), a storage write, a log or a `SELFDESTRUCT`'s beneficiary once the opcode completed, an EIP-7708 transfer log with the frame-start records or the `SELFDESTRUCT` that moves the value, deployed code once `return_create` has made every charge for it and before it commits the creation (`MegaContext::admit_code_deposit`; code starting with `0xEF` or over the code-size limit, and a creation that cannot pay a part of its deposit, the history included, fail the creation alone and are not counted), an Oracle hint before it is forwarded (one that would cross the transaction's limit is neither counted nor forwarded, and its call is answered with the stop, so the transaction keeps none of its bytes).
+ A frame's budget is a pool on its gas tracker (`limit::DATA_SIZE_POOL`; the KV-update and state-growth budgets are the other two pools): the transaction's tracker starts with what the body and the counts made before the frame leave (`AdditionalLimit::first_frame_pools`), revm hands the first frame the whole of it and every child the schedule's share of its caller's (`GasId::pool_kept_percent` = 2, so a child gets 98%), capped where the caller suspends (`cap_the_shares`: the frame cap, and a frame's remaining clamped to its budget, so a negative net never enlarges a child's share), and settles a returning child's pool as it settles the reservoir; the transaction's limit is held beside the pools on what the transaction keeps (`AdditionalLimit::usage`).
+ In each counted dimension the frame budget is tested before the transaction limit: a crossing of both names the budget, and the transaction limit is named only when the budget is not crossed — after Oracle hints used what the transaction had left, or when a deposit-like transaction's created caller stands on a state-growth limit of nothing; the budgets of the frames on the stack add up to what the transaction has left, so otherwise a frame that crosses the transaction limit crosses its own budget too.
+ The bytes are the byte table's, counted where they are made: the body before any frame, the authorities' records before the first frame, a frame start's records when it starts, held to the limits once revm decided it (none for a start revm refuses on its caller's account), a storage write, a log or a `SELFDESTRUCT`'s records (the account it clears and its beneficiary) once the opcode completed, an EIP-7708 transfer log with the frame-start records or the `SELFDESTRUCT` that moves the value, deployed code once `return_create` has made every charge for it and before it commits the creation (`MegaContext::admit_code_deposit`; code starting with `0xEF` or over the code-size limit, and a creation that cannot pay a part of its deposit, the history included, fail the creation alone and are not counted), an Oracle hint before it is forwarded (one that would cross the transaction's limit is neither counted nor forwarded, and its call is answered with the stop, so the transaction keeps none of its bytes).
A frame that crosses its budget or the transaction's limit reverts alone, and its caller resumes (the contracts below).
Every `MegaContext`, a bare one included, runs under its spec's limits, and a block executor installs the same (see the protocol limits below): Satin holds each transaction to `TX_DATA_LIMIT` and the block to `BLOCK_DATA_LIMIT`, 12.5 MiB each.
The block's data size is a packing budget (see the block executor below).
`tests/satin/data_size.rs` derives where the stop gives way to out-of-gas: a top-level fresh `SSTORE` is counted at 152,306 gas, and keeping its record costs its 3,520 history on top.
-- A limit stop names one of two runtime dimensions, the `kind` of `MegaLimitExceeded` (`LimitKind`), with the discriminants the legacy engine encoded: data size (0), counted on the lanes with a transaction limit and frame budgets, and compute gas (2), gas detention's stop.
- The legacy engine's KV updates (1) and state growth (3) name no dimension: `LimitKind::from_u8` answers `None` for them.
-- No limit holds the write records a transaction keeps — its KV count, one record per kept account or storage write, deduplicated per frame and taken back with a write-back or a failed frame — and the count is still reported, in the outcome's usage and the block's.
- The sender's account and the fee accounts are the body's, not records, so a transaction that writes nothing counts none.
+- A limit stop names one of four runtime dimensions, the `kind` of `MegaLimitExceeded` (`LimitKind`), with the discriminants the legacy engine encoded: data size (0), KV updates (1) and state growth (3), each drawn from a pool of the frames' gas trackers under a transaction limit, and compute gas (2), gas detention's stop.
+ An operation that crosses more than one counted dimension stops on the first of data size, KV updates, state growth (`limit::COUNTED`); compute is decided at the regular charge, before the write is counted.
+- The KV-update limit holds the write records a transaction keeps — its KV count, one record per kept account or storage write: an account's while its nonce, balance or code differs from what the transaction loaded, a slot's while its value differs from its original, each taken back by a write that returns the account or the slot and with a failed frame — to `EvmTxRuntimeLimits::tx_kv_update_limit` (`TX_KV_UPDATE_LIMIT`, 500,000) and every frame to 98% of what its parent has left, on the KV-update pool (`limit::KV_UPDATE_POOL`); a crossing reverts the frame with `MegaLimitExceeded(1, limit)` (`tests/satin/kv_updates.rs`), and the count is reported, in the outcome's usage and the block's.
+ The sender's account is the body's, not a record, and so are the fee credits the settlement makes, so a transaction that writes nothing counts none; a write execution makes to a fee account that is not the sender is a record like a write to any other account.
A record is forty bytes of data size, counted and taken back with them, so `KV × 40 ≤ data size` holds after every instruction (`tests/satin/write_records.rs`), and at the production data-size caps a transaction or a block keeps at most 327,680 records.
History gas prices every record.
-- No limit holds a transaction's state growth: EIP-8037 charges state gas for exactly the state a transaction adds, at the price of the SALT bucket it lands in, so what bounds it is what it costs — the transaction's gas limit and the block's (`tests/satin/state_growth.rs`).
+ At the spec's numbers 500,000 records weigh 20,000,000 bytes, more than `TX_DATA_LIMIT`, so the data size binds first; the KV check is still made.
+ An EIP-7702 list that would keep more records than the limit allows is skipped whole (`hold_authorization_list` in `evm/execution.rs`, see the authorization list below).
+- The state-growth limit holds the net count of new accounts and new slots a transaction keeps to `EvmTxRuntimeLimits::tx_state_growth_limit` (`TX_STATE_GROWTH_LIMIT`, 1,000) and every frame to 98% of what its parent has left, on the state-growth pool (`limit::STATE_GROWTH_POOL`); a crossing reverts the frame with `MegaLimitExceeded(3, limit)` (`tests/satin/state_growth.rs`), and the count is reported, in the outcome's usage (`LimitUsage::state_growth`, `max(net, 0)`) and the block's.
+ One unit rises where EIP-8037 charges the state gas of one, counted where the record of the same write is (`limit/record.rs`): an `SSTORE` from an original and present zero to non-zero, and falls on the write from an original zero back to zero; a value transfer that moves value its caller can fund to another account empty under EIP-161 (a value `CALL`, the transaction's own value), a creation at an empty address (the transaction's own included), both counted on the started frame and read off the journal before revm decides the start (`Accounts::transfer_growth`, `creation_growth`, in `FrameStart::of`, which loads a creation's address first where EIP-8037 is off and the opcode did not); a `SELFDESTRUCT` moving a balance to another account that does not exist; a creator's nonce bump that creates the creator, a keyless deployment's signer, counted with the creator's record on the creating frame once the creation returned (`Accounts::creator_counted`); and, before the first frame and on the transaction, each authority an applied authorization list created and the caller a deposit-like transaction created, which no failure takes back (`AdditionalLimit::count_authorities`, `count_created_caller`).
+ A fee credit, a `CALLCODE`, a value call to the calling account, deployed code and a delegation indicator are no rise; a failed frame's net goes with it.
+ An applied EIP-7702 authority counts as created where revm charged it as a new account — empty, loaded as not existing and untouched when the application reached it — read after the application as loaded as not existing, empty at the transaction's start and touched first by the application (`applied_authorities` in `evm/execution.rs`), so on a journal that runs several transactions unfinalized the count follows revm's charge, the flag of an earlier transaction's touch included (see the destruction table below).
+ EIP-8037 still charges state gas for exactly the state a transaction adds, at the price of the SALT bucket it lands in; the count is what stops the 1,001st slot, which the gas a transaction can pay would not.
+ An EIP-7702 list that would create more accounts than the limit allows is skipped whole, as one over the KV count is (`hold_authorization_list`).
+- The first effective `SELFDESTRUCT` of an account created in the transaction applies the destruction table (`limit/record.rs`, `DestroyedParts`; the completed-write hook in `evm/host.rs`): every part of the account the transaction made comes back to the destroying frame, whichever frame paid — the leaf when the transaction found no account there at its start (`Accounts::was_absent_at_start`: its original info empty, and the database answered none, `is_loaded_as_not_existing`, or an earlier transaction on the same journal destroyed it, which revm's record of this destruction names `LocallySelfdestroyed`), with its new-account state gas, its unit of state growth and the account's write record; the code deposited at it, with its state gas, its data size and its history; each slot it made non-zero from an original of zero, with its state gas, its unit and its record.
+ A part that existed at the start, such as the leaf of an address funded before the transaction or one empty under EIP-161 with storage, is an ordinary deletion: no refill, no fall, and its write record stands.
+ Every fact is the journal's: an account revm created in the transaction (`is_created_locally`), the first destruction of one (`SelfDestructResult::previously_destroyed` false), the account's original info and each slot's original value; a slot of an account created in the transaction that the journal does not hold yet loads as zero, so the slots it gives back are the ones it made non-zero, in key order.
+ revm's flags of an account the database answered none for and of a touched account are set at the account's first load or touch on the journal and outlive the transaction that set them on a journal that runs several transactions without finalizing; a fact about this transaction's start is read with what the journal records of this transaction: its original info, its entries (`JournalEntry::AccountDestroyed`'s status, `AccountTouched`), and the transaction id of what it loaded.
+ What the parts take back is in the same check as what the operation adds, so the beneficiary's record, its transfer log and its unit are held after the give-back; once the check passed, each part's state gas is refilled at the price it was charged, re-priced through `state_gas_price` at the site it landed on, with the history of the records and the schedule's history of the code, before the operation's own records are charged.
+ The refills follow the refill order, the frame's spill first; a failure of the destroying frame, or of a frame that contains it, takes back the mark with the journal and the give-back with the frame.
+ From the mark until the transaction ends the account counts nothing more (`Accounts::is_destroyed`): its nonce no longer is what the transaction loaded, so no write to it makes or takes back its record and a value moved to it adds no account, and an `SSTORE` of one of its slots counts nothing; the pricing hook prices every state charge on the account at nothing, so such an `SSTORE` neither charges nor refills fresh-slot state gas and code its own constructor deposits after destroying it (through a `DELEGATECALL`) is charged no state gas, whatever gas the frame holds, its data size and history standing; the table's own give-back prices the parts outside that rule (`MegaContext::priced_state_gas`).
+ A slot of the account loaded before the creation, which only a tool's load reaches, keeps the value it held at the start: the deletion refills nothing for it and makes its record while it still holds that value.
+ The account's logs stay counted.
+ The neutral configuration counts the table as the spec's does and prices state gas as the fixture's fork does, which gives none back for this destruction (`MegaContext::destruction_table_prices_state_gas`).
- The limits that change a result are protocol values fixed per spec, as the legacy engine's were: `ProtocolLimits::for_spec` (`block/limit.rs`) is the one table of them, keyed by `MegaSpecId`, with one arm, `SATIN`, every field written out.
- It holds the four per-transaction limits (`tx_runtime_limits`, an `EvmTxRuntimeLimits`: data size per transaction 13,107,200, no frame cap beyond the 98/100 share, detention's two caps 20,000,000 each) and the block's data-size budget, 13,107,200; the values are provisional with the constants.
+ It holds the per-transaction limits (`tx_runtime_limits`, an `EvmTxRuntimeLimits`: data size per transaction 13,107,200, KV updates per transaction 500,000, state growth per transaction 1,000, no frame cap beyond the 98/100 share, detention's two caps 20,000,000 each) and the block's three packing budgets, data size 13,107,200, KV updates 500,000 and state growth 1,000; the values are provisional with the constants.
No chain configuration carries them: they are not fork params, a genesis file names none, and a node passes none of them; a test holds them to what the removed load-time check held a chain's values to (none zero, the data size above `TX_BODY_SIZE`, the detention caps below `MAX_TX_COMPUTE_GAS`, 199,987,900, so detention binds), and `tests/block/l1_attributes.rs` holds the block's L1 attributes deposit to them.
Three layers keep three scopes: `ProtocolLimits::for_spec` the consensus values; `EvmTxRuntimeLimits` what one EVM runs under, the table's by default (`Default` is the default spec's), which a tool or a test may replace; `BlockLimits` the builder's policy, which only tightens.
`MegaContext::new` starts under its spec's limits, so an EVM from `MegaEvmFactory` (an RPC call, a simulation, a tool) and a bare context run under the limits block execution would hold their block to without being told; `MegaEvmFactory::with_tx_runtime_limits` and `MegaContext::with_tx_runtime_limits` are the explicit opt-outs, for equivalence, tools and tests.
- The block executor reads the table for the spec its EVM executes, installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to its data-size budget; `MegaBlockExecutor::with_protocol_limits`, which exists only under `cfg(test)` or `test-utils`, holds a block to other limits, for tests and for `mega-evme --override.limits`.
+ The block executor reads the table for the spec its EVM executes, installs `tx_runtime_limits` on the EVM at construction and again before every transaction, and holds the block to its packing budgets; `MegaBlockExecutor::with_protocol_limits`, which exists only under `cfg(test)` or `test-utils`, holds a block to other limits, for tests and for `mega-evme --override.limits`.
The block's gas limit is the executor's state (`BlockLimiter::block_gas_limit`), taken from the block environment; no policy carries one.
- The node's block context carries only building policy (`BlockLimits`): a transaction's declared gas, the encoded sizes and the data-availability sizes, which only a builder applies and never to a deposit, and a cap on the data-size budget that `BlockLimits::within` holds below the protocol's, so a policy tightens and never loosens; its default restricts nothing, and a validator leaves it so.
+ The node's block context carries only building policy (`BlockLimits`): a transaction's declared gas, the encoded sizes and the data-availability sizes, which only a builder applies and never to a deposit, and caps on the three packing budgets that `BlockLimits::within` holds below the protocol's, so a policy tightens and never loosens; its default restricts nothing, and a validator leaves it so.
A builder's policy changes which transactions it packs, never what a packed block computes (`tests/block/building_policy.rs`).
Satin carries no fork parameter: the `SequencerRegistry`'s roles are what the registry the legacy forks left holds.
A genesis file's `config` object carries Satin as one key, `satinTime`, and every reader — a node, a stateless validator, a genesis generator, `mega-evme --genesis` — reads it with `SatinChainConfig::from_genesis_config` (`block/genesis.rs`), which refuses any other key starting with `satin`, the registry, `satinInitialFromBlock` and limit keys of the format's earlier versions among them, a value that is not a 64-bit integer, and a schedule `validate_schedule` refuses; the key format is provisional.
- The protocol's own work is held to no per-transaction limit: a system-originated transaction (`system::is_system_originated`) and a system call — the pre-block calls among them — run under the layer's sticky exemption (`AdditionalLimit::exempt`), stamped before the body is counted, which every stop the layer hands out consults (`AdditionalLimit::crossed`), answering that nothing was crossed: no data-size limit and no frame budget stops them.
It is the set history gas exempts, for the same reason: the protocol's maintenance must not fail on a resource limit.
+ The exemption covers the KV updates and state growth beside data size.
What they use is counted all the same and reported, in the outcome's usage and in the block's counters, as a deposit's is.
- A block cap never refuses a pre-block call, which is no transaction of the block; a Mega System Transaction it refuses as any legacy transaction, because the block decides on the envelope (see the block executor below).
+ A block cap never refuses a pre-block call, which is no transaction of the block; a Mega System Transaction the block's packing budgets and the builder's policy never refuse, while the block's gas limit and the data-availability footprint hold it as any legacy transaction, because the block decides on the envelope (see the block executor below).
A user's deposit is not system-originated and is held to every per-transaction limit.
- Gas detention caps the compute a transaction may spend once it read volatile data — the block environment, the block beneficiary's account, the Oracle's storage — at its compute at the read plus a cap, a runtime limit of 20,000,000 by default (see Gas detention below).
It holds a frame's spendable gas with the revm fork's withheld part, which every reader of the frame's gas but a regular charge counts, so a detained transaction runs as it would without the read until a regular charge needs the withheld part.
@@ -222,11 +257,12 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat
The block's data-size limit, known only after execution, packs the transaction that reaches it and then refuses every later transaction before it runs.
It never refuses a deposit or a Mega System Transaction: it is a packing budget for the transactions the builder chooses, and neither is chosen; both still count towards it, so the transactions after them find the room they used.
Nor does the builder's policy refuse either.
- No block limit holds the execution, state or history ledger, or the write records: they are counted and reported.
- A deposit is the envelope's (`is_deposit` in `execute`): a Mega System Transaction is a legacy envelope, which an activation block refuses and which the data-availability limits and footprint hold like any non-deposit transaction, but the block decides before the engine promotes it that it is one (`MegaBlockTxResult::is_system_transaction`: a legacy call of the system shape from the live system address, read with `live_system_address` and `classify_system_transaction`), and the data-size budget and the builder's policy do not refuse it; the commit-time check reads the same flag.
+ The block's KV-update and state-growth limits (`BLOCK_KV_UPDATE_LIMIT`, 500,000 write records, and `BLOCK_STATE_GROWTH_LIMIT`, 1,000 new accounts and slots) are packing budgets of the same kind, checked after the data size and in that order (`BlockLimiter::pre_execution_check`), so a block full on several names the first; the transaction that reaches one is packed, every later ordinary one is refused before it runs, and neither refuses a deposit or a Mega System Transaction, which still count; the block's gas limit does not stand in for the state-growth budget (`tests/block/limits.rs`, `tests/block/system_tx_budgets.rs`).
+ No block limit holds the execution, state or history ledger: they are counted and reported.
+ A deposit is the envelope's (`is_deposit` in `execute`): a Mega System Transaction is a legacy envelope, which an activation block refuses and which the data-availability limits and footprint hold like any non-deposit transaction, but the block decides before the engine promotes it that it is one (`MegaBlockTxResult::is_system_transaction`: a legacy call of the system shape from the live system address, read with `live_system_address` and `classify_system_transaction`), and the packing budgets and the builder's policy do not refuse it; the commit-time check reads the same flag.
alloy-evm's `commit_transaction` cannot fail, and its contract is that an outcome commits before the next transaction executes; a builder that executes candidates and chooses among them commits through `commit_transaction_outcome`, which checks the counters again and refuses what no longer fits, and a debug build asserts the same check in `commit_transaction`.
The checked commit also refuses an outcome whose sender's nonce or balance — the system address's, for a system-address transaction — another commit moved since it executed (`MegaBlockExecutionError::StaleOutcome`, an internal error; the executor reads the sender's account before every transaction into `MegaBlockTxResult::{sender, sender_nonce, sender_balance}`), and a debug build asserts it in `commit_transaction`; any other state a candidate read is the builder's to keep fresh, which the system-transaction-first flow relies on (`tests/block/stale.rs`).
- It refuses a rewriting inspector at every entry point, and `apply_pre_execution_changes` commits each pre-block step's state on its own, in order, read-only entries included — that sequence of committed states, with the included transactions' and the exports, is the witness a stateless client needs, and a node collects it with a commit hook on its `State` (`State::set_state_hook`), which receives each state whole, where the block's transitions keep only what a state changed; after the two EIP calls it checks the seven predeploys in Satin's activation block alone (see below), applies a role change the `SequencerRegistry` has due in the block (see the system calls below), and last commits the L1 block contract's account and every slot the transactions can be priced against (`L1_BLOCK_INFO_SLOTS`: 1, 3, 5, 7 and 8) as read-only entries (`read_l1_block_info`), because op-revm and the executor read them on the block's state rather than through a transaction's journal, so they land in no transaction's state.
+ `apply_pre_execution_changes` commits each pre-block step's state on its own, in order, read-only entries included — that sequence of committed states, with the included transactions' and the exports, is the witness a stateless client needs, and a node collects it with a commit hook on its `State` (`State::set_state_hook`), which receives each state whole, where the block's transitions keep only what a state changed; after the two EIP calls it checks the seven predeploys in Satin's activation block alone (see below), applies a role change the `SequencerRegistry` has due in the block (see the system calls below), and last commits the L1 block contract's account and every slot the transactions can be priced against (`L1_BLOCK_INFO_SLOTS`: 1, 3, 5, 7 and 8) as read-only entries (`read_l1_block_info`), because op-revm and the executor read them on the block's state rather than through a transaction's journal, so they land in no transaction's state.
The overhead (5) is in the entry whatever the Ecotone scalars hold: op-revm reads it when the scalars it finds at the block's first non-deposit transaction are empty, which a deposit earlier in the block decides, so an entry listing it only under empty pre-block scalars would leave a read no state names (`tests/block/witness/state.rs`).
The pre-block step does not read the live system address: the executor reads it before every non-deposit transaction, as above, and every transaction reads it itself when it is validated (see below).
- Satin deploys, upgrades and seeds no contract: it runs on a chain that ran the legacy forks, which installed the six MegaETH system contracts at the versions Satin runs (the Oracle at v2.0.0, Rex5's, and the `SequencerRegistry` at v2.0.0, Rex6's), and whose genesis OP's tooling gave the EIP-7997 factory.
@@ -249,12 +285,12 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat
Every such read by a transaction is recorded with its answer on the transaction's outcome (`MegaTransactionOutcome::oracle_reads`, the context's `OracleReadRecord`, emptied before every transaction and system call), which is where a node building a stateless witness takes the oracle answers of the transactions it includes from.
- A `keylessDeploy(bytes,uint256)` call a transaction makes is a native keyless deployment (`system/keyless/`): the pre-EIP-155 creation it carries is deployed as a `CREATE` of its signer, at the signer's Nick's-Method address.
The dispatch (`keyless::is_dispatched`) runs in `frame_init` before interception, and revm builds the call's frame as any call's: on the contract, at depth 0, on revm's frame stack, with its own journal checkpoint and gas.
- No code runs in it: `frame_run` makes its actions by hand (`keyless::run`), on its first run the refusal or the creation, and on its resume, once the creation returned into it, the answer.
- An inspector sees the frames the deployment is made of: the call, started and ended as any call's, with no interpreter initialized and no step in it, and the creation as its child, one journal depth below.
+ No code runs in it: its actions are made by hand, its first where revm built the frame (`keyless::start`, in `frame_init`) — a refusal ends the frame before it runs, as the stop of a start does, and the creation is set on the frame's interpreter — and its answer once the creation returned into it (`keyless::answer`, in `frame_return_result`), set on the interpreter the same way; revm's frame run, plain or inspected, returns an action set on a frame before it runs.
+ An inspector sees the frames the deployment is made of: the call, started and ended as any call's, and the creation as its child, one journal depth below; the call's interpreter is handed to no `initialize_interp` and gets no `step`, since revm's inspected run returns an action set on a frame before any `step` and skips `initialize_interp` for a frame built with one, and a refused call is seen to start and end and nothing else.
It charges the fixed overhead, which pays for decoding the transaction and recovering its signer, and holds the call to the legacy engine's nine rules and error ABI in the legacy engine's order, so a call several rules refuse reports the legacy engine's error.
Among the rules it charges the signer's account when the creation's nonce bump creates it, SALT-priced state gas, where the legacy engine charged it; after every rule, what the `CREATE` opcode charges its frame: its regular gas (the schedule's `create` entry and EIP-3860's cost per word of init code), the created account, SALT-priced state gas, and the creation's two write records.
It then starts the creation at depth 1 with `CreateScheme::Custom` and `gasLimitOverride` capped to what the call has left, which must still cover the signed gas limit.
- Its lane is the one any depth-0 call pushes, running as the signer from the first run on.
+ It is held to its limits as any depth-0 call is, running as the signer from the first run on: the creation's start charge and share of its pool are the call's, and the signer's nonce record is counted on the call's pool once the creation returned, at the settlement (`keyless::settle`), as a `CREATE`'s creator's record is on the creator.
The creation returns into the call through `frame_return_result`, which reads the creation's outcome before revm merges it (`keyless::returning`) and takes the nonce back after (`keyless::settle`), before the call resumes, and the call answers in the ABI on its resume.
The frame is built on the contract as its target: the contract's account, which the transaction loads with its code to start its first frame, is touched by a call that returns, as a call's target is; a witness holds the account and its code for any transaction to the contract, so the frame adds nothing to it.
A call carrying value is refused `NoEtherTransfer()`, having paid the overhead, before revm builds its frame, so no value moves and nothing its start would write is counted.
@@ -278,21 +314,22 @@ The root `Cargo.toml` pins `revm = "=40.0.3"` and redirects all twelve revm crat
The read names no address unless the registry holds the code this engine requires (v2.0.0) and a non-zero address, so an absent, foreign or empty registry promotes nothing; in block execution Satin's activation block refuses a chain whose registry does not hold the code, and a later block runs on the state it is given.
It is a read of the transaction's own, so the slot is in every transaction's state and witness, not in the pre-block witness.
- A system call runs as EIP-8037 has it: at most 30,000,000 of its gas limit is regular gas, which is what `GAS` reads inside it, and the rest is its state-gas reservoir, which its state writes draw first before spilling onto the regular budget.
- The split is the fork's (`Handler::system_call_gas`, both system-call paths), switched on by `spec_cfg`; the neutral configuration leaves it off for both forks, as revm's runner does, and no state fixture makes a system call.
- A system call stays the protocol's own work: priced at the minimum SALT bucket, paying no history gas, held to no per-transaction limit and not detained, so it settles exactly as op-revm's does on the same configuration (`tests/satin/system_call.rs`, `tests/satin/equivalence.rs`).
+ The split is the handler's (`MegaHandler::tx_gas`, through which revm builds a system call's gas on both system-call paths), for every system call whatever the configuration (`MegaContext::splits_system_call_gas`); the neutral configuration leaves a system call's gas whole for both forks, as revm's runner does, and no state fixture makes a system call.
+ What a system call left of its reservoir is `AdditionalLimit::reservoir_remaining`, which revm's result does not carry.
+ A system call stays the protocol's own work: priced at the minimum SALT bucket, paying no history gas, held to no per-transaction limit and not detained, so it settles exactly as op-revm's does on the same configuration with the same split (`tests/satin/system_call.rs`, `tests/satin/equivalence.rs`).
A transaction is not a system call: every transaction's gas is split by the execution cap, the system-address transaction's included.
The system calls the engine makes, and their gas limits:
- | System call | Target | Gas limit | Regular | Reservoir |
- | ------------------------------------------------------------------------------------- | ------------------- | ----------------------------------------------------- | ------------------------ | --------------------------------------- |
- | EIP-2935 block hashes, pre-block | `0x0000F908…2935` | `pre_block_call_gas_limit`: max(block gas limit, 30M) | 30M | the block gas limit less 30M, or none |
- | EIP-4788 beacon root, pre-block | `0x000F3df6…Beac02` | the same | 30M | the same |
- | `SequencerRegistry.applyPendingChanges()`, pre-block, when a change is due | `0x6342…0006` | the same | 30M | the same |
- | alloy-evm's `transact_system_call`, revm's `SystemCallEvm` and `InspectSystemCallEvm` | the caller's | revm's `SYSTEM_CALL_GAS_LIMIT`, 31,566,720 | 30M | 1,566,720: sixteen fresh slots at m = 1 |
- | `MegaEvm::transact_system_call_with_gas_limit` | the caller's | the caller's | the lesser of it and 30M | the rest |
+ | System call | Target | Gas limit | Regular | Reservoir |
+ | ------------------------------------------------------------------------------------- | ------------------- | ------------------------------------------------- | ------- | --------------------------------------- |
+ | EIP-2935 block hashes, pre-block | `0x0000F908…2935` | `constants::PRE_BLOCK_CALL_GAS_LIMIT`, 31,566,720 | 30M | 1,566,720: sixteen fresh slots at m = 1 |
+ | EIP-4788 beacon root, pre-block | `0x000F3df6…Beac02` | the same | 30M | the same |
+ | `SequencerRegistry.applyPendingChanges()`, pre-block, when a change is due | `0x6342…0006` | the same | 30M | the same |
+ | alloy-evm's `transact_system_call`, revm's `SystemCallEvm` and `InspectSystemCallEvm` | the caller's | revm's `SYSTEM_CALL_GAS_LIMIT`, 31,566,720 | 30M | 1,566,720: sixteen fresh slots at m = 1 |
The pre-block calls run as the EIP-4788 system address (`0xff…fe`).
- Their budget is the legacy engine's, kept as it was rather than replaced: it was widened for the storage gas a crowded SALT bucket multiplied past 30M, which a system call no longer pays, and what it adds above 30M is reservoir, which nobody pays for when the call does not draw it; a block of 30M or less gives no reservoir, and the calls' few writes spill onto 30M of regular gas.
+ Their budget is one constant `MegaETH` owns, whatever the block's gas limit, which a pre-block call does not draw on: 30M of regular gas and a reservoir of sixteen fresh slots at the minimum bucket, which holds the most any pre-block call writes (six fresh slots, an `applyPendingChanges()` that applies both roles) more than twice over; it equals revm's default today and does not move with it.
+ None of the three contracts reads `GAS`, so the reservoir changes no call's result; the legacy engine's `max(block gas limit, 30M)`, widened for the storage gas a crowded SALT bucket multiplied, which a system call no longer pays, is gone.
A pre-block call that does not succeed refuses the block before its state is committed.
One helper runs all three pre-block calls and holds one rule for them (`block/eips.rs`, `transact_pre_block_call`): a database error the database calls fatal (`DBErrorMarker::is_fatal`) is an internal error (`BlockExecutionError::other`), because a read the database could not serve says nothing about the block and a node must not refuse a valid block because its storage failed; any other failure — a database error that is not fatal (under revm's `State`, an EIP-7928 block access list that does not cover a read), an EVM error other than the database's, or an outcome that is not a success — refuses the block with the call's own validation error (`BlockValidationError::BlockHashContractCall`, `BlockValidationError::BeaconRootContractCall`, `MegaBlockExecutionError::ApplyPendingChangesFailed`).
It is the rule alloy-evm's block executor holds a transaction's database error to (`BlockExecutionError::evm`).
@@ -309,54 +346,65 @@ Detention caps how much a transaction may still compute once it read such data (
- **What is volatile.**
The block environment (`NUMBER`, `TIMESTAMP`, `COINBASE`, `PREVRANDAO`, `GASLIMIT`, `BASEFEE`, `BLOBBASEFEE`, `SLOTNUM`, `BLOCKHASH`); the block beneficiary's account, through every account opcode, the four calls and the EIP-7702 delegate they follow, `SELFDESTRUCT` at either end, a sender or recipient that is the beneficiary, a recipient that delegates to it, an applied EIP-7702 authority that is, and a keyless deployment's signer that is (the call reads the signer's account through the journal, so it marks the read itself, at its compute then); the Oracle's storage, through `SLOAD` in the Oracle's own frame.
`BLOBHASH` is not: it reads the transaction's own blob hashes.
+ A call to the EIP-2935 history contract is a block-environment read, through the `NUMBER` its code runs before it loads the slot; the storage the EIP-2935 and EIP-4788 pre-block calls write is state the block starts with, and an `SLOAD` of it is none (`test_the_history_contract_reads_the_block_number_and_the_beacon_roots_contract_reads_state`).
A system-originated transaction and a system call are not detained, whatever they read, the block environment included: the same rule exempts them from every per-transaction limit.
Neither is a transaction under `no_limits()`, which the execution-spec gate's runner installs.
- **Where a read is marked.**
Where the Host loads the value (`evm/host.rs`), and committed by the opcode's wrapper once the opcode completed (`evm/instructions.rs`), as a write record is; a load that fails, and a read whose opcode then fails, mark nothing.
+ The Host refuses and marks a load only while a wrapper runs its opcode (`Detention::begin_read`): `CREATE`'s and `CREATE2`'s loads of their creator and created address, which revm makes through the Host, and an inspector's loads are no reads, neither refused nor marked, as a value call's check of its caller's balance is none.
- **The cap.**
Compute is the regular gas the transaction spends on what it runs, read off `Gas`: a frame's limit less what it has left — its withheld part included, so withheld gas is never spent — less the state and history gas that spilled onto its regular gas; what a halting frame burns is not compute either.
- The transaction's compute is the running frame's regular gas spent plus every suspended caller's, each less its child's gas limit, which takes a value call's stipend off with it, less what halts burned: the regular ledger at every moment, the burns taken out.
- The stipend stays outside compute on purpose, compute being regular gas drawn from the transaction's own pools: a callee may run up to 2,300 gas on each value call's stipend, and each value call costs its caller at least 9,100 of compute, so the gas run after a read is at most about 25% more than the cap.
+ The transaction's compute is the running frame's regular gas spent plus every suspended caller's, each less the gas it forwarded its child, plus the stipends of the value calls that returned, less what halts burned: every regular charge an instruction makes, whoever funds it, the burns taken out.
+ What a callee runs on a value call's stipend is compute: the stipend is not forwarded gas, so a caller's contribution while its child runs takes off its forward alone, and once a value call returned its stipend is counted apart, since what the callee left of it came back to the caller's gas on top of the forward; so compute is the regular ledger plus the stipends, less what halts burned, and the gas run after a read is at most the cap.
+ A precompile that runs out of gas counts nothing of its forward: its answer halts and burns it, a value call's stipend included.
A read sets a limit — the transaction's compute at the read plus its cap, `EvmTxRuntimeLimits::block_env_access_compute_gas_limit` or `oracle_access_compute_gas_limit`, 20,000,000 each by default (`BLOCK_ENV_ACCESS_COMPUTE_GAS`, `ORACLE_ACCESS_COMPUTE_GAS`) — and the limit only goes down, so the most restrictive read binds.
- Nothing per frame is kept for the figure until a read sets a limit: `MegaEvm::frame_init` records a caller's regular gas spent and gas limit when revm is about to build a child of it (`record_caller`, `Detention::on_child_build`), and the first read rebuilds what the frames it runs under add from those records (`Detention::track`); from there every frame is kept as it starts, suspends, resumes and ends, and debug builds keep the eager figures from the first frame on and assert the kept ones equal to them.
+ The frames' figures are kept for every transaction detention holds, from its first frame on, as each frame starts, suspends, resumes and ends, so a read at any depth finds the compute of the frames it runs under already summed.
`no_limits()` leaves both caps unlimited, and a transaction whose caps are both unlimited is not detained: that is how the neutral configuration's runner turns detention off.
It turns detention off together with every other per-transaction limit, so it is for equivalence mode and tests, not for executing the chain; `EvmTxRuntimeLimits::default()` and `ProtocolLimits::for_spec` detain, with caps below `MAX_TX_COMPUTE_GAS`, so a node running the chain never turns detention off.
- **The enforcement point: the withheld part.**
The revm fork keeps a frame's regular gas in two parts (`GasTracker`): a spendable part, the only one a regular charge draws, and a withheld part.
- Every other reader sees their sum — `GAS`, the 63/64 forward and the clamp on an explicit call gas, the `SSTORE` sentry, the skip-cold checks, the gas a child returns, the reimbursement — and a forward or a state or history spill draws the withheld part first.
- Detention holds a frame's spendable part at what the limit leaves the transaction (`Gas::limit_spendable`): at the read, once its wrapper committed it; at the frame's start and every resume (`before_frame_run`); and after `SSTORE`, whose restore of a slot to its original value refills regular gas.
+ Every other reader sees their sum — `GAS`, the 98/100 forward and the clamp on an explicit call gas, the `SSTORE` sentry, the skip-cold checks, the gas a child returns, the reimbursement — and a forward or a state or history spill draws the withheld part first.
+ The forward is Rex6's subtraction, `remaining − remaining × 2 / 100`, in place of EIP-150's 63/64: the fork's `GasParams::call_stipend_reduction` with the quotient 50 (the schedule's `GasId::call_stipend_reduction`) is that subtraction exactly, as `remaining − remaining / 50`; a value call's 2,300 stipend joins the forward after the cap, and a keyless deployment's creation keeps its own forward, `min(gasLimitOverride, remaining)`.
+ The neutral configuration (`MegaContext::with_neutral_cfg`) keeps EIP-150's 63/64, and gives a child the whole reservoir: equivalence mode is Ethereum's forward, not Satin's.
+ `no_limits()` is a separate switch.
+ It turns detention and every other per-transaction limit off, and it does not change the forward.
+ Detention holds a frame's spendable part at what the limit leaves the transaction (`Gas::limit_spendable`): at the read, once its wrapper committed it; at the frame's start, once revm built it (`frame_init`), and every resume (`frame_return_result`); and after `SSTORE`, in the completed-write hook, whose restore of a slot to its original value refills regular gas.
So a detained transaction runs exactly as it would without the read until a regular charge needs the withheld part: that charge fails as it would with nothing withheld, and the fork records a `WithheldCrossing` holding the regular gas the frame had before it, both parts together.
Nothing withheld is ever released: a frame's withheld part goes back to its caller with the rest of its gas, and `return_create`'s deposit and hash charges, the creating frame's own compute, draw the spendable part like any other regular charge.
- **The classification.**
A frame whose result carries a crossing record crossed the cap (`Detention::on_frame_end`).
- It is read in `after_frame_run`, after revm processed the frame's last action — `return_create` included — and before the result reaches the caller, or, for the transaction's own frame, `last_frame_result`, which overwrites the frame's gas with the transaction's.
+ It is read in the fork's run-result hook (`frame_run_result`, `end_frame`), which revm's plain and inspected loops call once a frame's run returns, after revm processed the frame's last action — `return_create` included — and before anything else sees the result: the inspector's `call_end`, `create_end` and `frame_end`, then `frame_return_result` and the caller, or, for the transaction's own frame, `last_frame_result`, which overwrites the frame's gas with the transaction's; only an out-of-gas is read, since a crossing only ever ends a frame on one.
+ So an inspector and a tracer see the frame end with the stop, as the receipt bills it, and a rewrite of the stop is taken as given like any other; a frame that ends before it runs, which `frame_init` returns, is classified where it ends (`end_before_it_runs`).
The frame becomes the stop's revert, `MegaLimitExceeded(2, limit)`, with its gas put back to the record's `remaining`: the charge that crossed is not made, the spendable and withheld parts go back to its caller, and the transaction's compute at the crossing is less than one charge short of the limit.
The caller resumes held to what the limit leaves, less than the charge that crossed, so a regular charge of its own past that crosses again and stops it in turn; one that ends within it ends the transaction within the limit.
The settlement is the same whether the halt zeroed the frame's gas (`OutOfGas`) or not (`MemoryOOG`, `return_create`'s own out-of-gas on a deposit charge).
- The stop reports the transaction's compute at the crossing as what was used (`LimitCheck::ExceedsLimit`), the figure the regular ledger bills, computed the same way at every crossing site; the size of the charge that crossed is not kept, so it is at most the limit, unless a halting frame's leftover, counted as compute, took the transaction past the limit before the charge.
+ The stop reports the transaction's compute at the crossing as what was used (`LimitCheck::ExceedsLimit`), the figure the regular ledger bills with the stipends of the transaction's value calls on top, computed the same way at every crossing site; the size of the charge that crossed is not kept, so it is at most the limit — but where an inspector's answer, taken as given, spent past what the limit left its frame, whose spending is its caller's compute.
Every other out-of-gas halts and burns as it would without the read: an operand above `usize`, a failed state or history charge, a regular charge beyond the frame's whole gas.
- **Answers.**
revm runs a precompile inside the frame's start, against the frame's gas limit, so a precompile forwarded more than the allowance its frame would start with is decided before it runs (`hold_precompile` in `MegaEvm::frame_init`).
One the engine prices (`PricedPrecompiles::price`, `evm/precompiles.rs`) is decided from its price, read with `Precompile::required_gas` off the Satin table's own entry: priced within the allowance, it runs on its whole forward, as without the read; priced past the allowance and within the forward, it is answered without running, out of gas and marked `WithheldCrossing::with_remaining(forward)` (`Detention::cross_at_price`), and stopped by the same classification; priced past its whole forward, it runs on the forward and runs out of gas, a failed call its caller survives, as without the read.
- A call revm refuses on its caller's account runs no precompile and is answered as without the read.
+ A call revm refuses on its caller's account runs no precompile and is answered as without the read: the answer given without running is not given to a value call whose caller cannot fund the value, which a comparison of the caller's balance with the value decides, as revm's transfer does.
+ None of this precedes the call's own regular charges, made at the opcode as any opcode's — its static gas, the value transfer, a cold access — and one that crosses stops the calling frame before the price is read, whether or not the caller can fund the value (`tests/satin/detained_transfers.rs`).
One residual is a choice: the price does not tell whether an input passes the checks a precompile makes after its gas check, so an input priced between the allowance and the forward that would fail such a check is the stop, where without the read the check fails the call, which its caller survives.
The Satin table prices an address only while the dispatched entry is still its own: not an address a node replaced through `MegaEvm::with_dyn_precompiles` (recorded, whatever id its precompile carries), not one whose dispatched entry carries another id, and nothing once the neutral configuration installed the fixture fork's set; a node's own precompiles carry no price either.
Every entry of the Satin table carries one, op-revm's size-limited wrappers of the BN254 pairing and the BLS12-381 MSMs and pairing included: the op-revm fork prices an input within a wrapper's size limit as the run it wraps does, and one past it, which the wrapper refuses before any gas check, at nothing.
alloy-evm's `PrecompilesMap` erases what it holds once a node changes it, so a change made around the engine, through the mutable reference to the map that revm's `EvmTr::all_mut` and alloy-evm's `Evm::components_mut` hand out, is not seen: an entry replaced through the map's mutable accessors under the replaced entry's id, and a whole set put in the map's place, whose entries are then priced from the Satin table wherever they carry its ids.
Neither accessor is a sign of a change — revm reaches the context through `all_mut` on every frame, and alloy-evm's tracer calls `components_mut` — so a node changes the set through `with_dyn_precompiles` or the factory's builder.
A precompile the engine cannot price is run on the allowance and sees it as its gas limit; its answer gets the rest of the forward back (`Detention::restore_forward`), and one that runs out of the allowance is marked as a crossing with its forward and stopped, whether its price is within the forward or not.
- An interceptor builds its answer on the whole forward, the caller's withheld part included: an answer that spent more regular gas than the allowance the frame would have run on is answered out of gas, marked with `set_withheld_crossing` — its spending the charge that crossed, so its frame gets its whole gas back, less a spill the revert credits — and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`, and on an inspector's answer in `inspect_frame_init`); the one answer of the engine's own that spends regular gas is that of a `keylessDeploy` call carrying value, and a crossing answer is settled on the limit the caller forwarded, whatever limit an inspector built it on.
+ An interceptor builds its answer on the whole forward, the caller's withheld part included: an answer that spent more regular gas than the allowance the frame would have run on is answered out of gas, marked with `set_withheld_crossing` — its spending the charge that crossed, so its frame gets its whole gas back, less a spill the revert credits — and stopped by the same classification (`settle_answer` in `MegaEvm::frame_init`); the one answer of the engine's own that spends regular gas is that of a `keylessDeploy` call carrying value, and a crossing answer is settled on the limit the caller forwarded.
+ An inspector's answer never reaches the engine's frame start, and is taken as given: no limit holds it.
An answer that halts otherwise burns its whole gas limit.
- **A keyless deployment's call.**
- The call is the transaction's own frame and runs no code, and detention holds it as any frame: its gas is held to what the limit leaves it when it first runs (`before_frame_run`), before it charges anything, so its own work — the overhead, then the `CREATE` opcode's regular gas — draws the spendable part, and a charge past the limit is a crossing its frame end stops, whether a rule would then have refused the call or its creation would have run.
+ The call is the transaction's own frame and runs no code, and detention holds it as any frame: its gas is held to what the limit leaves it once revm built it, before it charges anything, so its own work — the overhead, then the `CREATE` opcode's regular gas — draws the spendable part, and a charge past the limit is a crossing its frame end stops, whether a rule would then have refused the call or its creation would have run.
The forward to the creation is not the call's work and draws the withheld part first, as a `CREATE` opcode's does.
A call that starts its creation suspends on it as a frame suspends on its child, so the creation's first run adds the call's charges to the transaction's compute, as a caller's work before a `CREATE` is, and the creation runs under what the limit leaves it like any frame; its crossing stops the creation, and the call answers that stop as `ExecutionReverted` on its resume.
On its resume the call is held again, as every frame's resume is; it charges nothing more.
A call carrying value is an answer, held by the rule above.
- **What a halt burns.**
- An out-of-gas zeroes a frame's gas before the frame returns, so the wrapper of the opcode whose charge failed notes what the frame had first (`Detention::note_halt`); `KECCAK256` and the four copies into memory are wrapped for that alone, their charge having no bound, and so is `EXP`, whose exponent charge reaches 1,600; a frame-starting opcode that cannot pay its records hands the dropped frame's forward back before it fails.
- The one charge no wrapper sees is an opcode's static gas, which the step loop makes before the opcode runs: when it fails, what the halting frame had left counts as compute, per halting frame, under the failed charge's price (at most 4,999, on `SELFDESTRUCT`).
- Burned gas is counted as compute, so the stop comes earlier, never later; a frame whose leftover takes the compute past the limit does so without a crossing, so the stop is its caller's next charge, and the regular ledger at the stop holds that leftover's part past the limit beside the limit.
+ An out-of-gas zeroes a frame's gas before the frame returns, so the revm fork records what the frame had first: before every deduction that fails, an opcode's static gas, which the step loop charges before the opcode runs, included, and before a halt on a cold access the frame cannot pay (`Gas::failed_charge_remaining`); `Detention::on_frame_end` reads the record, and a halt that zeroes nothing leaves the frame's gas readable in its result.
+ So what every halting frame burns is exact, and none of it is compute.
+ A frame-starting opcode whose caller cannot pay the start's records starts no frame: the frame-start hook hands the forward back before the opcode fails, and records what the frame has then, since the failed charge recorded the gas left after the forward was taken.
+ An inspector's refused charge leaves its record as an opcode's does, as revm leaves it: a later halt that records nothing of its own is read off it.
- **Refused reads.**
`MegaAccessControl` switches volatile-data access off for the frame that calls `disableVolatileDataAccess()` and every frame below it, once the answer is settled and only when gas detention did not turn it into the stop (`Detention::disable_access_on_answer`), until that frame calls `enableVolatileDataAccess()` or returns; a frame below cannot switch back on what a frame above switched off (`DisabledByParent()`), and `isVolatileDataAccessDisabled()` answers for the caller.
The caller is the frame one level above the one the call would start (frame depth = the frame-init depth less one, where the legacy engine used the caller's journal depth, the same frame); a transaction that calls the contract directly has no frame above it, so disabling changes nothing, enabling succeeds and the query answers `false`.
@@ -370,68 +418,85 @@ Detention caps how much a transaction may still compute once it read such data (
Every later mechanism plugs into these; a change to one comes back to this layer.
-- **The Host only observes.**
- `sstore`, `log` and `selfdestruct` stage the facts revm hands them (`StagedRecord`) and record nothing.
- Recording in the Host would count a write the opcode's own failure takes back (an out-of-gas after the Host call), and a limit crossed there would stop a frame for a write that never happened.
-- **Commit after the opcode.**
- The wrappers of `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` discard a stale record on entry, run revm's instruction, then commit the staged record if the opcode completed and discard it if it failed, and charge the frame the history the record costs — which is the record's own data size, so the charge and the count are the same number.
- A `SELFDESTRUCT` that moved value also counts the transfer log revm journaled for the move, in the same check as its record, and is charged nothing for it.
- The wrappers of `CALL`, `CALLCODE`, `CREATE` and `CREATE2` charge their own frame for the records the frame they start makes, after revm computed the gas they forward, so the frame's budget carries none of them.
- Two things follow from charging after revm's instruction has built the frame's input: the frame carries a copy of the caller's reservoir, taken before the charge, so the wrapper writes the post-charge reservoir back into it — a frame that inherited the earlier one would hand the charge back on return, and a frame answered without running would hand it back twice.
- And the frame is already pending as the interpreter's action, which halts on an instruction's error only when no action is pending, so a caller that cannot pay drops the pending frame before it fails; otherwise the frame starts and its records are never paid for.
- The opcodes that can read volatile data run in detention's read wrapper, around the wrapper above when they have one (see Gas detention).
+- **Writes are counted once their opcode completed.**
+ The Host's write methods (`sstore`, `log`, `selfdestruct`) only write, whoever calls them.
+ revm's `SSTORE`, `LOG0`..`LOG4` and `SELFDESTRUCT` call the completed-write hook (`MegaContext::write_completed`) once the write is in the journal and every charge the opcode makes has been made, so a write the opcode's own failure takes back (an out-of-gas after the write) is never counted, and no limit stops a frame for a write that never happened.
+ A tool's write through the Host, an inspector's log among them, reaches no hook and is not counted.
+- **The completed-write hook.**
+ It counts the record on the running frame's pools (`AdditionalLimit::draw`) and holds it to the limits first — in each counted dimension the frame's budget, then the transaction's limit; a crossing is the stop, a revert of the frame — then charges the frame the history the record costs, which is the record's own data size, so the charge and the count are the same number: a log draws on the frame's history allowance first, a charge the frame cannot pay is an out-of-gas, and a record taken back refills its history.
+ A `SELFDESTRUCT` that moved value also counts the transfer log revm journaled for the move, in the same check as its records, and is charged nothing for it.
+ After an `SSTORE` it holds the frame to the compute limit again (`Detention::hold`, the one formula over the frame's `GasTracker`): a restore refills the state gas, revm before the hook, and the history gas, the hook, that spilled onto regular gas.
+- **The frame-start hook.**
+ revm's `CALL`, `CALLCODE`, `DELEGATECALL`, `STATICCALL`, `CREATE` and `CREATE2` call it (`MegaContext::frame_starting`) after every charge they make and after the forward is taken from the caller, before they build the frame's input: it charges the caller the history of the records the start makes, out of what the caller kept, and declares the part the frame's own records cost on the start (`FrameStart::charge`), which revm carries on the frame's input and outcome and refunds to the caller when the frame fails; the history of a creator's nonce record is charged there and not declared, the record outliving the creation.
+ The hook only prices, and counts nothing: a start's records are counted once revm decided it, and a creator's nonce record on the creator once the creation returned with the nonce bumped (`hold_creator`), so no count precedes revm's decision and nothing is given back.
+ After the hook revm takes the frame's share of the caller's reservoir and of each pool out of the caller (`GasTracker::forward_to_child`) and puts it on the frame's input, so a built frame and an answered start both inherit a share of the reservoir the charge left: `remaining − remaining × 2 / 100` (the schedule's `GasId::reservoir_kept_percent` = 2), whatever regular gas the caller asks to forward, the caller keeping the rest while the child runs, and the child's return adds what it left back to what the caller kept, unwinding the caller's outstanding spill first (`absorb_returned_reservoir`).
+ A keyless deployment's creation takes the same share of what the call has left after the call's start charges (`keyless::start`, through `forward_to_child`).
+ The transaction's own frame and a system call's outermost frame take the whole reservoir (the fork's `forward_all_to_child`), and the neutral configuration, on the fixture fork's schedule, gives every child the whole.
+ A caller that cannot pay, or a price that does not fit, gets the forward back and the halt's record re-written, and the opcode fails out of gas without starting a frame.
+ The records are one rule over caller, target and value (`Accounts::start_records`), asked at the opcode and again where revm decides the start, a creation's at the address it takes (`FrameStart::target`), and counted on the started frame's pool once revm decided it; a debug build holds those to what revm's start made of the accounts, exactly for every record.
+ A start an inspector rewrites after its opcode is not charged again: what the opcode charged stands, and its declared part comes back only as it does for any start whose frame keeps nothing — a frame that fails, or a start revm refuses before it bumps a nonce or moves a value; its records are those revm then made.
+- **The instruction table.**
+ The opcodes that can read volatile data run in detention's read wrapper (see Gas detention).
Every other opcode runs revm's instruction unwrapped, and the static gas table is revm's Amsterdam one.
- **Write records.**
- One 40-byte record per account or storage write: a slot's first change in the transaction (taken back on write-back to the original value), a value transfer's sender and recipient, a creation's creator nonce and created account, a `SELFDESTRUCT` moving value to another account, an applied EIP-7702 authority, the transaction's value recipient or created account.
- The sender's own account is part of the transaction body: it is never a record, and a frame running as the sender (through an EIP-7702 delegation) counts it as recorded.
- Records are deduplicated per frame (a frame's account is recorded once) and live on the frame's lane: a success merges the lane into the caller's, a failure discards it; a creator's nonce record survives the creation's failure once the nonce was bumped.
- That record lands on the creator after the creation's own check, so the creator is held to its budget with it before it runs on, and reverts alone if it crossed (`AdditionalLimit::on_frame_return`).
- The KV count a node reports is the write-record count; no limit holds it.
-- **Lanes stay aligned with frames.**
- `frame_init` pushes one lane per frame result revm will return, an empty one for a frame answered without running (the depth guard, an interceptor, an inspector); `frame_return_result` pops it, and `last_frame_result` pops the outermost one when it never ran.
- A `keylessDeploy` call's frame has the lane any depth-0 call has, and its creation's lane is pushed above it as any child's.
+ One 40-byte record per account or storage write, which follows the net change: a slot's record exists while its value differs from its original in the transaction (made by its first change, taken back on a write-back), an account's while its nonce, balance or code differs from what the transaction loaded, revm's original info (`Accounts::is_changed`): a start's records are read off the journal before revm makes the start — a value transfer's two sides on the balances it leaves them, a creation's creator and created account (an address the transaction funded, or a `SELFDESTRUCT` paid, before the creation lands on it is changed already, and the creation adds no record for it) — and a `SELFDESTRUCT`'s after it, its beneficiary and the account it clears rebuilt as they were from the balance it moved (`CompletedWrite::SelfDestruct::balance`); the applied EIP-7702 authorities and the transaction's own recipient or created account are counted where they are made.
+ So a transfer to an account already changed adds nothing, one that returns an account takes its record back (its history credited to the caller once the frame's start is kept), a value `CALLCODE` or a call to the calling account itself records nothing, and a start whose value the caller cannot fund is charged nothing.
+ The sender's own account is part of the transaction body: validation changes it before execution, so no write to it — a frame running as the sender (through an EIP-7702 delegation), value sent back to it — records it again; a fee account is unchanged until execution writes it, which records it.
+ Records live on the pool of the frame that made them: a success hands them to the caller, a failure takes them back and puts back what the frame took back; a creator's nonce record is the creating frame's, counted on its pool once the creation returned with the nonce bumped, the creation's share having been taken at the opcode before it, so it survives the creation's failure and is held to the creator's budget, not the creation's.
+ It is held to the creator's budget and then to the transaction's limit as it is counted, before the creator runs on, which reverts alone if it crossed (`hold_creator`).
+ The KV count a node reports is the write-record count, which the KV-update limit holds.
+- **The byte pool decides.**
+ A frame's data-size budget is the byte pool on its gas tracker, which the revm fork forwards and settles as it does the reservoir: what the transaction's own execution keeps is drawn there where it is made — a frame start's records and transfer log on the started frame, a completed write and a deposit's code from the Host's hooks — and a frame that fails gives its draws back with its state and history gas.
+ The transaction's limit is held beside the pools, on what the transaction keeps (`AdditionalLimit::usage`): the body, the hints and the authorities' records, which are no frame's, and the frames' draws, counted with them and restored to what they were at a start when that start's frame keeps nothing (`AdditionalLimit::close_start`, one entry per start revm decided, keyed by its depth).
+ The entry also carries what a pool cannot: the write-record count and the transfer logs the transaction reports apart from its bytes, the take-back credit a kept start gives its caller, and a creation's creator as it stood before revm decided it.
+ Nothing a tool or a precompile writes is drawn or counted: only the hooks draw, and only where the transaction's own execution writes; a tool's checkpoint the tool reverts takes the writes back but not the draws.
+ Every verdict is the layer's: a completed write's, a deposit's and a hint's check, a frame's budget, the verdict on a start once revm decided it (the hypothetical one for a call gas detention answers without running), the check of a caller at every child's return; a start's history comes back to its caller with the fork's start charge when the frame fails, and the price of the records a kept start took back on the frame's result before revm merges it.
+- **A start's charge rides on revm's carriers.**
+ The frame-start hook declares what a start's own records cost on the start (`FrameStart::charge`), revm carries it on the frame's input and outcome and refunds it when the frame fails, for a frame it built and an answer it gave alike; the transaction's own frame carries its record's charge on its input from `first_frame_input`, refunded by the shared first-frame settlement. An answer the engine builds itself carries its input's share and charge (`synthetic_frame_result`); an inspector's answer carries what the inspector built it with.
+ The history allowance a value call gives its child is the fork's tracker field, set from the schedule's `call_history_allowance`; only a log draws on it.
- **The stop.**
- A limit stops the frame that crosses it with a revert, never a halt, whether the limit is the transaction's or the frame's own budget: the frame reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)` (`AdditionalLimit::crossed`, the one verdict, which the exemption answers), what it counted goes with its lane, and its caller resumes as after any revert.
- There is no latch: a caller that resumes is within every limit, is held to what the transaction has left, and is stopped in turn by a write or a charge of its own that crosses one, so the transaction never keeps more than its data-size limit and computes past detention's limit only by what halting frames left; a caller that catches the stop and ends lets the transaction succeed.
- The frame budget is what keeps a caller's own work within reach of a callee: a child inherits the whole reservoir and history gas draws it first, so gas does not bound what a child appends, and without a budget a callee could take the transaction to its limit and leave the caller that caught its stop nothing to carry on with.
- The one stop a frame returns before running another instruction is the one a child left it (`AdditionalLimit::stop_before_run`, `before_frame_run`): a failed creation's nonce record, which lands on its creator unchecked, putting the creator over a limit.
- A stop of the transaction's own frame is the transaction's result, which settles like an EIP-8037 revert, its unspent regular gas and the reservoir back to the sender.
+ A limit stops the frame that crosses it with a revert, never a halt, whether the limit is the transaction's or the frame's own budget: the frame reverts with `MegaLimitExceeded(uint8 kind, uint64 limit)` (`AdditionalLimit::crossed`, for the data size and gas detention's compute stop alike, answering the exemption), what it counted goes with its frame, and its caller resumes as after any revert.
+ There is no latch: a caller that resumes is within every limit — but where a failure below it put back a record a frame above made while a hint the failed frame sent stays, which stops the caller as it resumes (below) — is held to what the transaction has left, and is stopped in turn by a write or a charge of its own that crosses one, so the transaction never keeps more than its data-size limit and never computes past detention's limit; a caller that catches the stop and ends lets the transaction succeed.
+ The frame budget is what keeps a caller's own work within reach of a callee: a child inherits 98/100 of the caller's reservoir and history gas draws it first, so gas does not bound what a child appends, and without a budget a callee could take the transaction to its limit and leave the caller that caught its stop nothing to carry on with; the reservoir the caller keeps, `remaining × 2 / 100`, is what is left of its gas for state and history whatever the child spends.
+ A child gets 98/100 of the remaining reservoir by the subtraction `remaining − remaining × 2 / 100`, and 98/100 of the parent's remaining data size by `parent_remaining × 98 / 100`, rounded down.
+ The neutral configuration keeps the whole reservoir and EIP-150's 63/64 forward.
+ A frame returns a stop before running another instruction in two cases: when its own start crossed a limit once revm built it, which ends the frame in `frame_init` before it runs, returned as an answer is (`end_before_it_runs`); and on a resume, when the nonce record of a creation it made, counted on it as the creation returns, puts it over a limit (`hold_creator`), or a child's failure leaves the transaction over one — the failure restores what the frames kept at the child's start, and an Oracle hint the child sent into room a take-back freed stays (`AdditionalLimit::hold_caller`) — which `frame_return_result` sets on the frame's interpreter for its run to return.
+ A stop of the transaction's own frame is the transaction's result, which settles like an EIP-8037 revert, its unspent regular gas and the reservoir back to the sender; the history charged before execution for that frame's write record comes back with its start charge at the settlement, whenever the frame did not keep the record.
Nothing is rescued for the sender on a stop, because nothing was taken from it: the stop settles on the gas the frames hold, and detention withholds inside a frame's own tracker.
A stop of the transaction's own frame reverts what the frames did, the first frame's value and write record included, and nothing pre-execution applied: an admitted EIP-7702 authority keeps its nonce, its delegation, its state gas, its record and that record's history, and a deposit keeps its mint and the caller account it created, as through any failed first frame (`tests/satin/state_growth.rs`).
- A limit is enforced before the writes it guards: a frame whose start would cross it is answered with the stop before revm builds it (a creation still bumps its creator's nonce, so a stopped creation transaction cannot be replayed).
+ A limit is enforced on the writes it guards before anything runs on them: a frame whose start crosses it returns the stop before its first instruction, or its answer gives way to the stop, and what the start moved goes back with it (a creation keeps its creator's nonce bump, which revm makes before the frame's checkpoint, so a stopped creation transaction cannot be replayed).
Nothing counted before the first frame crosses the data-size limit: validation (`MegaHandler::validate_initial_tx_gas`, before any gas check) refuses a transaction whose body, with a 40-byte record for each entry of its authorization list, exceeds it (`AdditionalLimit::admits_tx_body`, `TX_BODY_OVER_DATA_SIZE_LIMIT`, an `InvalidTransaction::Str`), the system-originated exempt; a deposit refused so is a failed deposit, and a pool refuses it through `validate_transaction_stateless` alike.
- `record_tx_body` is a pure count, and `record_applied_authorities` asserts in debug builds that the records cannot cross; at the spec's numbers the gas checks already bound a body with its records to 6,732,889 bytes (`tests/satin/pool_validation.rs`).
+ The body is a pure count, and `AdditionalLimit::count_authorities` asserts in debug builds that the records cannot cross; at the spec's numbers the gas checks already bound a body with its records to 6,732,889 bytes (`tests/satin/pool_validation.rs`).
A frame revm answers with a success and the engine then rewrites to the stop — gas detention's crossing — has its journal taken back to where its start began, at any depth, as revm takes back a frame that fails (`take_back_a_stopped_answer`): its caller resumes and keeps its own writes, and no caller's revert follows to take the answer's back.
- A record is checked before its history is charged, so a record the limit rejects is not charged and the stop is what its frame reports; at a frame start the caller pays at its opcode, before the records are counted, so there an out-of-gas comes first.
+ A record is checked before its history is charged, so a record the limit rejects is not charged and the stop is what its frame reports; at a frame start the caller pays at its opcode, before revm decides the start and its records are held to the limits, so there an out-of-gas comes first, even for a start revm then refuses.
A real out-of-gas, a precompile out-of-gas and an invalid opcode still halt and burn; an out-of-gas before the first frame takes back what pre-execution counted and keeps the body.
The layer's state belongs to one transaction: the handler resets it first thing, in `validate_env`, once it knows whether the transaction is the protocol's own, and every system-call entry point of `MegaEvm` resets it before it runs the handler's system-call path.
- The outcome's `limit_exceeded`, not the output, tells a stop from a contract reverting with the same bytes: it names the crossing that produced the result of the transaction's own frame — a transaction-level limit or that frame's own data-size budget — noted where the stop became a frame's result (`AdditionalLimit::note_frame_stop`) and kept only while that frame's result is still the stop's revert; a stop a caller caught, and re-raised or not, is none.
+ The outcome's `limit_exceeded`, not the output, tells a stop from a contract reverting with the same bytes: it names the crossing that produced the result of the transaction's own frame — a transaction-level limit or that frame's own budget in data size, KV updates or state growth — noted where the stop became a frame's result (`AdditionalLimit::note_frame_stop`) and kept only while that frame's result is still the stop's revert; a stop a caller caught, and re-raised or not, is none.
`LimitStop::from_result` (and `MegaTransactionOutcome::limit_stop`) reads a stop off the two together, for an RPC's error; `decode_mega_limit_exceeded` reads the bytes alone, which make no stop by themselves.
- `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as frames that kept nothing.
+ `tests/satin/stops.rs` pins the protocol as a matrix: every limit crossed by the transaction's own frame and three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as the successes the inspector made of them.
- **A per-frame gas cap stays inside the frame's tracker.**
- Detention caps a frame's regular gas with the fork's withheld part (`Gas::limit_spendable`), which every reader of the frame's gas but a regular charge counts, so it moves no gas between pools and has nothing to release: a child's withheld part goes back to its caller with the rest of its gas, and a stop settles on the crossing record where the frame ends (`after_frame_run`).
+ Detention caps a frame's regular gas with the fork's withheld part (`Gas::limit_spendable`), which every reader of the frame's gas but a regular charge counts, so it moves no gas between pools and has nothing to release: a child's withheld part goes back to its caller with the rest of its gas, and a stop settles on the crossing record where the frame's run returns (`frame_run_result`).
A later mechanism that caps a frame's gas uses the same part; it limits the frame at its start and again after every credit — a child's return, `SSTORE`'s refill — and never releases a creating frame's withheld part before `return_create`, whose charges are the frame's own regular charges.
- **Synthetic frame results carry the caller's pools.**
- A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir (`untouched_call_gas`, `with_pools_of`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags, so it settles exactly like revm's own (`settle_frame_result`).
-- **The admission gate.**
- A rewriting inspector is a tool feature; `with_trusted_inspector` requires a `TrustedObserver` declaration, `has_rewriting_inspector` is what block execution refuses — as an internal error, since the inspector is the node's choice and no verdict on the block — and `DeclaredObserver` carries the declaration for a foreign tracer and proves it in debug builds.
- alloy-evm's `BlockExecutorFactory` asks for an executor for every `I: Inspector`, so the refusal cannot be a bound on the type: block execution checks it wherever an outcome is produced or chosen — the pre-block changes, a transaction's execution, the end of the block and `commit_transaction_outcome`, the checked commit — because an inspector can be enabled after the block was set up and a caller can run transactions without setting it up.
- alloy-evm's `commit_transaction` checks nothing and needs no check: it cannot fail, runs no code, and commits the outcome the last execution produced under the gate, which no inspector enabled since can reach.
- `create_executor_with_trusted_inspector` is the compile-time proof; `create_executor` is the checked route.
- In a block a declared observer sees the transactions, user and system alike, and nothing else: the pre-block calls run on the handler's plain system-call path, as alloy-evm's `transact_system_call` runs one, and the end of the block runs no code; the module doc of `evm/inspector.rs` holds the map of what an inspector sees and may rewrite in each phase.
- No rewrite is refused: a failed creation an inspector turns into a success settles as a frame that kept nothing, like a call it revives (below), and its caller is handed the address the inspector gave.
- A creation stopped by a limit is a failed creation like any other, and is settled the same way if revived.
+ A result built without running a frame is a `synthetic_frame_result`: gas untouched with the inherited reservoir and byte share (`untouched_call_gas`, `untouched_create_gas`), never `Gas::new(limit)`, and the calling opcode's upfront state-gas flags and start charge, so revm's own frame return settles it exactly like a result of its own.
+- **Inspectors in block execution.**
+ Block execution admits any inspector: which inspectors may run on block production is a node's decision, not the engine's.
+ A block builds from an EVM the node made with `MegaEvmFactory::create_evm_with_inspector` (or `MegaEvm::with_inspector`) and `MegaBlockExecutorFactory::create_executor` (or `MegaBlockExecutor::new`).
+ An inspector sees the transactions, user and system alike, and nothing else: the pre-block calls run on the handler's plain system-call path, as alloy-evm's `transact_system_call` runs one, and the end of the block runs no code; the `evm` module doc holds what an inspector sees and may rewrite.
+ `test_utils::ReadOnlyObserver` wraps an inspector that is meant to write nothing back and proves it in debug builds, for tests.
+ No rewrite is refused, and none is corrected: the engine takes a rewritten result as given (below).
The test utilities' inspectors are not declared.
-- **A frame that kept nothing settles as one, whatever an inspector made of its result.**
- A frame an inspector answered in place of running never started, and a frame that failed had its journal checkpoint reverted before the inspector saw its result.
- Whatever the inspector hands the caller for either, the caller gets the success, the output and the regular gas it chose, and nothing else (`settle_kept_nothing` in `evm/inspector.rs`): no state or history gas and no refund, no write record — the lane is discarded as a failure's, and the history its caller paid for the records comes back — and the upfront state gas its caller's opcode was charged for an account the frame did not add comes back — for a call, as recorded before the inspector's hooks ran, so a rewritten target does not change the price it comes back at — as does, for the transaction's own frame, the history of its write record.
- So Foundry's `expectRevert` on a call that wrote and reverted bills the transaction as the revert does.
- The reverse holds too: a success an inspector rewrites into a failure has its journal taken back to the frame's checkpoint — for a start revm answered without building a frame, to where the start began — as revm takes back a frame that fails, so the state follows the failure its ledgers settle as (`ResultSource` and `revert_journal_to` in `evm/inspector.rs`); a creation keeps its creator's nonce bump, which revm makes before the checkpoint, and the journal's depth is left as it was.
- Everything journaled since the checkpoint goes, what the inspector wrote to the journal in the callback that rewrote the result included: the one place the rewrite and a real failure part, since revm takes a failed frame back before `call_end`.
+- **A rewritten result is taken as given, as revm takes it.**
+ revm commits or reverts a frame's journal checkpoint before the inspector sees the frame's result, and the caller settles the result the inspector hands back, its classification, output and gas, reservoir and byte pool included; the engine adds nothing to that settlement.
+ A failed frame revived into a success — Foundry's `expectRevert` on a call that wrote and reverted — keeps its journal reverted and settles as a success: its state gas, history, refund and the records it counted merge into its caller, and the upfront charge its caller's opcode made stays.
+ A success rewritten into a failure keeps its journal, the inspector's own writes in that callback included, and settles as a failure: its charges roll back, its counts are restored with its start's entry and its start charge is refunded.
+ A frame an inspector answers in place of running never started: what its caller's opcode was charged for it — the upfront state gas and the history of its start's records — stays charged unless the answer carries the upfront-charge flags and the start charge back; a creation's creator record is not counted, revm having bumped no nonce, and its history stays charged; and the answer settles on the gas it is built on.
+ So a tool's state and its ledgers can part under a rewrite, as they do under revm; keeping them consistent is the tool's business, and block execution runs no rewriting inspector the node did not choose.
+ The write records and transfer logs the transaction reports follow the result its caller settles, as the byte pool does (`AdditionalLimit::close_start`).
- **An inspector's writes to gas.**
Gas an inspector writes in the `step_end` of a frame's last instruction reaches nobody: the instruction copied the frame's gas into its result; the result's gas, rewritten in `call_end`, is what the caller merges, reservoir included.
- An answer is the exception: the frame it stands for never ran, so it carries nothing but the regular gas the inspector chose, and its caller merges back the reservoir it forwarded whatever `Gas` the answer was built on — `Gas::new(limit)`, which Foundry answers every cheatcode on, carries none, and Foundry's default gas limit of 2^30 is above the execution cap.
- A charge the frame cannot pay is refused and takes nothing, and the frame runs on; revm's instruction loop sees the inspector through `StepGuard`, which puts back the withheld-part crossing such a refusal records, so gas detention never stops a frame for an inspector's charge.
+ An answer settles on the `Gas` it is built on: `Gas::new(limit)`, which Foundry answers every cheatcode on, carries no reservoir and unlimited pools, so above the execution cap — Foundry's default gas limit of 2^30 is above it — the caller is left only the 2 per cent of its reservoir it kept when it handed the call its share, as the fork's add-settlement has it.
+ A charge the frame cannot pay is refused and takes nothing, and the frame runs on, with the record of the refused charge left on its gas, as revm leaves it: a withheld-part crossing stops nothing in a frame that ends without an out-of-gas, and a later halt that records nothing of its own is read off the failed-charge record.
An inspector that overwrites the interpreter's gas (Foundry's `pauseGasMetering` restores a snapshot before every instruction) overwrites detention's split with it, and the frame runs on the snapshot's split until detention next holds it: at a read, a start or resume, or after an `SSTORE`.
- **The interceptor dispatch.**
Its order is the scheme guard, the address, the selector, then the method's value policy, each step cheaper than the next: `CALLCODE` and `DELEGATECALL` never reach an interceptor, because they run the callee's code in the caller's context; the address test is one comparison against the shared `0x6342…` prefix and runs on every call a transaction makes; the selector is peeked without materialising the calldata behind it, and is admitted on its four bytes alone, trailing bytes and all.
@@ -443,6 +508,8 @@ Every later mechanism plugs into these; a change to one comes back to this layer
`Host::state_gas_price(id, site)` is the single place an EIP-8037 state gas charge is priced.
A charge is given back two ways, and neither reads a second table: `SSTORE`'s own restore, a caller's upfront charge for a call or creation that did not add the leaf, the transaction-level refund and the settlement of a synthetic frame result re-price the same `(id, site)` pair through the hook; a frame that fails rolls its own charges back by the amounts it recorded while running, without asking for a price at all.
Both cancel the charge exactly whatever the price was — the re-priced sites because a bucket's multiplier is read once per transaction, so the two cannot disagree even if the environment's answer would, and the rolled-back amounts because nothing but the hook priced them.
+ The one exception is an inspector's: revm reads the account a call's upfront charge is given back for off the frame's inputs, so an inspector that rewrites a call's target has the charge given back at the new target's price, as under revm (`tests/satin/inspector_settlement.rs`).
+ A charge on an account created in the transaction and destroyed since prices at nothing: its destruction gave back what the transaction had charged for it, at the prices charged and outside that rule (`MegaContext::priced_state_gas`), so a re-pricing after the mark — the restore of a slot it gave back — gives back nothing a second time.
A mechanism that adds a state charge adds a `StateGasCharge` at the site the state lands on; it must not price the charge itself.
- **Three ledgers, and the bytes beside the third.**
`MegaGasUsage` splits a transaction's raw spend into regular (compute), state and history gas, all paid from the EIP-8037 pools, reservoir first; state or history gas that spilled onto regular gas stays on its own ledger.
@@ -453,14 +520,15 @@ Every later mechanism plugs into these; a change to one comes back to this layer
It is the history the schedule prices, not the chain's physical growth: an exempt transaction's bytes are not in it, and a body counts its five fixed write records even when fewer fee accounts are written.
For a transaction that pays history it is the data size the transaction kept less its Oracle hints' payloads and its transfer logs: both columns read one count at every site, deployed code included, which the data-size limit makes before the creation commits and only for code revm deposits.
`gas_used` is the receipt's figure; `BlockGasCounters` sums the three ledgers and the history bytes per block.
+ `reservoir_remaining` is what the EIP-8037 reservoir held where revm built the result's gas, before the EIP-7623 floor absorbs it; revm's `ResultGas` does not carry it, so the handler reads it and the layer reports it (`AdditionalLimit::reservoir_remaining`), for a system call too.
## Test Organization (`crates/mega-evm/tests/`)
- `satin/` — tests of the Satin engine (integration tests; add new ones here or in a new directory with a `main.rs`).
-- `block/` — tests of block execution: the Karst block rules, the block-level limits, the counters, the factory and the admission gate; under `block/witness/`, the witness-replay harness: a block executed on a recorder of every read, then again on a strict database and environments that serve exactly a witness — the record of every read, and the witness a node builds from the states the block committed (the pre-block steps' and the included transactions') and the exports — each replay held to the recording, one case per mechanism that reads and per read that gas or a limit skips.
+- `block/` — tests of block execution: the Karst block rules, the block-level limits, the counters and the factory; under `block/witness/`, the witness-replay harness: a block executed on a recorder of every read, then again on a strict database and environments that serve exactly a witness — the record of every read, and the witness a node builds from the states the block committed (the pre-block steps' and the included transactions') and the exports — each replay held to the recording, one case per mechanism that reads and per read that gas or a limit skips.
- `system/` — tests of the system contracts: the interceptor dispatch, what each contract answers, keyless deployment (`system/keyless/`) and the system-address transaction.
- `fuzz/` — randomized tests: properties the engine must hold on any input, and the neutral differential against op-revm and revm's mainnet EVM (see Randomized tests below).
-- `shared/` — no target: `snapshot.rs` holds `assert_sorted_json_snapshot!`, which every target includes with `#[path = "../shared/snapshot.rs"] mod snapshot;`.
+- `shared/` — no target: `snapshot.rs` holds `assert_sorted_json_snapshot!`, which every target includes with `#[path = "../shared/snapshot.rs"] mod snapshot;`, and `op_reference.rs` the op-revm reference the baselines compare with, op-revm's handler with Satin's system-call split and the reservoir its result settled with, which the `satin` and `block` targets include the same way.
It has no `main.rs`, so Cargo builds nothing there; the snapshot files live in `snapshots/` beside the file that asserts.
- Unit tests live next to the code in `#[cfg(test)] mod tests`.
@@ -490,12 +558,13 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te
- **A failure is reproducible.**
The runner panics with the property's name, the reason, the seed and case count that reproduce the run, and the case proptest shrank to within its shrink limits (two minutes and 4,096 steps, so not always the minimal one), rendered as the generator types (`Case`, `BlockCase`), from which a regression test is written by hand into `regressions.rs`.
- **The generators** (`gen/`) build a `Case`: a `World` (four fixed accounts, a beneficiary that may be one of them, a delegation, SALT capacities with multipliers above one and a failing bucket, the Oracle's answers, runtime limits in place of the spec's, the block), a `Tx` of one of six shapes (call, creation, EIP-7702, deposit, system-address, keyless) at five gas tiers, and the `Program`s of the three contracts, lists of self-contained ops biased towards what the engine meters.
+ A call, an account read or a `SELFDESTRUCT` may name the address one of the program's own `CREATE2` ops lands on (`Target::Created`), so a program can fund or pay an account before it creates it.
A keyless deployment carries its own world: the signer's funds, nonce and code, what the deploy address holds, how the carried transaction is encoded and what it is signed for, so that each of its rules is reached.
The keyless property also pads one init code in eight with zero bytes, which never run, to the initcode size limit, one byte past it or twice it; the other properties draw init code at its own size, since a mebibyte of calldata in their cases would buy nothing they check.
The weights keep what refuses a transaction before it runs rare — about one case in five — because most properties have nothing to check of a refusal.
`Case::execute` runs it on a fresh EVM; `blocks.rs` runs envelopes through `MegaBlockExecutor`.
`Flavor::Neutral` replaces what only `MegaETH` has by its plain counterpart, for the differential, and `Case::without_destruction_in_creation` takes every self-destruction out of init code for the one comparison that settles it otherwise, Ethereum's on Amsterdam.
-- **What the properties state** (`properties.rs`, `keyless.rs`, `blocks.rs`, `differential.rs`): the same outcome twice, under a recording inspector, and on an EVM that already ran another transaction, one that ended in an error included; the gas ledgers, the reservoir exactly; `KV × 40 ≤ data size` after every instruction, and every transaction keeps its body and the hints it forwarded; what a stop keeps; a keyless deployment's rules in the spec's order, its answer and its signer's nonce; a block's counters as the sum of what its transactions report, and its budgets; the neutral differential.
+- **What the properties state** (`properties.rs`, `keyless.rs`, `blocks.rs`, `differential.rs`): the same outcome twice, under a recording inspector, and on an EVM that already ran another transaction, one that ended in an error included; the gas ledgers, the reservoir exactly; `KV × 40 ≤ data size` after every instruction, and every transaction keeps its body and the hints it forwarded; the write-record count as the net change of the state, computed from the case's pre-state and the outcome's state with the settlement's fee credits taken out; what a stop keeps; a keyless deployment's rules in the spec's order, its answer and its signer's nonce; a block's counters as the sum of what its transactions report, and its budgets; the neutral differential.
A panic fails whichever property draws the case.
Several print a tally of what they reached (`--nocapture`): how the previous transaction ended, each keyless rule, the cases rewritten for Amsterdam.
- **To add a property**, write a `#[test]` that calls `harness::check(name, bounded_cases, || case(Flavor::Satin), |case| { ... })` and returns `Err` through `prop_eq!` / `prop_check!` where the outcome breaks the property; keep the bounded case count such that the whole target stays under a minute in debug.
@@ -513,6 +582,9 @@ for s in $(seq 1 20); do MEGA_FUZZ_SEED=$s cargo test --release -p mega-evm --te
- **The op-revm baseline** (`tests/satin/equivalence.rs`): an ordinary transaction through `MegaEvm` against op-revm on the same configuration, which Satin differs from by its history ledger alone.
- **The execution-spec gate** (`crates/mega-state-test`, `.github/workflows/exec-spec-satin.yml`): Ethereum's state-test fixtures through `MegaEvm`, on the fixture releases the fork's own runner (`.github/workflows/exec-spec.yml`) uses.
- Equivalence mode is the gate: Satin's machinery — handler, frame lifecycle, Host, instruction table — priced as the fixture's fork prices it, through the neutral configuration (`MegaContext::with_neutral_cfg`, `test_utils::{neutral_cfg, neutralize_evm}`), which exists only behind `test-utils`, and held to no runtime limit (`EvmTxRuntimeLimits::no_limits()`, installed by the runner itself).
+ The neutral configuration keeps EIP-150's 63/64 forward and gives a child the whole reservoir.
+ `no_limits()` is the separate switch that turns the per-transaction limits off.
+ The counts it reports (`LimitUsage`: data size, write records, state growth) are the engine's own, by Satin's rules, and no fixture checks them: the neutral configuration prices what the fixture's fork prices and counts what Satin counts, the destruction table's give-backs included, so a change to a counting rule moves an equivalence-mode transaction's whole-outcome digest in `usage` alone, which is that change's and is no deviation.
Every failure must be explained by a deviation in `crates/mega-state-test/src/deviations.rs`, with its rule, its reason and the exact entries it explains, each with the hashes Satin produces, and every listed entry must fail exactly as listed; the executed and skipped counts are pinned in the workflow and equal the fork runner's.
- Satin mode is a report: the same fixtures under Satin's own configuration, counted by outcome in the step summary; it never fails the job.
- The blockchain tests are a gate too (`state-test btest`, `crates/mega-state-test/src/blockchain/`): the main release's Osaka `blockchain_tests`, imported block by block through `MegaBlockExecutor` on `MegaEvm` in equivalence mode's configuration, held to no limit (`ProtocolLimits::no_limits()`, installed by the runner through the executor's test-and-tool override), as the state-test runner holds a transaction.
@@ -601,7 +673,7 @@ When the agent is requested to implement a new feature or bug fix, it should con
- **Keep the op-revm baseline honest.**
A change that makes Satin differ from op-revm on purpose must update `tests/satin/equivalence.rs` (or add a case) so the difference is pinned, not silently absorbed.
- **Hold a test at any byte price.**
- A gas limit is regular room on top of what the scenario adds at the prices in effect (`satin_gas_params()`, `history_gas`), never a number that happened to cover it at the constants; a call or creation that forwards all but a 64th of its gas keeps 64 times the history of the records it pays for.
+ A gas limit is regular room on top of what the scenario adds at the prices in effect (`satin_gas_params()`, `history_gas`), never a number that happened to cover it at the constants; a call or creation that forwards all but 2 per cent of its gas keeps a fiftieth of what it held, so it must hold 50 times the history of the records it pays for (`common::holding_to_keep` inverts the split).
A charge a scenario must not be able to pay is derived the same way — a gas limit one short of it — not a number that is short of it only while a byte is dear.
A test that pins the spec's own numbers returns early at other prices (`runs_at_measurement_prices`); run `scripts/price_grid.sh --pr` before committing a test change.
- **Pin only outputs with no computable expectation.**
diff --git a/Cargo.lock b/Cargo.lock
index b50a95875..869ba3e17 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1914,7 +1914,7 @@ version = "3.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"
dependencies = [
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -2384,7 +2384,7 @@ dependencies = [
"libc",
"option-ext",
"redox_users",
- "windows-sys 0.61.2",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -2514,7 +2514,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "778e2ac28f6c47af28e4907f13ffd1e1ddbd400980a9abd7c8df189bf578a5ad"
dependencies = [
"libc",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -3316,7 +3316,7 @@ checksum = "e04d7f318608d35d4b61ddd75cbdaee86b023ebe2bd5a66ee0915f0bf93095a9"
dependencies = [
"hermit-abi",
"libc",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -3917,7 +3917,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [
- "windows-sys 0.61.2",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -4259,7 +4259,7 @@ dependencies = [
[[package]]
name = "op-revm"
version = "20.0.0"
-source = "git+https://github.com/megaeth-labs/op-revm?tag=v20.0.0-mega.3#58bc98e2fcaffcdea23595b2680fc68daddd7b69"
+source = "git+https://github.com/megaeth-labs/op-revm?rev=f599efdabc3e5b36a280f1aa72978751bd64c160#f599efdabc3e5b36a280f1aa72978751bd64c160"
dependencies = [
"auto_impl",
"revm 40.0.3",
@@ -5196,7 +5196,7 @@ dependencies = [
[[package]]
name = "revm"
version = "40.0.3"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"revm-bytecode 11.0.1",
"revm-context 18.0.3",
@@ -5227,7 +5227,7 @@ dependencies = [
[[package]]
name = "revm-bytecode"
version = "11.0.1"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"bitvec",
"phf 0.13.1",
@@ -5254,7 +5254,7 @@ dependencies = [
[[package]]
name = "revm-context"
version = "18.0.3"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"bitvec",
"cfg-if",
@@ -5286,7 +5286,7 @@ dependencies = [
[[package]]
name = "revm-context-interface"
version = "19.0.3"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"alloy-eip2930",
"alloy-eip7702",
@@ -5318,7 +5318,7 @@ dependencies = [
[[package]]
name = "revm-database"
version = "15.0.2"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"alloy-eips 2.1.1",
"alloy-provider 2.1.1",
@@ -5349,7 +5349,7 @@ dependencies = [
[[package]]
name = "revm-database-interface"
version = "12.1.1"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"auto_impl",
"either",
@@ -5382,7 +5382,7 @@ dependencies = [
[[package]]
name = "revm-handler"
version = "20.0.3"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"auto_impl",
"derive-where",
@@ -5418,7 +5418,7 @@ dependencies = [
[[package]]
name = "revm-inspector"
version = "21.0.3"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"auto_impl",
"either",
@@ -5483,7 +5483,7 @@ dependencies = [
[[package]]
name = "revm-interpreter"
version = "37.0.3"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"revm-bytecode 11.0.1",
"revm-context-interface 19.0.3",
@@ -5523,7 +5523,7 @@ dependencies = [
[[package]]
name = "revm-precompile"
version = "36.0.3"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"ark-bls12-381",
"ark-bn254",
@@ -5559,7 +5559,7 @@ dependencies = [
[[package]]
name = "revm-primitives"
version = "24.0.1"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"alloy-primitives",
"once_cell",
@@ -5581,7 +5581,7 @@ dependencies = [
[[package]]
name = "revm-state"
version = "12.0.1"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"alloy-eip7928 0.4.11",
"bitflags 2.11.1",
@@ -5594,7 +5594,7 @@ dependencies = [
[[package]]
name = "revm-statetest-types"
version = "19.0.3"
-source = "git+https://github.com/megaeth-labs/revm?tag=v40.0.3-mega.4#b706bb1a0f1359ee0a73825e4743300c260494ec"
+source = "git+https://github.com/megaeth-labs/revm?rev=2fc8edf33b2ffddb195cebc17be9adabfd95417c#2fc8edf33b2ffddb195cebc17be9adabfd95417c"
dependencies = [
"alloy-eip7928 0.4.11",
"k256",
@@ -5764,7 +5764,7 @@ dependencies = [
"errno",
"libc",
"linux-raw-sys",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -6429,7 +6429,7 @@ dependencies = [
"getrandom 0.3.3",
"once_cell",
"rustix",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
]
[[package]]
@@ -6985,7 +6985,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
]
[[package]]
diff --git a/Cargo.toml b/Cargo.toml
index ae3ba2ae5..319b4d467 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -232,20 +232,20 @@ codegen-units = 1
[patch.crates-io]
# megaeth fork of revm (revm 40.0.3 + the revm 43 gas core + the megaeth hooks).
# All twelve crates move together, otherwise the build resolves a second copy of revm.
-revm = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
-revm-primitives = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
-revm-interpreter = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
-revm-context = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
-revm-context-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
-revm-handler = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
-revm-database = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
-revm-database-interface = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
-revm-state = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
-revm-bytecode = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
-revm-precompile = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
-revm-inspector = { git = "https://github.com/megaeth-labs/revm", tag = "v40.0.3-mega.4" }
+revm = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
+revm-primitives = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
+revm-interpreter = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
+revm-context = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
+revm-context-interface = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
+revm-handler = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
+revm-database = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
+revm-database-interface = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
+revm-state = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
+revm-bytecode = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
+revm-precompile = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
+revm-inspector = { git = "https://github.com/megaeth-labs/revm", rev = "2fc8edf33b2ffddb195cebc17be9adabfd95417c" }
[patch."https://github.com/ethereum-optimism/optimism"]
# megaeth fork of op-revm (the OP monorepo copy ported to the revm fork's gas core), built
-# against the revm tag above.
-op-revm = { git = "https://github.com/megaeth-labs/op-revm", tag = "v20.0.0-mega.3" }
+# against the revm pin above.
+op-revm = { git = "https://github.com/megaeth-labs/op-revm", rev = "f599efdabc3e5b36a280f1aa72978751bd64c160" }
diff --git a/REVIEW.md b/REVIEW.md
index 8451aeeb4..d04b1ce12 100644
--- a/REVIEW.md
+++ b/REVIEW.md
@@ -24,27 +24,28 @@ Defer to the baseline for everything not listed here; the rules below take prece
- Pre-block helpers (the activation block's predeploy check, pre-block system calls, the registry's due-change read, the L1 block info read) return their state (an `EvmState`, or a `ResultAndState` for a system call) for the block executor to commit on its own, in order; they never call `db.commit(...)`.
An idempotent "no change" path returns an `EvmState` that carries the observed account as a read-only entry; returning nothing drops the account from the stateless witness read set and produces an incomplete proof.
The same applies inside execution: read through the journal with revm's own loads (`load_account`, `sload`), never `journal.database.basic(...)`, or the account driving the result is missing from the returned state.
-- **The Host only observes; the opcode's wrapper commits.**
- `sstore`, `log` and `selfdestruct` stage a record and record nothing; the wrapper commits it after the opcode completed and discards it if the opcode failed.
+- **A write is counted once its opcode completed.**
+ The Host's `sstore`, `log` and `selfdestruct` only write and count nothing; revm's write instructions call the completed-write hook (`Host::write_completed`) after every charge they make, and the frame-starting instructions call the frame-start hook (`Host::frame_starting`) after the forward and before the frame's input is built.
A record, a charge or a read mark made before the opcode can still fail counts a write that never happened.
- Check that every exit path of a wrapped instruction (stack underflow, out of gas, decode failure, a failed inner call) leaves the staged record discarded and nothing counted.
+ The frame-start hook only prices: a start's records are counted once revm decided it, and a creator's nonce record on the creator once the creation returned with the nonce bumped (`hold_creator`), so no count precedes revm's decision and none is given back.
+ Check that nothing is counted in the Host's write methods, that no charge lands in a write instruction after the hook (the fork's call sites), and that the engine's matches over `CompletedWrite` and `FrameStartKind` carry no wildcard arm.
- **A limit is enforced before the write it guards.**
- A limit — the transaction's or a frame's budget — stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, never with a halt, and its caller resumes within every limit; a stop of the transaction's own frame keeps the gas its frames hold, and nothing is taken from the sender on a stop.
+ A limit — the transaction's or a frame's budget — stops the frame that crosses it with a revert carrying `MegaLimitExceeded`, never with a halt, and its caller resumes within every limit, unless the failure put back a record a frame above made while an Oracle hint the failed frame sent stays, when the caller returns the transaction's stop as it resumes; a stop of the transaction's own frame keeps the gas its frames hold, and nothing is taken from the sender on a stop.
Flag a stop that surfaces as a halt, a limit that is checked after the state change it guards, a stopped frame whose writes, logs or counted bytes survive into its caller, and an answer the engine turns into the stop whose journal is not taken back.
The outcome's `limit_exceeded`, not the output bytes, tells a stop from a contract that reverts with the same bytes.
-- **Lanes, pools and ledgers stay aligned with frames.**
- `frame_init` pushes one lane per frame result revm returns, including a frame answered without running; a synthetic frame result carries the caller's pools (`synthetic_frame_result`), never `Gas::new(limit)`.
- A mechanism that adds a state charge goes through `Host::state_gas_price` at the site the state lands on and does not price the charge itself; a charge is given back at the price it was made at.
+- **Pools and ledgers stay aligned with frames.**
+ A frame's byte pool is on its gas tracker and settles with it; `frame_init` opens one entry per start revm decided (`AdditionalLimit::open_start`), which the result returning at that depth closes (`close_start`), and a start revm did not decide opens none; a synthetic frame result carries the caller's pools (`synthetic_frame_result`), never `Gas::new(limit)`.
+ A mechanism that adds a state charge goes through `Host::state_gas_price` at the site the state lands on and does not price the charge itself; a charge is given back at the price it was made at, unless an inspector rewrote the call's target, which revm reads the refund's account off.
The three ledgers (regular, state, history) add up to the raw spend, and the block counts `max(regular, floor)` with history taken out first.
- **Gas detention caps a frame inside the frame's own tracker.**
It withholds a part of the frame's regular gas (`Gas::limit_spendable`) that every reader but a regular charge counts, so there is nothing to move or release; a mechanism that caps a frame's gas uses the same part, holds the frame at its start and after every credit, and never releases a creating frame's withheld part before `return_create`.
A read of volatile data is marked where the Host loads the value and committed by the opcode's wrapper once the opcode completed; a new volatile-derived read or side effect (the block environment, the beneficiary's account through any account opcode, the Oracle's storage, an EIP-7702 delegate) has to be marked, and the delegate resolved before marking.
Flag a bound or an economic claim in a comment or the spec that the code does not meet.
- **Keyless deployment is a native creation.**
- The `keylessDeploy` call's frame runs no code and makes its actions by hand; check that the creation's outcome returns into the call through `frame_return_result`, that every effect (gas, the data-size lane, volatile access, logs, state) is reconciled in the one frame stack, that the signer's nonce rule holds on success and on failure, and that a value validated before execution (a gas-limit override) is not mutated afterwards.
+ The `keylessDeploy` call's frame runs no code and makes its actions by hand; check that the creation's outcome returns into the call through `frame_return_result`, that every effect (gas, the data-size pool, volatile access, logs, state) is reconciled in the one frame stack, that the signer's nonce rule holds on success and on failure, and that a value validated before execution (a gas-limit override) is not mutated afterwards.
- **The interceptor dispatch is ordered cheapest-first and fails closed.**
The call-scheme guard, then the address, then the selector, then the method's value policy; only `CALL` and `STATICCALL` reach an interceptor; an unknown selector is not intercepted and falls through to the contract's bytecode; a method that takes no value answers a value-bearing call with its error.
-- **System calls and system-address transactions:** a system call and a system-originated transaction are exempt from the per-transaction limits and history gas, priced at the minimum SALT bucket and not detained; a pre-block call with dynamic cost takes a `block.gas_limit`-derived budget; a database error the database calls fatal is an internal error and any other failure refuses the block with the call's own validation error; a system-address transaction validates nonce, chain id and EIP-3607 against replay, and a commit step that re-checks block limits re-checks the sender's nonce and balance too.
+- **System calls and system-address transactions:** a system call and a system-originated transaction are exempt from the per-transaction limits and history gas, priced at the minimum SALT bucket and not detained; a pre-block call runs on the one pre-block budget (`constants::PRE_BLOCK_CALL_GAS_LIMIT`), whatever the block's gas limit; a database error the database calls fatal is an internal error and any other failure refuses the block with the call's own validation error; a system-address transaction validates nonce, chain id and EIP-3607 against replay, and a commit step that re-checks block limits re-checks the sender's nonce and balance too.
- **The stateless witness must hold every read.**
A change that makes block execution read state outside a transaction's journal commits the read as a read-only entry of a pre-block state or exports it, and adds a witness-replay case; nothing may depend on which source (the database, the SALT environment, the oracle service) answered.
- **Hot-path accounting stays O(1)** in attacker-controlled call depth and authorization count — no frame-stack walk per opcode, no unindexed `Vec` scan per authorization.
@@ -77,7 +78,7 @@ Defer to the baseline for everything not listed here; the rules below take prece
Flag a new state-gas assertion that lacks it: the failure only shows in the configuration nobody watches.
- Every other test holds at a byte price of nothing and at any price from one gas per byte up to the grid's dearest point, and the byte-price grid job checks it.
Below one gas per byte the schedule's entries round to nothing one at a time, and past the grid a fixed-size scenario outgrows any transaction below the execution cap; no test is held there.
- A gas limit is its regular room on top of what the scenario adds at the prices in effect, read off the schedule and `history_gas`, not a number that happened to cover it at the constants; a call or creation that forwards all but a 64th of its gas keeps 64 times the history of the records it pays for.
+ A gas limit is its regular room on top of what the scenario adds at the prices in effect, read off the schedule and `history_gas`, not a number that happened to cover it at the constants; a call or creation that forwards all but 2 per cent of its gas keeps a fiftieth of it, so it must hold 50 times the history of the records it pays for.
A case whose scenario is state or history gas — a limit to cross, a bucket to scale, a charge that cannot be paid — returns early where that byte costs nothing (`state_is_free`, `history_is_free` in each test target's `common.rs`), and its other assertions still run.
- **Benchmark methodology.**
A perf-comparison PR must pin comparable hardforks on both arms.
diff --git a/bin/mega-evme/AGENTS.md b/bin/mega-evme/AGENTS.md
index 780505a48..96d1408c1 100644
--- a/bin/mega-evme/AGENTS.md
+++ b/bin/mega-evme/AGENTS.md
@@ -14,6 +14,7 @@ Two engines: the in-tree sources run Satin; a spec from `Equivalence` to `Rex6`
- `src/tx/`: full transaction execution command with raw-tx override support.
- `src/replay/`: RPC-backed historical transaction replay through block executor (Satin; a legacy spec is the 1.7.1 CLI's).
- `src/block/`: `replay --block`, whole blocks on either engine compared with the chain: inputs and the block cache (`inputs.rs`), the parent state in plain data (`state.rs`), one executor per engine exchanging only plain data (`satin.rs`, `legacy.rs`), the plain data both hand back (`exec.rs`), records and the comparison (`record.rs`), the driver (`cmd.rs`).
+- `tests/fixtures/blocks.tar.xz`: the three recorded Rex6 blocks and their code store in the block cache layout, one deterministic archive extracted once per test binary (`tests/common/mod.rs`); `scripts/pack_blocks_fixture.py ` repacks it, `--check` requires a repack of the committed archive to be byte-identical.
- `tests/satin-differences.md`: the pinned differences between the engines, rendered by `tests/differences.rs` (`UPDATE_EVME_DIFFERENCES=1` rewrites it).
## KEY PATTERNS
diff --git a/bin/mega-evme/Cargo.toml b/bin/mega-evme/Cargo.toml
index ebdf0760f..13ec51fe6 100644
--- a/bin/mega-evme/Cargo.toml
+++ b/bin/mega-evme/Cargo.toml
@@ -9,6 +9,8 @@ repository.workspace = true
description = "MegaETH executable EVM"
readme = "README.md"
default-run = "mega-evme"
+# Test data and the scripts that pack it stay out of the published crate.
+exclude = ["scripts/", "tests/fixtures/"]
[lints]
workspace = true
diff --git a/bin/mega-evme/scripts/pack_blocks_fixture.py b/bin/mega-evme/scripts/pack_blocks_fixture.py
new file mode 100644
index 000000000..6c16ae049
--- /dev/null
+++ b/bin/mega-evme/scripts/pack_blocks_fixture.py
@@ -0,0 +1,55 @@
+#!/usr/bin/env python3
+"""Pack a block cache tree into the deterministic `tests/fixtures/blocks.tar.xz`.
+
+Usage: scripts/pack_blocks_fixture.py []
+
+`` holds `blocks/` and `codes/`.
+Members are regular files only, in sorted path order, in ustar with mode 0644, uid/gid 0, empty
+owner names and mtime 0; the tar is compressed with xz preset 9 extreme, single-threaded.
+Packing the same files therefore always gives the same bytes.
+`--check ` unpacks nothing: it repacks the archive's own members and requires the same bytes.
+"""
+import io
+import lzma
+import sys
+import tarfile
+from pathlib import Path
+
+DEFAULT_ARCHIVE = Path(__file__).resolve().parent.parent / "tests/fixtures/blocks.tar.xz"
+
+
+def pack(members):
+ """members: sorted list of (relative posix path, bytes)."""
+ raw = io.BytesIO()
+ with tarfile.open(fileobj=raw, mode="w", format=tarfile.USTAR_FORMAT) as tar:
+ for name, data in members:
+ info = tarfile.TarInfo(name)
+ info.size = len(data)
+ info.mode = 0o644
+ info.uid = info.gid = 0
+ info.uname = info.gname = ""
+ info.mtime = 0
+ tar.addfile(info, io.BytesIO(data))
+ filters = [{"id": lzma.FILTER_LZMA2, "preset": 9 | lzma.PRESET_EXTREME}]
+ return lzma.compress(raw.getvalue(), format=lzma.FORMAT_XZ, check=lzma.CHECK_CRC64, filters=filters)
+
+
+def main():
+ args = sys.argv[1:]
+ if args and args[0] == "--check":
+ archive = Path(args[1] if len(args) > 1 else DEFAULT_ARCHIVE)
+ with tarfile.open(archive, "r:xz") as tar:
+ members = [(m.name, tar.extractfile(m).read()) for m in tar.getmembers() if m.isfile()]
+ if pack(members) != archive.read_bytes():
+ sys.exit(f"{archive}: a repack of its members differs")
+ print(f"{archive}: repack is byte-identical")
+ return
+ root = Path(args[0])
+ out = Path(args[1]) if len(args) > 1 else DEFAULT_ARCHIVE
+ files = sorted(p for p in root.rglob("*") if p.is_file())
+ members = [(p.relative_to(root).as_posix(), p.read_bytes()) for p in files]
+ out.write_bytes(pack(members))
+ print(f"{out}: {len(members)} members, {out.stat().st_size} bytes")
+
+
+main()
diff --git a/bin/mega-evme/src/block/record.rs b/bin/mega-evme/src/block/record.rs
index 7c1dde2bb..31cc673d8 100644
--- a/bin/mega-evme/src/block/record.rs
+++ b/bin/mega-evme/src/block/record.rs
@@ -215,6 +215,7 @@ fn sum_satin<'a>(reports: impl Iterator) -> SatinReport
floor_gas: acc.floor_gas + r.floor_gas,
data_size: acc.data_size + r.data_size,
write_records: acc.write_records + r.write_records,
+ state_growth: acc.state_growth + r.state_growth,
limit_exceeded: None,
limits_override: None,
})
diff --git a/bin/mega-evme/src/block/satin.rs b/bin/mega-evme/src/block/satin.rs
index 3e2eb3159..9917d2a9d 100644
--- a/bin/mega-evme/src/block/satin.rs
+++ b/bin/mega-evme/src/block/satin.rs
@@ -4,16 +4,15 @@ use alloy_consensus::transaction::Recovered;
use alloy_eips::{Decodable2718, Encodable2718};
use alloy_primitives::U256;
use mega_evm::{
- alloy_evm::{block::BlockExecutor, EvmEnv},
+ alloy_evm::{block::BlockExecutor, EvmEnv, EvmFactory},
alloy_op_evm::block::OpAlloyReceiptBuilder,
revm::{
context::{result::ExecutionResult, BlockEnv, CfgEnv},
database::State,
- inspector::NoOpInspector,
primitives::eip4844,
},
- BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory,
- MegaHardforkConfig, MegaHardforks, MegaSpecId, MegaTxEnvelope, ProtocolLimits,
+ BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforkConfig,
+ MegaHardforks, MegaSpecId, MegaTxEnvelope, ProtocolLimits,
};
use super::{
@@ -68,11 +67,7 @@ pub(super) fn execute(
for &(bucket, capacity) in bucket_capacities {
envs = envs.with_bucket_capacity(bucket, capacity);
}
- let factory = MegaBlockExecutorFactory::new(
- OpAlloyReceiptBuilder::default(),
- &hardforks,
- MegaEvmFactory::new().with_external_env_factory(envs),
- );
+ let evm_factory = MegaEvmFactory::new().with_external_env_factory(envs);
let only_deposits =
admits_only_deposits(&hardforks, header.number, parent_timestamp, header.timestamp)?;
// Without the parent's timestamp the block admits every transaction only where no fork the
@@ -90,12 +85,9 @@ pub(super) fn execute(
let result = {
let mut db = State::builder().with_database(SatinDb(state)).with_bundle_update().build();
- let mut executor = factory.create_executor_with_trusted_inspector(
- &mut db,
- EvmEnv::new(cfg, block_env),
- block_ctx,
- NoOpInspector,
- );
+ let evm = evm_factory.create_evm(&mut db, EvmEnv::new(cfg, block_env));
+ let mut executor =
+ MegaBlockExecutor::new(evm, block_ctx, &hardforks, OpAlloyReceiptBuilder::default());
if let Some(limits) = limits_override {
executor = executor.with_protocol_limits(limits);
}
diff --git a/bin/mega-evme/src/common/outcome.rs b/bin/mega-evme/src/common/outcome.rs
index 942cbfe83..bb9f78360 100644
--- a/bin/mega-evme/src/common/outcome.rs
+++ b/bin/mega-evme/src/common/outcome.rs
@@ -60,8 +60,11 @@ pub struct SatinReport {
pub data_size: u64,
/// Account and storage write records the transaction kept: its KV count.
pub write_records: u64,
+ /// New accounts and new storage slots the transaction kept, net: its state growth.
+ pub state_growth: u64,
/// The limit that stopped the transaction, if one did: the crossing that produced the result
- /// of its own frame, a transaction-level limit or that frame's own data-size budget.
+ /// of its own frame, a transaction-level limit or that frame's own budget in data size, KV
+ /// updates or state growth.
pub limit_exceeded: Option,
/// The protocol limits the run was held to, in the shape `--override.limits` takes them;
/// present only when that flag replaced the schedule's, so the record of a counterfactual
@@ -73,7 +76,7 @@ pub struct SatinReport {
/// A limit that stopped a Satin transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct LimitStop {
- /// The dimension: `data_size` or `compute_gas`.
+ /// The dimension: `data_size`, `kv_updates`, `compute_gas` or `state_growth`.
pub kind: &'static str,
/// The limit crossed, in the dimension's unit.
pub limit: u64,
@@ -94,6 +97,7 @@ impl SatinReport {
floor_gas: gas.floor,
data_size: outcome.usage.data_size,
write_records: outcome.usage.write_records,
+ state_growth: outcome.usage.state_growth,
limit_exceeded: match outcome.limit_exceeded {
Some(LimitCheck::ExceedsLimit { kind, limit, used, .. }) => {
Some(LimitStop { kind: limit_kind_name(kind), limit, used })
@@ -109,7 +113,9 @@ impl SatinReport {
pub const fn limit_kind_name(kind: LimitKind) -> &'static str {
match kind {
LimitKind::DataSize => "data_size",
+ LimitKind::KvUpdate => "kv_updates",
LimitKind::ComputeGas => "compute_gas",
+ LimitKind::StateGrowth => "state_growth",
}
}
@@ -253,6 +259,7 @@ pub fn print_satin_report(report: &SatinReport) {
println!("Floor Gas: {}", report.floor_gas);
println!("Data Size: {}", report.data_size);
println!("Write Records: {}", report.write_records);
+ println!("State Growth: {}", report.state_growth);
if let Some(stop) = report.limit_exceeded {
println!("Limit Exceeded: {} (limit {}, used {})", stop.kind, stop.limit, stop.used);
}
diff --git a/bin/mega-evme/src/replay/cmd.rs b/bin/mega-evme/src/replay/cmd.rs
index 032b47bff..b2256685e 100644
--- a/bin/mega-evme/src/replay/cmd.rs
+++ b/bin/mega-evme/src/replay/cmd.rs
@@ -8,7 +8,7 @@ use clap::Parser;
use mega_evm::{
alloy_evm::{
block::{BlockExecutionError, BlockExecutor},
- Evm, EvmEnv,
+ Evm, EvmEnv, EvmFactory,
},
alloy_op_evm::block::OpAlloyReceiptBuilder,
revm::{
@@ -19,8 +19,8 @@ use mega_evm::{
primitives::{eip4844, Address, Log},
DatabaseRef, Inspector,
},
- BlockLimits, DeclaredObserver, MegaBlockExecutionCtx, MegaBlockExecutorFactory, MegaEvmFactory,
- MegaHardforks, MegaSpecId,
+ BlockLimits, MegaBlockExecutionCtx, MegaBlockExecutor, MegaEvmFactory, MegaHardforks,
+ MegaSpecId,
};
use tracing::{debug, info, trace, warn};
@@ -443,11 +443,6 @@ impl Cmd {
let evm_env = EvmEnv::new(cfg_env, block_env);
let evm_factory = MegaEvmFactory::new().with_external_env_factory(external_envs);
- let block_executor_factory = MegaBlockExecutorFactory::new(
- OpAlloyReceiptBuilder::default(),
- &hardforks,
- evm_factory,
- );
// The block is held to Satin's protocol limits, or the override's, with no building
// policy, as a validator holds it; the block's gas limit comes from its header. Whether
// it admits only deposits comes from the schedule and the parent block's timestamp, as a
@@ -465,18 +460,14 @@ impl Cmd {
.with_satin_activation_block(activates_satin);
let start = Instant::now();
- // The tracer reads and writes nothing back, so block execution admits it declared.
- // It is attached only for `--trace`: otherwise preceding transactions would be recorded
- // and then discarded.
- let mut inspector = DeclaredObserver::new(ReplayTracer::from_args(&self.trace_args));
+ // The tracer is attached only for `--trace`: otherwise preceding transactions would be
+ // recorded and then discarded.
+ let mut inspector = ReplayTracer::from_args(&self.trace_args);
let mut state =
StateBuilder::new().with_database(&mut database).with_bundle_update().build();
- let mut block_executor = block_executor_factory.create_executor_with_trusted_inspector(
- &mut state,
- evm_env,
- block_ctx,
- &mut inspector,
- );
+ let evm = evm_factory.create_evm_with_inspector(&mut state, evm_env, &mut inspector);
+ let mut block_executor =
+ MegaBlockExecutor::new(evm, block_ctx, &hardforks, OpAlloyReceiptBuilder::default());
if let Some(limits) = limits_override {
block_executor = block_executor.with_protocol_limits(limits);
}
@@ -541,7 +532,7 @@ impl Cmd {
.unwrap_or(0);
// The trace covers the target transaction only.
- if let ReplayTracer::On(tracer) = &mut block_executor.evm_mut().inspector_mut().0 {
+ if let ReplayTracer::On(tracer) = block_executor.evm_mut().inspector_mut() {
tracer.fuse();
}
let outcome = block_executor
@@ -570,7 +561,7 @@ impl Cmd {
state: evm_state.clone(),
};
- let trace_data = match &block_executor.inspector().0 {
+ let trace_data = match block_executor.inspector() {
ReplayTracer::On(tracer) => Some(self.trace_args.generate_trace(
tracer,
&result_and_state,
diff --git a/bin/mega-evme/tests/block_replay.rs b/bin/mega-evme/tests/block_replay.rs
index 1fd09502f..ec3a4c4da 100644
--- a/bin/mega-evme/tests/block_replay.rs
+++ b/bin/mega-evme/tests/block_replay.rs
@@ -1,5 +1,5 @@
//! `mega-evme replay --block`: whole blocks on either engine, compared with the chain, on the
-//! recorded mainnet blocks of `tests/fixtures/blocks` (see `common/blocks.rs`).
+//! recorded mainnet blocks of `tests/fixtures/blocks.tar.xz` (see `common/blocks.rs`).
#![cfg(feature = "legacy")]
mod common;
@@ -33,6 +33,38 @@ fn replay(number: u64, dir: &Path, extra: &[&str]) -> common::blocks::Run {
run_evme(&args)
}
+/// Extractions of the fixture archive racing into one directory all succeed and leave every
+/// member in place, as test processes that start at once on a cold run extract it.
+#[test]
+fn test_racing_extractions_of_the_fixture_archive_all_succeed() {
+ const WRITERS: usize = 8;
+ let archive = common::fixtures_dir().join("blocks.tar.xz");
+ let destination = common::extracted_root().join(format!(".race-{}", std::process::id()));
+ let _ = std::fs::remove_dir_all(&destination);
+ let barrier = std::sync::Barrier::new(WRITERS);
+ std::thread::scope(|scope| {
+ for _ in 0..WRITERS {
+ scope.spawn(|| {
+ barrier.wait();
+ common::install_archive(&archive, &destination);
+ });
+ }
+ });
+ let listing = std::process::Command::new("tar").arg("-tJf").arg(&archive).output().unwrap();
+ assert!(listing.status.success());
+ let members: Vec = String::from_utf8(listing.stdout)
+ .unwrap()
+ .lines()
+ .filter(|member| !member.ends_with('/'))
+ .map(str::to_string)
+ .collect();
+ assert!(!members.is_empty());
+ for member in &members {
+ assert!(destination.join(member).is_file(), "{member} is in place");
+ }
+ std::fs::remove_dir_all(&destination).unwrap();
+}
+
/// The legacy leg replays each recorded block exactly as the chain executed it: every
/// transaction's status, gas used, cumulative gas used and logs, and the receipts root.
/// Offline, a replay writes nothing to the cache.
@@ -268,10 +300,13 @@ fn test_an_override_replays_a_satin_block_under_other_limits() {
assert!(reason.contains(mega_evm::TX_BODY_OVER_DATA_SIZE_LIMIT), "{reason}");
continue;
}
+ // The frame that crosses the transaction's limit crosses its own budget, a share of
+ // what the limit leaves, which the stop names with what that frame used of it.
let stop = &tx["satin"]["limit_exceeded"];
assert_eq!(stop["kind"], "data_size", "{tx}");
- assert_eq!(stop["limit"], limit, "{tx}");
- assert!(stop["used"].as_u64().unwrap() > limit, "{tx}");
+ let budget = stop["limit"].as_u64().unwrap();
+ assert!(budget <= limit, "{tx}");
+ assert!(stop["used"].as_u64().unwrap() > budget, "{tx}");
}
}
assert!(protocols > 0 && others > 0, "{protocols} {others}");
diff --git a/bin/mega-evme/tests/common/blocks.rs b/bin/mega-evme/tests/common/blocks.rs
index 6c4e012df..666ba0500 100644
--- a/bin/mega-evme/tests/common/blocks.rs
+++ b/bin/mega-evme/tests/common/blocks.rs
@@ -1,4 +1,4 @@
-//! The recorded mainnet blocks under `tests/fixtures/blocks`, and running the binary on them.
+//! The recorded mainnet blocks of `tests/fixtures/blocks.tar.xz`, and running the binary on them.
//!
//! The fixtures are three `MegaETH` mainnet blocks (Rex6) in the block cache layout, recorded
//! from the chain: each block with its transactions, the chain's receipts, and the state its
@@ -9,6 +9,7 @@
use std::{
path::{Path, PathBuf},
process::Command,
+ sync::OnceLock,
};
use alloy_primitives::{address, Address, B256, U256};
@@ -41,9 +42,11 @@ pub(crate) fn overhead_slot() -> B256 {
B256::with_last_byte(5)
}
-/// The recorded block cache.
+/// The recorded block cache: `tests/fixtures/blocks.tar.xz` extracted once per test binary (see
+/// `super::fixture_archive`). Read-only; a test that writes takes [`cache_copy`].
pub(crate) fn fixtures() -> &'static Path {
- Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fixtures/blocks"))
+ static DIR: OnceLock = OnceLock::new();
+ DIR.get_or_init(|| super::fixture_archive("blocks.tar.xz"))
}
/// Where block `number` lives in the cache at `dir`.
diff --git a/bin/mega-evme/tests/common/mod.rs b/bin/mega-evme/tests/common/mod.rs
index 1ebbaa75e..39db1b4ad 100644
--- a/bin/mega-evme/tests/common/mod.rs
+++ b/bin/mega-evme/tests/common/mod.rs
@@ -11,10 +11,131 @@
pub(crate) mod blocks;
+use std::{
+ path::{Path, PathBuf},
+ process::Command,
+ sync::atomic::{AtomicUsize, Ordering},
+};
+
use clap::Parser;
use mega_evme::common::RpcArgs;
use wiremock::{matchers, Mock, MockServer, ResponseTemplate};
+/// Resolve an archive in `tests/fixtures/` holding many fixtures, extracting
+/// all of its members, and return the directory they were extracted into.
+///
+/// `name` names the archive itself (`blocks.tar.xz`). Each member is then the
+/// file of that relative path in the returned directory. The directory is
+/// returned only once every member is in place; see [`install_archive`] for why
+/// an extraction is safe to share across runs and concurrent test binaries.
+pub(crate) fn fixture_archive(name: &str) -> PathBuf {
+ let archive = fixtures_dir().join(name);
+ assert!(
+ archive.is_file(),
+ "no fixture archive named {name}: {} does not exist",
+ archive.display()
+ );
+ extracted(&archive)
+}
+
+/// The directory `archive` is extracted into, extracting it first unless an
+/// earlier extraction already completed there.
+fn extracted(archive: &Path) -> PathBuf {
+ let destination = extraction_dir(archive);
+ if !destination.join(EXTRACTION_COMPLETE).is_file() {
+ install_archive(archive, &destination);
+ }
+ destination
+}
+
+/// Marker [`install_archive`] writes into an extraction directory once every
+/// member of the archive is in place.
+const EXTRACTION_COMPLETE: &str = ".extraction-complete";
+
+/// Directory an archive is extracted into: under [`extracted_root`], named by
+/// the keccak-256 of the archive's bytes.
+fn extraction_dir(archive: &Path) -> PathBuf {
+ let bytes =
+ std::fs::read(archive).unwrap_or_else(|e| panic!("cannot read {}: {e}", archive.display()));
+ extracted_root().join(format!("{:x}", alloy_primitives::keccak256(&bytes)))
+}
+
+/// Extract every member of `archive` into `destination`, its
+/// [`extraction_dir`], and mark the directory complete.
+///
+/// Naming the directory by the archive's digest means:
+///
+/// - an extraction is reused by every later test binary and every later run for as long as its
+/// archive is unchanged, so the directory does not grow from run to run;
+/// - a changed archive (a recapture, or a branch switch) has a different digest, so an extraction
+/// of an earlier version is never served for it; that earlier extraction stays until `cargo
+/// clean`;
+/// - concurrent extractions — parallel tests, or test binaries running at once — each unpack into a
+/// private scratch directory and rename every file into place, which is atomic, so a reader sees
+/// either no file or a complete one, and two writers write the same bytes. The completion marker
+/// is renamed into place last, so a directory carrying it holds every member.
+///
+/// Extraction shells out to `tar -xJf` rather than linking a decompressor:
+/// every platform that runs these tests has one, and this is the only place
+/// that reads an archive.
+pub(crate) fn install_archive(archive: &Path, destination: &Path) {
+ static NEXT: AtomicUsize = AtomicUsize::new(0);
+ let scratch = extracted_root().join(format!(
+ ".extracting-{}-{}",
+ std::process::id(),
+ NEXT.fetch_add(1, Ordering::Relaxed)
+ ));
+ std::fs::create_dir_all(&scratch).expect("failed to create the extraction directory");
+ let status = Command::new("tar")
+ .arg("-xJf")
+ .arg(archive)
+ .arg("-C")
+ .arg(&scratch)
+ .status()
+ .expect("failed to run tar");
+ assert!(status.success(), "failed to extract {}", archive.display());
+
+ move_files(&scratch, destination);
+ let marker = scratch.join(EXTRACTION_COMPLETE);
+ std::fs::write(&marker, b"").expect("failed to write the extraction marker");
+ std::fs::rename(&marker, destination.join(EXTRACTION_COMPLETE))
+ .expect("failed to mark the extraction complete");
+ let _ = std::fs::remove_dir_all(&scratch);
+}
+
+/// Move every file under `from` to the same path under `to`, creating the directories on the way.
+///
+/// Each file is renamed on its own, which is atomic and replaces a file of the same name, so a
+/// second writer moving the same members succeeds where renaming a directory onto one already in
+/// place would fail.
+fn move_files(from: &Path, to: &Path) {
+ std::fs::create_dir_all(to).expect("failed to create the extraction directory");
+ for entry in std::fs::read_dir(from).expect("failed to read the extraction directory") {
+ let entry = entry.expect("failed to read an extracted member");
+ let target = to.join(entry.file_name());
+ if entry.file_type().expect("failed to read an extracted member's type").is_dir() {
+ move_files(&entry.path(), &target);
+ } else {
+ std::fs::rename(entry.path(), &target)
+ .expect("failed to move an extracted fixture into place");
+ }
+ }
+}
+
+/// Directory the committed fixtures live in.
+pub(crate) fn fixtures_dir() -> PathBuf {
+ Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures")
+}
+
+/// Directory compressed fixtures are extracted into.
+///
+/// It lives under cargo's per-target scratch directory (`CARGO_TARGET_TMPDIR`),
+/// which persists across test runs and is removed by `cargo clean`. Exposed so a
+/// test that normalizes the paths a run prints can name it.
+pub(crate) fn extracted_root() -> PathBuf {
+ Path::new(env!("CARGO_TARGET_TMPDIR")).join("mega-evme-fixtures")
+}
+
/// A mock JSON-RPC server tuned for mega-evme integration tests.
///
/// All mounted mocks match `POST` (the JSON-RPC verb) and use priorities so
diff --git a/bin/mega-evme/tests/differences.rs b/bin/mega-evme/tests/differences.rs
index 8dfa53f59..cfdc25c09 100644
--- a/bin/mega-evme/tests/differences.rs
+++ b/bin/mega-evme/tests/differences.rs
@@ -9,7 +9,7 @@
//! The inputs are the ones this repository can build without a chain: the `run` and `tx`
//! fixtures, each run on both engines (`test_.json` and `test_satin_.json`, whose
//! outputs `tests/integration.rs` holds the binary to), and the recorded mainnet blocks of
-//! `tests/fixtures/blocks`, whose legacy replay matches the chain.
+//! `tests/fixtures/blocks.tar.xz`, whose legacy replay matches the chain.
#![cfg(feature = "legacy")]
mod common;
@@ -155,7 +155,7 @@ fn render_blocks(out: &mut String) {
writeln!(out, "## Recorded mainnet blocks\n").unwrap();
writeln!(
out,
- "The three Rex6 blocks of `tests/fixtures/blocks`, each replayed on both engines. The \
+ "The three Rex6 blocks of `tests/fixtures/blocks.tar.xz`, each replayed on both engines. The \
legacy replay of each matches the chain (every receipt and the receipts root), so the \
legacy column is the chain's. Satin runs the transactions as signed, on the state \
their parent block left.\n"
diff --git a/bin/mega-evme/tests/fixtures/blocks.tar.xz b/bin/mega-evme/tests/fixtures/blocks.tar.xz
new file mode 100644
index 000000000..4e80ba1c4
Binary files /dev/null and b/bin/mega-evme/tests/fixtures/blocks.tar.xz differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400001.json.zst b/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400001.json.zst
deleted file mode 100644
index 7b683daaf..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400001.json.zst and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400007.json.zst b/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400007.json.zst
deleted file mode 100644
index 1d7a3d2b5..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400007.json.zst and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400110.json.zst b/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400110.json.zst
deleted file mode 100644
index 324da2d61..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/blocks/2640/26400110.json.zst and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/00/003d29a8c6f51157a3a25b6dca29f62d443a99baaa366699ef84f802ae5801b4.bin b/bin/mega-evme/tests/fixtures/blocks/codes/00/003d29a8c6f51157a3a25b6dca29f62d443a99baaa366699ef84f802ae5801b4.bin
deleted file mode 100644
index 17ca87df9..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/00/003d29a8c6f51157a3a25b6dca29f62d443a99baaa366699ef84f802ae5801b4.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/1b/1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2.bin b/bin/mega-evme/tests/fixtures/blocks/codes/1b/1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2.bin
deleted file mode 100644
index 4240bb68e..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/1b/1b2df8ca5350cd7106d67ed95532584526f97a5ca267c8eef73a1831f53720f2.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/2b/2b9df977426a14fba5fd5b393dc621c8d9b020d9aa6e83879561426943aee0b0.bin b/bin/mega-evme/tests/fixtures/blocks/codes/2b/2b9df977426a14fba5fd5b393dc621c8d9b020d9aa6e83879561426943aee0b0.bin
deleted file mode 100644
index 3b3dc2705..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/2b/2b9df977426a14fba5fd5b393dc621c8d9b020d9aa6e83879561426943aee0b0.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/39/3927f2a4803c5e18153ff5742d0fa1acd9ad04538e4e6037cb4a9b28694ca87f.bin b/bin/mega-evme/tests/fixtures/blocks/codes/39/3927f2a4803c5e18153ff5742d0fa1acd9ad04538e4e6037cb4a9b28694ca87f.bin
deleted file mode 100644
index 7229d1821..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/39/3927f2a4803c5e18153ff5742d0fa1acd9ad04538e4e6037cb4a9b28694ca87f.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/3f/3f77685d5db0f99bf10bf1f0cd31a5d59bde918169800b8d219754360a1f58b2.bin b/bin/mega-evme/tests/fixtures/blocks/codes/3f/3f77685d5db0f99bf10bf1f0cd31a5d59bde918169800b8d219754360a1f58b2.bin
deleted file mode 100644
index c80ae656a..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/3f/3f77685d5db0f99bf10bf1f0cd31a5d59bde918169800b8d219754360a1f58b2.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/45/459716bd908d0ccf47599b42af92c72e7e5f2a4ba6c3bda5bb2ada1b91c829a9.bin b/bin/mega-evme/tests/fixtures/blocks/codes/45/459716bd908d0ccf47599b42af92c72e7e5f2a4ba6c3bda5bb2ada1b91c829a9.bin
deleted file mode 100644
index d84759d92..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/45/459716bd908d0ccf47599b42af92c72e7e5f2a4ba6c3bda5bb2ada1b91c829a9.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/49/49c1640723483828ed8f68499465c80e43b953eaa41c27d9a03515fb9cad660f.bin b/bin/mega-evme/tests/fixtures/blocks/codes/49/49c1640723483828ed8f68499465c80e43b953eaa41c27d9a03515fb9cad660f.bin
deleted file mode 100644
index fda99a2f9..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/49/49c1640723483828ed8f68499465c80e43b953eaa41c27d9a03515fb9cad660f.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/4d/4d9be648c5bf39973670d9f8b481d5d0b971e6a2db2deccc6b98cde21c5dd83e.bin b/bin/mega-evme/tests/fixtures/blocks/codes/4d/4d9be648c5bf39973670d9f8b481d5d0b971e6a2db2deccc6b98cde21c5dd83e.bin
deleted file mode 100644
index 59424f4eb..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/4d/4d9be648c5bf39973670d9f8b481d5d0b971e6a2db2deccc6b98cde21c5dd83e.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/55/55020d41649acf7a84add6e628b887f802218d9ac86f142ef0994da43ea5eeb6.bin b/bin/mega-evme/tests/fixtures/blocks/codes/55/55020d41649acf7a84add6e628b887f802218d9ac86f142ef0994da43ea5eeb6.bin
deleted file mode 100644
index e299bee5c..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/55/55020d41649acf7a84add6e628b887f802218d9ac86f142ef0994da43ea5eeb6.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/6e/6e49e66782037c0555897870e29fa5e552daf4719552131a0abce779daec0a5d.bin b/bin/mega-evme/tests/fixtures/blocks/codes/6e/6e49e66782037c0555897870e29fa5e552daf4719552131a0abce779daec0a5d.bin
deleted file mode 100644
index b135cf2c6..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/6e/6e49e66782037c0555897870e29fa5e552daf4719552131a0abce779daec0a5d.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/6f/6f5dd02efc31c07c6d99d8d36417cb2a2327d87970645a2c1012e61f617551ee.bin b/bin/mega-evme/tests/fixtures/blocks/codes/6f/6f5dd02efc31c07c6d99d8d36417cb2a2327d87970645a2c1012e61f617551ee.bin
deleted file mode 100644
index 910842577..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/6f/6f5dd02efc31c07c6d99d8d36417cb2a2327d87970645a2c1012e61f617551ee.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/6f/6f77a5c9db7cfef9a4d05faff0d08af36ea1ead283270da9bf554c306a6c87b9.bin b/bin/mega-evme/tests/fixtures/blocks/codes/6f/6f77a5c9db7cfef9a4d05faff0d08af36ea1ead283270da9bf554c306a6c87b9.bin
deleted file mode 100644
index 723962f23..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/6f/6f77a5c9db7cfef9a4d05faff0d08af36ea1ead283270da9bf554c306a6c87b9.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/71/71a65239db8d0f1bb765fad36e34f57600420d103a4401ef7555bd50b229dc55.bin b/bin/mega-evme/tests/fixtures/blocks/codes/71/71a65239db8d0f1bb765fad36e34f57600420d103a4401ef7555bd50b229dc55.bin
deleted file mode 100644
index 78ea0add1..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/71/71a65239db8d0f1bb765fad36e34f57600420d103a4401ef7555bd50b229dc55.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/78/781c9c39ab69e9b7d099ec75e5a28df41dc891c8fffbe0148c94ed5adc8b0c09.bin b/bin/mega-evme/tests/fixtures/blocks/codes/78/781c9c39ab69e9b7d099ec75e5a28df41dc891c8fffbe0148c94ed5adc8b0c09.bin
deleted file mode 100644
index d43b07e4d..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/78/781c9c39ab69e9b7d099ec75e5a28df41dc891c8fffbe0148c94ed5adc8b0c09.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/78/78dd15e7753d3e60a8003bda403516ec43590177c4009049afc16fa1bc9f8dc4.bin b/bin/mega-evme/tests/fixtures/blocks/codes/78/78dd15e7753d3e60a8003bda403516ec43590177c4009049afc16fa1bc9f8dc4.bin
deleted file mode 100644
index 16d6a9cbc..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/78/78dd15e7753d3e60a8003bda403516ec43590177c4009049afc16fa1bc9f8dc4.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/7e/7eff9da33cc2042d53428940c03a32662470f639863b356e5cd453b03bb0ce42.bin b/bin/mega-evme/tests/fixtures/blocks/codes/7e/7eff9da33cc2042d53428940c03a32662470f639863b356e5cd453b03bb0ce42.bin
deleted file mode 100644
index aa6601338..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/7e/7eff9da33cc2042d53428940c03a32662470f639863b356e5cd453b03bb0ce42.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/86/864cc9ad53b338b82da1f7cab85ab0b3d5c8861acb422b6fec63cf36234f36a6.bin b/bin/mega-evme/tests/fixtures/blocks/codes/86/864cc9ad53b338b82da1f7cab85ab0b3d5c8861acb422b6fec63cf36234f36a6.bin
deleted file mode 100644
index 9f6425adc..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/86/864cc9ad53b338b82da1f7cab85ab0b3d5c8861acb422b6fec63cf36234f36a6.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/8e/8e3fe7a416d3e5f3b7be74ddd4e7e58e516fa3f80b67c6d930e3cd7297da4a4b.bin b/bin/mega-evme/tests/fixtures/blocks/codes/8e/8e3fe7a416d3e5f3b7be74ddd4e7e58e516fa3f80b67c6d930e3cd7297da4a4b.bin
deleted file mode 100644
index f2eba0794..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/8e/8e3fe7a416d3e5f3b7be74ddd4e7e58e516fa3f80b67c6d930e3cd7297da4a4b.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/96/96d0f3ba6b474e9684a97e4388ec8dbb7929818b51e6b4f19f885ccbdf642f9b.bin b/bin/mega-evme/tests/fixtures/blocks/codes/96/96d0f3ba6b474e9684a97e4388ec8dbb7929818b51e6b4f19f885ccbdf642f9b.bin
deleted file mode 100644
index 5e729b9de..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/96/96d0f3ba6b474e9684a97e4388ec8dbb7929818b51e6b4f19f885ccbdf642f9b.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/9f/9ff4579ce0b80a88bfe720db622b7d433b94a4aa840e943aa9b6ada3f7847cad.bin b/bin/mega-evme/tests/fixtures/blocks/codes/9f/9ff4579ce0b80a88bfe720db622b7d433b94a4aa840e943aa9b6ada3f7847cad.bin
deleted file mode 100644
index 62386fc02..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/9f/9ff4579ce0b80a88bfe720db622b7d433b94a4aa840e943aa9b6ada3f7847cad.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/a2/a220f51e097a419ab9cc99098261c8cca605219541f7e9bb9aadc66ee9e277fe.bin b/bin/mega-evme/tests/fixtures/blocks/codes/a2/a220f51e097a419ab9cc99098261c8cca605219541f7e9bb9aadc66ee9e277fe.bin
deleted file mode 100644
index 8e3692fd7..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/a2/a220f51e097a419ab9cc99098261c8cca605219541f7e9bb9aadc66ee9e277fe.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/aa/aac32b96929a057494369eec530c2fc6640176b13d2c10b5df218f920f3a1dc5.bin b/bin/mega-evme/tests/fixtures/blocks/codes/aa/aac32b96929a057494369eec530c2fc6640176b13d2c10b5df218f920f3a1dc5.bin
deleted file mode 100644
index ce6f13e0e..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/aa/aac32b96929a057494369eec530c2fc6640176b13d2c10b5df218f920f3a1dc5.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/ab/ab5d51e60951e30c2843d8fa783c5edc085ef7ece05077c3382b8d3b367863b0.bin b/bin/mega-evme/tests/fixtures/blocks/codes/ab/ab5d51e60951e30c2843d8fa783c5edc085ef7ece05077c3382b8d3b367863b0.bin
deleted file mode 100644
index fef3fdb1e..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/ab/ab5d51e60951e30c2843d8fa783c5edc085ef7ece05077c3382b8d3b367863b0.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/ab/abd7e8f1c8f0f9ca0346df585b65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43.bin b/bin/mega-evme/tests/fixtures/blocks/codes/ab/abd7e8f1c8f0f9ca0346df585b65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43.bin
deleted file mode 100644
index 51aee0959..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/ab/abd7e8f1c8f0f9ca0346df585b65d9791a7e9ba5c431cc4eda5d2c2f1f5e9c43.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/b4/b49519ce3e3318d1a31455153c184f4e6642e083d8031f89854e6de590c5b999.bin b/bin/mega-evme/tests/fixtures/blocks/codes/b4/b49519ce3e3318d1a31455153c184f4e6642e083d8031f89854e6de590c5b999.bin
deleted file mode 100644
index ff7f4b086..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/b4/b49519ce3e3318d1a31455153c184f4e6642e083d8031f89854e6de590c5b999.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/c8/c8c18504b075d2d658fa153db117fb06613189b4e0459b3a2263fc0ed240cf5c.bin b/bin/mega-evme/tests/fixtures/blocks/codes/c8/c8c18504b075d2d658fa153db117fb06613189b4e0459b3a2263fc0ed240cf5c.bin
deleted file mode 100644
index d23f1cd60..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/c8/c8c18504b075d2d658fa153db117fb06613189b4e0459b3a2263fc0ed240cf5c.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/cc/cc7e366c8e998368260791347f23477c857b80d45c69929c1f38b031ff5d2919.bin b/bin/mega-evme/tests/fixtures/blocks/codes/cc/cc7e366c8e998368260791347f23477c857b80d45c69929c1f38b031ff5d2919.bin
deleted file mode 100644
index 4658bcd2f..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/cc/cc7e366c8e998368260791347f23477c857b80d45c69929c1f38b031ff5d2919.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/f0/f0b39905b14634f160f60fcc20a2b574f528d515f6f765506edc1205705b4139.bin b/bin/mega-evme/tests/fixtures/blocks/codes/f0/f0b39905b14634f160f60fcc20a2b574f528d515f6f765506edc1205705b4139.bin
deleted file mode 100644
index a9e9a7ae0..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/f0/f0b39905b14634f160f60fcc20a2b574f528d515f6f765506edc1205705b4139.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/f5/f57acd40259872606d76197ef052f3d35588dadf919ee1f0e3cb9b62d3f4b02c.bin b/bin/mega-evme/tests/fixtures/blocks/codes/f5/f57acd40259872606d76197ef052f3d35588dadf919ee1f0e3cb9b62d3f4b02c.bin
deleted file mode 100644
index c527f90d4..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/f5/f57acd40259872606d76197ef052f3d35588dadf919ee1f0e3cb9b62d3f4b02c.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/f7/f7bdad905f90d6e7cb07182aeba262aeb634b015222134d5abfd8f7b7828276a.bin b/bin/mega-evme/tests/fixtures/blocks/codes/f7/f7bdad905f90d6e7cb07182aeba262aeb634b015222134d5abfd8f7b7828276a.bin
deleted file mode 100644
index bd2f99563..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/f7/f7bdad905f90d6e7cb07182aeba262aeb634b015222134d5abfd8f7b7828276a.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/fa/fa8c9db6c6cab7108dea276f4cd09d575674eb0852c0fa3187e59e98ef977998.bin b/bin/mega-evme/tests/fixtures/blocks/codes/fa/fa8c9db6c6cab7108dea276f4cd09d575674eb0852c0fa3187e59e98ef977998.bin
deleted file mode 100644
index e69a0b8b8..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/fa/fa8c9db6c6cab7108dea276f4cd09d575674eb0852c0fa3187e59e98ef977998.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/blocks/codes/fd/fdf85d183a122fe611bc878683b722b2b22633e13900c4b13767742b9f5f5a90.bin b/bin/mega-evme/tests/fixtures/blocks/codes/fd/fdf85d183a122fe611bc878683b722b2b22633e13900c4b13767742b9f5f5a90.bin
deleted file mode 100644
index c12cb0b3d..000000000
Binary files a/bin/mega-evme/tests/fixtures/blocks/codes/fd/fdf85d183a122fe611bc878683b722b2b22633e13900c4b13767742b9f5f5a90.bin and /dev/null differ
diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_basic_return.json b/bin/mega-evme/tests/fixtures/test_satin_run_basic_return.json
index b4faea4d7..6e7229c78 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_run_basic_return.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_run_basic_return.json
@@ -20,6 +20,7 @@
"floor_gas": 15000,
"data_size": 310,
"write_records": 0,
+ "state_growth": 0,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_codefile.json b/bin/mega-evme/tests/fixtures/test_satin_run_codefile.json
index 78f6b9894..b5a9e0bfa 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_run_codefile.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_run_codefile.json
@@ -21,6 +21,7 @@
"floor_gas": 15000,
"data_size": 310,
"write_records": 0,
+ "state_growth": 0,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_create.json b/bin/mega-evme/tests/fixtures/test_satin_run_create.json
index 5ed7f9687..a51263753 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_run_create.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_run_create.json
@@ -23,6 +23,7 @@
"floor_gas": 24640,
"data_size": 361,
"write_records": 1,
+ "state_growth": 1,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_dump_inline.json b/bin/mega-evme/tests/fixtures/test_satin_run_dump_inline.json
index 547aa97a5..5e8d601fa 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_run_dump_inline.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_run_dump_inline.json
@@ -68,6 +68,7 @@
"floor_gas": 15000,
"data_size": 350,
"write_records": 1,
+ "state_growth": 1,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_input.json b/bin/mega-evme/tests/fixtures/test_satin_run_input.json
index 8f7b22975..23bdca9b8 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_run_input.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_run_input.json
@@ -22,6 +22,7 @@
"floor_gas": 15256,
"data_size": 314,
"write_records": 0,
+ "state_growth": 0,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_prestate.json b/bin/mega-evme/tests/fixtures/test_satin_run_prestate.json
index dce4facb0..a43c08eb4 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_run_prestate.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_run_prestate.json
@@ -28,6 +28,7 @@
"floor_gas": 15000,
"data_size": 310,
"write_records": 0,
+ "state_growth": 0,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_revert.json b/bin/mega-evme/tests/fixtures/test_satin_run_revert.json
index f4435570a..2c7a70d99 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_run_revert.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_run_revert.json
@@ -20,6 +20,7 @@
"floor_gas": 15000,
"data_size": 310,
"write_records": 0,
+ "state_growth": 0,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_rpc_args_parse.json b/bin/mega-evme/tests/fixtures/test_satin_run_rpc_args_parse.json
index 8d9f2bb51..40d2d608b 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_run_rpc_args_parse.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_run_rpc_args_parse.json
@@ -28,6 +28,7 @@
"floor_gas": 15000,
"data_size": 310,
"write_records": 0,
+ "state_growth": 0,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_storage_override.json b/bin/mega-evme/tests/fixtures/test_satin_run_storage_override.json
index c18022340..c5596a0f4 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_run_storage_override.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_run_storage_override.json
@@ -22,6 +22,7 @@
"floor_gas": 15000,
"data_size": 310,
"write_records": 0,
+ "state_growth": 0,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_run_trace_inline.json b/bin/mega-evme/tests/fixtures/test_satin_run_trace_inline.json
index d57a7d645..9fbe9bed6 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_run_trace_inline.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_run_trace_inline.json
@@ -106,6 +106,7 @@
"floor_gas": 15000,
"data_size": 310,
"write_records": 0,
+ "state_growth": 0,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_tx_create.json b/bin/mega-evme/tests/fixtures/test_satin_tx_create.json
index 1ad13be06..b03e8f20f 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_tx_create.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_tx_create.json
@@ -44,6 +44,7 @@
"floor_gas": 24640,
"data_size": 361,
"write_records": 1,
+ "state_growth": 1,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_tx_halt_oog.json b/bin/mega-evme/tests/fixtures/test_satin_tx_halt_oog.json
index e44ece4c8..1e380ed0a 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_tx_halt_oog.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_tx_halt_oog.json
@@ -45,6 +45,7 @@
"floor_gas": 15000,
"data_size": 310,
"write_records": 0,
+ "state_growth": 0,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_tx_revert.json b/bin/mega-evme/tests/fixtures/test_satin_tx_revert.json
index b95064882..cdcc74897 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_tx_revert.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_tx_revert.json
@@ -43,6 +43,7 @@
"floor_gas": 15000,
"data_size": 310,
"write_records": 0,
+ "state_growth": 0,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/fixtures/test_satin_tx_value_transfer.json b/bin/mega-evme/tests/fixtures/test_satin_tx_value_transfer.json
index 65161804b..07afdf897 100644
--- a/bin/mega-evme/tests/fixtures/test_satin_tx_value_transfer.json
+++ b/bin/mega-evme/tests/fixtures/test_satin_tx_value_transfer.json
@@ -59,6 +59,7 @@
"floor_gas": 21000,
"data_size": 510,
"write_records": 1,
+ "state_growth": 1,
"limit_exceeded": null
}
}
diff --git a/bin/mega-evme/tests/limits.rs b/bin/mega-evme/tests/limits.rs
index a8fe8c507..5bb599f8c 100644
--- a/bin/mega-evme/tests/limits.rs
+++ b/bin/mega-evme/tests/limits.rs
@@ -68,9 +68,11 @@ fn test_an_override_holds_a_satin_run_to_other_limits() {
let data_size = run_two_writes(Some(r#"{"txRuntimeLimits":{"txDataSizeLimit":350}}"#));
assert_eq!(data_size["success"], false);
+ // The second write crosses the transaction's own frame's budget, the 40 bytes the body
+ // leaves of the limit, which the stop names.
assert_eq!(
data_size["satin"]["limit_exceeded"],
- json!({ "kind": "data_size", "limit": 350, "used": 390 })
+ json!({ "kind": "data_size", "limit": 40, "used": 80 })
);
assert_eq!(data_size["satin"]["write_records"], 0, "the stop takes the writes back");
assert_eq!(data_size["satin"]["limits_override"], defaults_with_tx_data_size(350));
@@ -91,6 +93,20 @@ fn test_an_override_is_read_from_a_file() {
assert_eq!(from_file, inline);
}
+/// A limits file in the shape's first published version, written before a transaction and a block
+/// had KV-update and state-growth limits, runs: the limits it names replace Satin's, and the ones
+/// it predates stay at Satin's values.
+#[test]
+fn test_an_override_from_a_file_of_the_first_version_runs() {
+ let limits = r#"{"txRuntimeLimits":{"txDataSizeLimit":350,"frameDataSizeLimit":18446744073709551615,"blockEnvAccessComputeGasLimit":20000000,"oracleAccessComputeGasLimit":20000000},"blockTxsDataLimit":13107200}"#;
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("limits.json");
+ std::fs::write(&path, limits).unwrap();
+ let run = run_two_writes(Some(path.to_str().unwrap()));
+ assert_eq!(run["success"], false, "the second write crosses the data size");
+ assert_eq!(run["satin"]["limits_override"], defaults_with_tx_data_size(350));
+}
+
/// `tx` takes the override too: a body one byte over the transaction data-size limit is rejected
/// at validation, and a limit the body fits runs it and names the override.
#[test]
@@ -219,7 +235,7 @@ fn test_a_genesis_file_runs_satin_under_the_specs_limits() {
let overridden = run(&["--override.limits", &limits]).json();
assert_eq!(
overridden["satin"]["limit_exceeded"],
- json!({ "kind": "data_size", "limit": ONE_RECORD, "used": TWO_RECORDS })
+ json!({ "kind": "data_size", "limit": WRITE_RECORD_SIZE, "used": 2 * WRITE_RECORD_SIZE })
);
// The file is its chain's: a run on another chain is refused.
diff --git a/bin/mega-evme/tests/rex6_forward.rs b/bin/mega-evme/tests/rex6_forward.rs
new file mode 100644
index 000000000..20798b5fc
--- /dev/null
+++ b/bin/mega-evme/tests/rex6_forward.rs
@@ -0,0 +1,266 @@
+//! The contracts of `mega-evm`'s `tests/satin/reservoir_drain.rs` under Rex6, on the released
+//! engine the legacy leg links: one gas pool, so EIP-150's forward bounds everything a callee
+//! spends, its storage gas included.
+//!
+//! `A` reads `GAS`, calls `C` with a forward of 1,000,000, reads `GAS` again, writes `K` fresh
+//! slots and returns the two readings and the call's flag. `C` is `STOP`, `INVALID` (which burns
+//! its forward), or the loop of `LOG0`s of 512 bytes that the Satin test runs, byte for byte: it
+//! stops when an iteration's `GAS` drop exceeds the log's regular cost (4,478 with the closing
+//! `GAS`), or when its gas falls below 52,481. Under one pool the drop always includes the log's
+//! storage gas, so that callee logs once; the greedy one, which never stops on the drop, logs
+//! until its forward runs low.
+//!
+//! `K` is the most slots `A` completes after the `INVALID` callee, found by running it. `A`'s
+//! work completes after every callee, because none of them spends more than the forward.
+//!
+//! The gas limit is 20,000,000, where the gas binds `A`'s work before Rex6's limit of 1,000 new
+//! slots per transaction. Without the work, each callee spends the same at 20,000,000 and at
+//! 400,000,000: a larger gas limit gives it nothing more. The tests print their tables
+//! (`--nocapture`).
+
+#![cfg(feature = "legacy")]
+
+use mega_evm_legacy::{
+ alloy_primitives::{address, Address, Bytes, TxKind, U256},
+ revm::{
+ bytecode::opcode::{
+ ADD, CALL, DUP1, DUP2, GAS, GT, INVALID, ISZERO, JUMP, JUMPDEST, JUMPI, LOG0, LT,
+ MSTORE, POP, PUSH0, PUSH1, PUSH2, PUSH20, PUSH4, RETURN, SSTORE, STOP, SUB, SWAP1,
+ },
+ context::{result::ExecutionResult, BlockEnv, TxEnv},
+ },
+ test_utils::MemoryDatabase,
+ MegaContext, MegaEvm, MegaSpecId, MegaTransaction,
+};
+
+const SENDER: Address = address!("0000000000000000000000000000000000710000");
+const A: Address = address!("0000000000000000000000000000000000710001");
+const C: Address = address!("0000000000000000000000000000000000710002");
+
+const FORWARD: u32 = 1_000_000;
+
+// The Satin test's numbers for its `LOG0` callee, which that test holds to these values.
+
+/// The regular gas of one log with its operands and the closing `GAS`.
+const STOP_ABOVE: u32 = 4_478;
+/// The gas the callee keeps before another iteration.
+const RESERVE: u32 = 52_481;
+
+/// A callee: its name in the tables and its code.
+#[derive(Clone, Debug)]
+struct Callee {
+ name: &'static str,
+ code: Bytes,
+}
+
+impl Callee {
+ fn new(name: &'static str, code: Bytes) -> Self {
+ Self { name, code }
+ }
+
+ fn burns() -> Self {
+ Self::new("INVALID", Bytes::from_static(&[INVALID]))
+ }
+}
+
+/// The `LOG0` callee: 512 bytes of data from memory expanded first, in a loop that reads `GAS`
+/// around each log.
+fn logging(stop_on_spill: bool) -> Bytes {
+ let stop_above = if stop_on_spill { STOP_ABOVE } else { u32::MAX };
+ let mut code = vec![PUSH0, PUSH2, 0x01, 0xe0, MSTORE, PUSH0];
+ let top = code.len();
+ code.extend([JUMPDEST, GAS, PUSH2, 0x02, 0x00, PUSH0, LOG0, GAS, DUP1, PUSH4]);
+ code.extend(RESERVE.to_be_bytes());
+ code.extend([GT, PUSH2, 0, 0, JUMPI]);
+ let out_on_reserve = code.len() - 3;
+ code.extend([SWAP1, SUB, PUSH4]);
+ code.extend(stop_above.to_be_bytes());
+ code.extend([LT, PUSH2, 0, 0, JUMPI]);
+ let out_on_drop = code.len() - 3;
+ code.extend([PUSH1, 1, ADD, PUSH2]);
+ code.extend((top as u16).to_be_bytes());
+ code.push(JUMP);
+ let out = (code.len() as u16).to_be_bytes();
+ code.extend([JUMPDEST, STOP]);
+ code[out_on_reserve..out_on_reserve + 2].copy_from_slice(&out);
+ code[out_on_drop..out_on_drop + 2].copy_from_slice(&out);
+ code.into()
+}
+
+/// `A`: `GAS`, `CALL(FORWARD, C)`, `GAS`, `work` fresh slots, and the two readings and the flag
+/// returned.
+fn caller(work: u32) -> Bytes {
+ let mut code = vec![GAS, PUSH0, PUSH0, PUSH0, PUSH0, PUSH0, PUSH20];
+ code.extend(C);
+ code.push(PUSH4);
+ code.extend(FORWARD.to_be_bytes());
+ code.extend([CALL, GAS, PUSH4]);
+ code.extend(work.to_be_bytes());
+ let top = code.len() as u16;
+ code.extend([JUMPDEST, DUP1, ISZERO, PUSH2, 0, 0, JUMPI]);
+ let out_at = code.len() - 3;
+ code.extend([PUSH1, 1, DUP2, SSTORE, PUSH1, 1, SWAP1, SUB, PUSH2]);
+ code.extend(top.to_be_bytes());
+ code.push(JUMP);
+ let out = (code.len() as u16).to_be_bytes();
+ code[out_at..out_at + 2].copy_from_slice(&out);
+ code.extend([JUMPDEST, POP, PUSH1, 0x40, MSTORE, PUSH1, 0x20, MSTORE, PUSH0, MSTORE]);
+ code.extend([PUSH1, 0x60, PUSH0, RETURN]);
+ code.into()
+}
+
+/// One run's figures.
+#[derive(Clone, Debug)]
+struct Run {
+ callee: &'static str,
+ gas_limit: u64,
+ work: u32,
+ status: String,
+ gas_used: u64,
+ logs: usize,
+ /// `A`'s `GAS` before and after the call, when `A` returned.
+ gas_around_call: Option<(u64, u64)>,
+ /// The call's flag, when `A` returned.
+ call_succeeded: Option,
+}
+
+impl Run {
+ fn completed(&self) -> bool {
+ self.gas_around_call.is_some()
+ }
+}
+
+fn run(gas_limit: u64, callee: Callee, work: u32) -> Run {
+ let db = MemoryDatabase::default()
+ .account_balance(SENDER, U256::from(10u64.pow(18)))
+ .account_code(A, caller(work))
+ .account_code(C, callee.code);
+ let block = BlockEnv { number: U256::from(1), gas_limit: 10_000_000_000, ..Default::default() };
+ let mut context = MegaContext::new(db, MegaSpecId::REX6).with_block(block);
+ context.modify_chain(|chain| {
+ chain.operator_fee_scalar = Some(U256::ZERO);
+ chain.operator_fee_constant = Some(U256::ZERO);
+ });
+ let mut tx = MegaTransaction::new(TxEnv {
+ caller: SENDER,
+ kind: TxKind::Call(A),
+ gas_limit,
+ ..Default::default()
+ });
+ tx.enveloped_tx = Some(Bytes::new());
+ let outcome = MegaEvm::new(context).execute_transaction(tx).expect("the transaction is valid");
+ let (status, words) = match &outcome.result {
+ ExecutionResult::Success { output, .. } => {
+ let words: Vec =
+ output.data().chunks(32).map(|w| U256::from_be_slice(w).to::()).collect();
+ ("success".to_string(), Some(words))
+ }
+ ExecutionResult::Revert { .. } => ("revert".to_string(), None),
+ ExecutionResult::Halt { reason, .. } => (format!("halt: {reason:?}"), None),
+ };
+ Run {
+ callee: callee.name,
+ gas_limit,
+ work,
+ status,
+ gas_used: outcome.result.gas_used(),
+ logs: outcome.result.logs().len(),
+ gas_around_call: words.as_ref().map(|words| (words[0], words[2])),
+ call_succeeded: words.as_ref().map(|words| words[1] == 1),
+ }
+}
+
+fn callees() -> [Callee; 3] {
+ [
+ Callee::new("STOP", Bytes::from_static(&[STOP])),
+ Callee::new("LOG0 512 B", logging(true)),
+ Callee::new("LOG0 512 B, greedy", logging(false)),
+ ]
+}
+
+/// The most slots `A` completes after a callee that burns its forward.
+fn work_after_a_burned_forward(gas_limit: u64) -> u32 {
+ let (mut fits, mut fails) = (0, 1_000);
+ let too_many = run(gas_limit, Callee::burns(), fails);
+ assert!(too_many.status.contains("OutOfGas"), "the gas binds before 1,000 slots: {too_many:?}");
+ while fails - fits > 1 {
+ let mid = (fits + fails) / 2;
+ if run(gas_limit, Callee::burns(), mid).completed() {
+ fits = mid;
+ } else {
+ fails = mid;
+ }
+ }
+ fits
+}
+
+fn print_table(title: &str, rows: &[Run], baseline_after: u64) {
+ println!("\n### {title}\n");
+ println!(
+ "| gas limit | C | logs | C spend | C spend / forward | A GAS before | A GAS after | \
+ A work (slots) | status | gas used |"
+ );
+ println!("|{}", "---:|".repeat(10));
+ for row in rows {
+ let shown = |figure: Option| figure.unwrap_or_else(|| "-".into());
+ let before = shown(row.gas_around_call.map(|(before, _)| before.to_string()));
+ let after = shown(row.gas_around_call.map(|(_, after)| after.to_string()));
+ let spend = row.gas_around_call.map(|(_, after)| baseline_after - after);
+ println!(
+ "| {} | {} | {} | {} | {} | {} | {} | {} | {} | {} |",
+ row.gas_limit,
+ row.callee,
+ row.logs,
+ shown(spend.map(|s| s.to_string())),
+ shown(spend.map(|s| format!("{:.2}", s as f64 / f64::from(FORWARD)))),
+ before,
+ after,
+ row.work,
+ row.status,
+ row.gas_used,
+ );
+ }
+}
+
+/// Holds every callee to its forward: its spend, read as `A`'s `GAS` after the call against
+/// `A`'s after a callee that returned at once, is at most the forward, and `A`'s work completes.
+#[track_caller]
+fn assert_within_the_forward(rows: &[Run]) -> u64 {
+ assert!(rows.iter().all(Run::completed), "A's work completes after every callee: {rows:#?}");
+ assert!(rows.iter().all(|row| row.call_succeeded == Some(true)), "every callee returns");
+ let baseline_after = rows[0].gas_around_call.unwrap().1;
+ for row in rows {
+ let spend = baseline_after - row.gas_around_call.unwrap().1;
+ assert!(spend <= u64::from(FORWARD), "{}: {spend} within the forward", row.callee);
+ }
+ baseline_after
+}
+
+#[test]
+fn test_rex6_a_callee_spends_within_its_forward() {
+ const GAS_LIMIT: u64 = 20_000_000;
+ let work = work_after_a_burned_forward(GAS_LIMIT);
+ let mut rows: Vec<_> = callees().into_iter().map(|c| run(GAS_LIMIT, c, work)).collect();
+ let baseline_after = assert_within_the_forward(&rows);
+ assert_eq!(rows[1].logs, 1, "the drop includes the log's storage gas from the first log on");
+ assert!(rows[2].logs > 1, "the greedy callee logs until its forward runs low");
+
+ // The two ends of the calibration, for the table.
+ rows.extend([run(GAS_LIMIT, Callee::burns(), work), run(GAS_LIMIT, Callee::burns(), work + 1)]);
+ print_table("6a. Rex6, gas limit 20M, forward 1M", &rows, baseline_after);
+}
+
+#[test]
+fn test_rex6_a_callee_spends_the_same_at_a_larger_gas_limit() {
+ let spends = |gas_limit| {
+ let rows: Vec<_> = callees().into_iter().map(|c| run(gas_limit, c, 0)).collect();
+ let baseline_after = assert_within_the_forward(&rows);
+ let spends: Vec<_> =
+ rows.iter().map(|row| baseline_after - row.gas_around_call.unwrap().1).collect();
+ (rows, baseline_after, spends)
+ };
+ let (_, _, at_20m) = spends(20_000_000);
+ let (rows, baseline_after, at_400m) = spends(400_000_000);
+ assert_eq!(at_20m, at_400m, "each callee spends the same at either gas limit");
+ print_table("6b. Rex6, gas limit 400M, forward 1M, no work", &rows, baseline_after);
+}
diff --git a/bin/mega-evme/tests/satin-differences.md b/bin/mega-evme/tests/satin-differences.md
index 3f133ef8d..40079bde1 100644
--- a/bin/mega-evme/tests/satin-differences.md
+++ b/bin/mega-evme/tests/satin-differences.md
@@ -35,7 +35,7 @@ Each fixture's command run on both engines: `tests/fixtures/test_.json` an
## Recorded mainnet blocks
-The three Rex6 blocks of `tests/fixtures/blocks`, each replayed on both engines. The legacy replay of each matches the chain (every receipt and the receipts root), so the legacy column is the chain's. Satin runs the transactions as signed, on the state their parent block left.
+The three Rex6 blocks of `tests/fixtures/blocks.tar.xz`, each replayed on both engines. The legacy replay of each matches the chain (every receipt and the receipts root), so the legacy column is the chain's. Satin runs the transactions as signed, on the state their parent block left.
| Block | Transactions | Legacy gas | Satin gas | Satin / legacy | Regular | State | History | Status differs | Logs | Refused |
|---|---:|---:|---:|---:|---:|---:|---:|---:|---|---:|
diff --git a/crates/mega-evm/README.md b/crates/mega-evm/README.md
index 9bb86423e..29ff43c68 100644
--- a/crates/mega-evm/README.md
+++ b/crates/mega-evm/README.md
@@ -26,6 +26,7 @@ The legacy spec names do not parse: `"Rex6".parse::()` fails with `P
Satin is under construction.
Today it runs transactions through its own handler over op-revm's, with EIP-8037 and the EIP-2780 intrinsic cost switched on and a 200,000,000 execution cap; gas above the cap goes to the EIP-8037 reservoir.
+A call or creation forwards at most `remaining − remaining × 2 / 100` of its caller's regular gas, Rex6's rule in place of EIP-150's 63/64, and its child takes the same share of the reservoir its caller has left, whatever regular gas the call asks for; the transaction's own frame and a system call's outermost frame take the whole reservoir.
The gas schedule is Amsterdam's, EIP-8038's state-access prices included, with two changes: the EIP-8037 state-gas entries are rebuilt from MegaETH's own cost per state byte, so a new storage slot draws 97,920 state gas and a new account 183,600, and a byte of deployed code is priced at MegaETH's cost per history byte.
The schedule also brings the Amsterdam opcodes (`DUPN`, `SWAPN`, `EXCHANGE`, `SLOTNUM`) and raises the code-size limits to 512 KiB of contract and 1 MiB of initcode.
@@ -38,7 +39,7 @@ Its byte prices are an input: the `satin-price-override` feature, off by default
The precompile set is op-revm's Karst set with KZG point evaluation repriced to 100,000.
It is carried as an alloy-evm `PrecompilesMap`, so a node can add or replace an address through `MegaEvmFactory::with_dyn_precompiles_builder`.
-The common execution layer is in place: the frame lifecycle the later mechanisms plug into, the count of data-size bytes and write records per frame, the stop protocol that reverts the frame crossing a limit, which its caller may catch, and the inspector contract: the admission gate and what a rewrite does not change.
+The common execution layer is in place: the frame lifecycle the later mechanisms plug into, the count of data-size bytes, write records and new state per frame, the stop protocol that reverts the frame crossing a limit, which its caller may catch, and the inspector contract: what a rewrite does not change.
The data-size limit is in place on top of it.
A transaction is held to a data-size limit, and every frame to a budget: the transaction's own frame gets what its body leaves, and a child 98% of what its parent has left.
@@ -47,16 +48,16 @@ A transfer log counts what a `LOG3` of one word counts, 160 bytes, where the val
A frame start revm refuses on its caller's account — a value the caller cannot fund, a creation whose creator's nonce cannot be bumped — counts nothing; a creation onto an occupied address is counted, and revm refuses it after the count.
A frame that crosses its budget reverts alone; a transaction that crosses its limit is stopped with a revert carrying `MegaLimitExceeded`, and pays only for what ran.
A record is checked before its history is charged, so a record the limit rejects costs nothing and the stop is what the transaction reports.
-The limits are fixed per spec, `ProtocolLimits::for_spec`: Satin holds each transaction and the block to 12.5 MiB of data size and a detained transaction to 20,000,000 of compute past its read, and every EVM, a bare one included, runs under them; `EvmTxRuntimeLimits` sets others on an EVM, a tool's or a test's counterfactual.
-The block's data size is a packing budget: the transaction that crosses it is packed and the next one refused.
+The limits are fixed per spec, `ProtocolLimits::for_spec`: Satin holds each transaction and the block to 12.5 MiB of data size, 500,000 write records and 1,000 new accounts and slots, and a detained transaction to 20,000,000 of compute past its read, and every EVM, a bare one included, runs under them; `EvmTxRuntimeLimits` sets others on an EVM, a tool's or a test's counterfactual.
+The block's data size, write records and state growth are packing budgets: the transaction that reaches one is packed and the next ordinary one refused.
`MegaEvm::execute_transaction` returns the result with the gas split into its regular, state and history ledgers beside the history bytes, the usage counted and the limit that stopped the transaction, if any.
Block execution is in place too: `MegaBlockExecutor` is alloy-evm's `BlockExecutor` over a `MegaEvm`, with the block rules of the Karst base — a fork's activation block admits only deposit transactions, the data-availability footprint of the block's transactions is held to the block's gas limit and reported as its blob gas, and the L1 block info is read by the first transaction that prices against it, so the block's own L1 info deposit is what the transactions after it are priced with.
Every transaction is held to the spec's limits, and the block counts what its transactions spent on each of the three ledgers and the history bytes they appended.
-The limits that change a result are protocol values fixed per spec, `ProtocolLimits::for_spec`: the per-transaction runtime limits and the block's data-size budget, the same on every chain, so no chain configuration carries them and a node passes none of them.
-The block context a node passes carries only building policy (`BlockLimits`): a transaction's declared gas, the encoded sizes and the data-availability sizes, which only a builder applies and never to a deposit, and a cap that can lower the block's data-size budget and never raise it, so a validator that leaves it at its default computes the block a builder packed under any policy.
+The limits that change a result are protocol values fixed per spec, `ProtocolLimits::for_spec`: the per-transaction runtime limits and the block's three packing budgets, the same on every chain, so no chain configuration carries them and a node passes none of them.
+The block context a node passes carries only building policy (`BlockLimits`): a transaction's declared gas, the encoded sizes and the data-availability sizes, which only a builder applies and never to a deposit, and caps that can lower the block's three packing budgets and never raise them, so a validator that leaves it at its default computes the block a builder packed under any policy.
The execution figure a block counts for a transaction is its regular ledger — its gas less state and history, read off revm's `Gas` — at least its EIP-7623 floor.
-The block's data-size cap never refuses a deposit, which the block must include; a deposit still counts towards it.
+The block's packing budgets never refuse a deposit, which the block must include, or a Mega System Transaction; both still count towards them.
A builder that executes candidates and chooses among them commits through `commit_transaction_outcome`, which checks the block's counters again; alloy-evm's `commit_transaction` cannot fail and expects each outcome to commit before the next transaction executes, and a debug build asserts it.
`apply_pre_execution_changes` makes the EIP-2935 and EIP-4788 calls, in the block in which Satin activates — which the node says with `MegaBlockExecutionCtx::satin_activation_block` — checks that the six MegaETH system contracts and the EIP-7997 `CREATE2` factory hold the code Satin runs, which the legacy forks and OP's genesis tooling installed and without which that block is invalid, applies a role change the `SequencerRegistry` has due in the block with its `applyPendingChanges()` call, and last reads the L1 block contract's account and the five slots the block's transactions can be priced against, which op-revm and the executor read on the database rather than through a transaction.
It commits each pre-block state on its own, in order, read-only entries included — the two EIP calls, the activation block's seven reads, the read of the registry's pending changes and its call, and the L1 block info; with the included transactions' states and oracle reads, and the block hashes and buckets the executor exports, the sequence of committed states is the witness a stateless client needs, and a node collects it with a commit hook on its `State` (`State::set_state_hook`).
@@ -64,8 +65,8 @@ A database that cannot serve one of those L1 reads fails the block before its fi
A system call runs as EIP-8037 has it: at most 30,000,000 of its gas limit is regular gas, which is what `GAS` reads inside it, and the rest is its state-gas reservoir, which the state it writes draws first.
revm's default system-call gas limit, 31,566,720, is 30,000,000 and a reservoir of sixteen fresh slots.
-The block's pre-block calls run on the block's gas limit and never less than 30,000,000, the legacy engine's budget kept as it was; what it adds above 30,000,000 is reservoir, not regular gas.
-The legacy engine widened it for the storage gas a crowded SALT bucket multiplied, which a system call no longer pays: it prices its state at the minimum bucket.
+The block's pre-block calls run on `constants::PRE_BLOCK_CALL_GAS_LIMIT`, 31,566,720, whatever the block's gas limit: 30,000,000 of regular gas and a reservoir of sixteen fresh slots at the minimum bucket, which a system call prices its state at.
+The legacy engine's budget, the block's gas limit and never less than 30,000,000, is gone: it was widened for the storage gas a crowded SALT bucket multiplied, which a system call no longer pays.
A pre-block call that does not succeed refuses the block with the call's own validation error; a database error the database calls fatal is an internal error instead, since it says nothing about the block.
That is the rule alloy-evm's block executor holds a transaction's database error to.
A system call pays no history gas, is held to no per-transaction limit and is not detained.
@@ -121,7 +122,7 @@ The body is charged at validation, in the EIP-8037 intrinsic state-gas slot so t
Everything else is charged where the write is made and given back, at the same price, by whoever's failure takes it back.
The records a `CALL`, `CALLCODE`, `CREATE` or `CREATE2` starts a frame for are charged to the caller out of what it kept after forwarding gas: a caller that cannot pay halts, and the frame does not start.
A deposit, a transaction the protocol itself sent and a system call pay no history at all.
-The last two are held to no per-transaction limit either, for the same reason — the protocol's maintenance must not fail on a resource limit: no data-size limit and no frame budget stops them, and what they use is counted and reported all the same.
+The last two are held to no per-transaction limit either, for the same reason — the protocol's maintenance must not fail on a resource limit: no data-size, KV-update or state-growth limit and no frame budget stops them, and what they use is counted and reported all the same.
A user's deposit is held to every limit.
The pairing between the two counts is per record, not per transaction.
@@ -133,15 +134,16 @@ The history bytes a transaction reports count those bytes all the same, so a blo
The transfer log of the value that granted an allowance draws nothing from it.
The byte column is the history the schedule prices, not the chain's physical growth: a transaction exempt from history gas reports none, a body counts its five fixed write records even when fewer fee accounts are written, and the transfer logs are not in it.
-No limit holds the KV count or the state a transaction adds.
-The KV count is the write-record count the layer keeps — one record per account or storage write the transaction keeps, the sender and the fee accounts being the body's.
-Every record is forty bytes of data size, so at the production data-size caps a transaction or a block keeps at most 327,680 records.
-The transaction's KV count is in its outcome's usage and the block's in its result.
-A transaction's state growth is the EIP-8037 state gas it spends, at the price of the SALT bucket it lands in: what bounds it is what it costs.
+The KV-update limit is in place beside it.
+The KV count is the write-record count the layer keeps — one record per account or storage write the transaction keeps, the sender and the fee accounts being the body's — and a transaction is held to 500,000 of them and every frame to 98% of what its parent has left.
+Every record is forty bytes of data size, so at the production data-size caps a transaction or a block keeps at most 327,680 records and the data size binds first; the KV check is still made.
+The state-growth limit is in place too: the net count of new accounts and new slots a transaction keeps, where EIP-8037 charges the state gas of one, is held to 1,000, and every frame to 98% of what its parent has left.
+A slot written back to zero falls, a failed frame's net goes with it, and a negative net never enlarges the next child's budget; EIP-8037 still prices the state a transaction adds, but the count is what stops the 1,001st slot.
+An EIP-7702 list that would keep more records or create more accounts than the transaction may is skipped whole, and the transaction's own frame is stopped before it runs.
+The transaction's KV count and state growth are in its outcome's usage and the block's in its result.
Gas detention is in place: a transaction that reads volatile data — the block environment, the block beneficiary's account, the Oracle's storage — may compute at most 20,000,000 more gas after the read than it had spent at it.
-Compute is the regular gas spent: the state and history gas that spilled onto regular gas are not compute, and neither is what a halting frame burns.
-The one exception is what a frame has left when an opcode's static gas fails, which counts as compute: under that charge's price per halting frame, so the stop only comes earlier.
+Compute is the regular gas spent: the state and history gas that spilled onto regular gas are not compute, and neither is what a halting frame burns, whatever charge it could not pay, an opcode's static gas included.
The Host marks the read where it loads the value, and the most restrictive read binds.
Every frame's spendable gas is held to what the limit leaves the transaction, and the rest is withheld, with the revm fork's withheld part of a frame's regular gas: a regular charge cannot draw it, and every other reader of the frame's gas — `GAS`, the gas a call forwards, the `SSTORE` sentry, what a callee returns — counts it.
So a transaction that reads runs as it would without the read until a regular charge needs the withheld gas.
@@ -159,15 +161,16 @@ The error's argument is a `uint8`: a refused `SLOTNUM` names access type 12, whi
The two caps are runtime limits, 20,000,000 each by default; `EvmTxRuntimeLimits::no_limits()` leaves them unlimited, and a transaction whose caps are both unlimited is not detained.
The protocol's own transactions and the system calls are not detained either.
-Every limit — the transaction's data size, a frame's data-size budget and gas detention's compute limit — stops the frame that crosses it the same way.
+Every limit — the transaction's data size, KV updates and state growth, a frame's budget in each, and gas detention's compute limit — stops the frame that crosses it the same way.
That frame reverts with `MegaLimitExceeded(kind, limit)`, keeping nothing it wrote or logged, and its caller resumes as after any revert: the call fails, the stop is its return data, and the gas the frame had comes back.
The caller is held to what the transaction has left, so a write or a charge of its own that crosses again stops it in turn, and a caller that catches the stop and ends lets the transaction succeed.
Only a stop of the transaction's own frame is the transaction's result, and `LimitStop` reports only that one.
It settles like any EIP-8037 revert: the transaction keeps nothing it wrote or logged, its sender pays the intrinsic gas and what ran, and gets back the rest of its regular gas and the reservoir, less the body's history.
Nothing is rescued, because nothing was taken: detention withholds gas inside a frame's own tracker and never spends it.
-An inspector may rewrite a stop as it may any failure; a frame that kept nothing settles as one whatever the inspector made of its result.
+An inspector may rewrite a stop as it may any failure, and the result it hands back is taken as given, as revm takes it.
+An inspector sees a frame that crosses the compute limit end with the stop: the stop is made once the frame's run returns, before the inspector's `call_end`, `create_end` and `frame_end`, so a tracer shows the frame as the receipt bills it.
A real out-of-gas and a precompile given less than its price still halt and burn what their frame was given.
-`tests/satin/stops.rs` pins every limit crossed by the transaction's own frame and by a frame three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as frames that kept nothing.
+`tests/satin/stops.rs` pins every limit crossed by the transaction's own frame and by a frame three calls down, whose callers catch the stop and succeed, below and above the execution cap, with and without an inspector that records every frame's end, and a column of stopped creations an inspector revives, which settle as the successes it made of them.
## Quick start
@@ -204,22 +207,15 @@ for tx in transactions {
let (evm, result) = executor.finish_with_counters()?;
```
-Block execution admits an inspected transaction only from an EVM whose inspector is declared read-only:
-
-```rust,ignore
-use mega_evm::DeclaredObserver;
-
-let evm = MegaEvm::new(context).with_trusted_inspector(DeclaredObserver(tracer));
-assert!(!evm.has_rewriting_inspector());
-```
-
-A declared observer sees a block's transactions, user and system alike, and nothing else: the pre-block calls run no inspector, and the end of the block runs no code.
-Outside block execution an inspector may rewrite what execution produces — Foundry's cheatcodes are built on that — within the inspector contract.
-A failed creation rewritten into a success is refused, and a limit's stop is not rewritten.
-A frame an inspector answered in place of running, or a failed frame it turned into a success, settles into its caller as a frame that kept nothing: the caller sees the success, the output and the regular gas the inspector chose, and no state gas, history gas, refund or write record of writes the journal does not hold.
-An answer hands its caller back the reservoir it forwarded, whatever gas the inspector built it on.
-A success an inspector rewrites into a failure has its journal taken back as a failed frame's is, so the state follows the failure its ledgers settle as.
-Gas an inspector writes after a frame's last instruction reaches nobody, and a charge a frame cannot pay is refused without stopping it.
+Block execution admits any inspector: a node decides which inspectors may run on block production, and the engine no longer refuses one.
+An inspector runs on revm's inspected lifecycle unchanged: the engine's frame start and return are the ones both loops share, and it does nothing extra for an inspector.
+An inspector sees a block's transactions, user and system alike, and nothing else: the pre-block calls run no inspector, and the end of the block runs no code.
+An inspector may rewrite what execution produces — Foundry's cheatcodes are built on that — within the inspector contract.
+A rewritten result is taken as given, as revm takes it: revm commits or reverts the frame's journal before the inspector sees the result, and the caller settles what the inspector hands back, its gas, reservoir and byte pool included.
+A failed frame turned into a success keeps its journal reverted and settles as a success, its charges and records merged; a success turned into a failure keeps its journal and settles as a failure; a frame answered in place of running keeps what its caller's opcode was charged for it, and settles on the gas the answer is built on — `Gas::new(limit)` carries no reservoir.
+A failed creation rewritten into a success hands its creator the address the inspector gave, with nothing deployed there.
+Gas an inspector writes after a frame's last instruction reaches nobody, and a charge a frame cannot pay is refused without stopping it, its record left on the frame's gas as revm leaves it.
+An answer an inspector gives in place of a frame is taken as given too: no limit holds it.
`tests/satin/inspector_cheatcodes.rs` drives `deal`, `store`, `pauseGasMetering` / `resumeGasMetering` and `expectRevert` through the engine as Foundry's inspector does.
## Node integration
diff --git a/crates/mega-evm/benches/transact.rs b/crates/mega-evm/benches/transact.rs
index 1acddffa6..81a7def05 100644
--- a/crates/mega-evm/benches/transact.rs
+++ b/crates/mega-evm/benches/transact.rs
@@ -5,10 +5,11 @@
//!
//! - `empty_transaction`, `ether_transfer`: the per-transaction cost.
//! - `deep_calls`: a contract calling itself 64 deep, each frame writing a slot and logging, so
-//! every frame pays the frame lifecycle's lanes and every `SSTORE` and `LOG` its commit wrapper.
+//! every frame pays the frame lifecycle's start and return — its start held to the limits, its
+//! byte pool forwarded and settled — and every `SSTORE` and `LOG` its completed-write hook.
//! - `storage_writes`: 200 first writes to fresh slots, then 200 writes back, in one frame: the
-//! `SSTORE` wrapper's commit and refund.
-//! - `logs`: 200 two-topic logs in one frame: the `LOG` wrapper's commit, and the one
+//! `SSTORE`'s completed-write hook, its commit and its refund.
+//! - `logs`: 200 two-topic logs in one frame: the `LOG`'s completed-write hook, and the one
//! `record_history_cost` each log's bytes cost — no allocation, no second pass over the table.
//! - `calldata`: a call carrying 4 KiB of calldata, which is 4 KiB of the transaction body's
//! history, priced once before the first frame runs.
@@ -33,9 +34,9 @@
//! gas detention marks in the Host and commits in the opcode's wrapper; the first caps the frame,
//! and the call starts and resumes under the limit.
//! - `hashes_and_copies`: 200 rounds of a 32-byte `KECCAK256`, `MCOPY`, `CALLDATACOPY` and
-//! `CODECOPY`, an empty `RETURNDATACOPY` and an `EXP` of a one-byte exponent: the wrapper each of
-//! them runs in, which notes the frame's gas for gas detention when the opcode's charge fails and
-//! compares a result when it does not.
+//! `CODECOPY`, an empty `RETURNDATACOPY` and an `EXP` of a one-byte exponent: revm's own
+//! instructions, which no wrapper surrounds, since what a failed charge leaves the frame is read
+//! off the fork's failed-charge record.
//! - `data_size_limit`: 200 fresh slots and 200 two-topic logs in one frame, run under a
//! transaction data-size limit equal to exactly what the transaction keeps, so every record is
//! checked against a limit it is about to reach (`satin`); the same one byte short of it, so the
@@ -554,19 +555,23 @@ fn bench_transact(c: &mut Criterion) {
assert!(at_limit.result.is_success(), "data_size_limit: {:?}", at_limit.result);
assert_eq!(
at_limit.usage,
- LimitUsage { data_size: LIMITED_KEPT, write_records: REPEAT },
+ LimitUsage { data_size: LIMITED_KEPT, write_records: REPEAT, state_growth: REPEAT },
"data_size_limit: the arm must keep every byte and record it is sized for",
);
let stopped = MegaEvm::new(limited(LIMITED_KEPT - 1))
.execute_transaction(OpTx(limited_tx.clone()))
.unwrap();
+ // The transaction's own frame keeps everything but the body, so the last log crosses that
+ // frame's budget, what the limit leaves after the body, together with the limit, and the stop
+ // names the budget.
+ let body = TX_BODY_SIZE + limited_tx.base.data.len() as u64;
assert_eq!(
stopped.limit_exceeded,
Some(LimitCheck::ExceedsLimit {
kind: LimitKind::DataSize,
- limit: LIMITED_KEPT - 1,
- used: LIMITED_KEPT,
- frame_local: false,
+ limit: LIMITED_KEPT - 1 - body,
+ used: LIMITED_KEPT - body,
+ frame_local: true,
}),
"data_size_limit/stopped: the last log must be the byte that crosses",
);
diff --git a/crates/mega-evm/src/access/detention.rs b/crates/mega-evm/src/access/detention.rs
index c013d8c30..e8b8723fd 100644
--- a/crates/mega-evm/src/access/detention.rs
+++ b/crates/mega-evm/src/access/detention.rs
@@ -6,7 +6,10 @@ use core::{cell::Cell, num::NonZeroU64};
use std::vec::Vec;
use alloy_primitives::{Bytes, U256};
-use revm::interpreter::{gas::WithheldCrossing, Gas, InstructionResult, InterpreterResult};
+use revm::{
+ context_interface::cfg::gas::GasTracker,
+ interpreter::{gas::WithheldCrossing, Gas, InstructionResult, InterpreterResult},
+};
use super::VolatileDataAccess;
use crate::system::VOLATILE_DATA_ACCESS_DISABLED_SELECTOR;
@@ -18,7 +21,8 @@ pub(crate) struct ComputeStop {
/// The most compute the transaction may reach.
pub(crate) limit: u64,
/// The transaction's compute before the charge that would have crossed the limit: what its
- /// regular ledger bills once the stopped frame's gas is put back.
+ /// regular ledger bills once the stopped frame's gas is put back, and the stipends of its
+ /// value calls on top, which that ledger never billed.
pub(crate) used: u64,
}
@@ -27,43 +31,40 @@ pub(crate) struct ComputeStop {
struct DetainedFrame {
/// The frame's regular gas spent when it suspended on a child ([`regular_spent`]).
at_suspension: u64,
+ /// The stipend of the value call the frame suspended on, which revm adds to the child's gas
+ /// limit and the frame never paid: zero for any other child.
+ child_stipend: u64,
/// While a child of the frame runs: what the frame adds to the transaction's compute, which is
- /// [`at_suspension`](Self::at_suspension) less the child's gas limit.
+ /// [`at_suspension`](Self::at_suspension) less the gas it forwarded the child — the child's
+ /// gas limit without the stipend.
contribution: u64,
}
-/// What detention records of a frame when revm is about to build a child of it, while no read has
-/// set a limit: enough to rebuild what the frame adds to the transaction's compute while that
-/// child runs, should a read below it set the first limit.
-#[derive(Clone, Copy, Debug, Default)]
-struct CallerRecord {
- /// The frame's regular gas spent ([`regular_spent`]).
- spent: u64,
- /// The frame's own gas limit: what its caller's regular gas spent is taken less of.
- limit: u64,
-}
-
-/// The frames' figures the transaction's compute is read from.
-///
-/// Detention keeps them from the first read that sets a limit on; debug builds keep a second copy
-/// from the transaction's first frame on, by the same updates, and hold the first to it.
+/// The frames' figures the transaction's compute is read from, kept from the transaction's first
+/// frame on.
#[derive(Clone, Debug, Default)]
struct FrameFigures {
/// One entry per frame that runs or is suspended, the running one last.
frames: Vec,
/// The compute of the frames suspended on a child that runs.
suspended: u64,
+ /// The stipends of the value calls that returned: gas nobody paid, which came back to the
+ /// callers' gas with what their children left of it, so the callers' regular gas spent is
+ /// short of their compute by these.
+ stipends: u64,
}
impl FrameFigures {
fn clear(&mut self) {
self.frames.clear();
self.suspended = 0;
+ self.stipends = 0;
}
/// The frame at `depth`, whose gas limit is `gas_limit`, is about to run. On its first run its
/// caller's compute is added; on a resume it is taken back out, because the frame's own
- /// regular gas spent now accounts for the child.
+ /// regular gas spent now accounts for the child — but for a value call's stipend, which the
+ /// child's return handed it on top of what it forwarded, and which is counted apart.
fn on_frame_run(&mut self, gas_limit: u64, depth: usize) {
if self.frames.len() == depth {
let contribution = self.caller_contribution(depth, gas_limit);
@@ -74,15 +75,19 @@ impl FrameFigures {
self.frames.push(DetainedFrame::default());
} else if let Some(frame) = self.frames.get_mut(depth) {
self.suspended = self.suspended.saturating_sub(frame.contribution);
+ self.stipends = self.stipends.saturating_add(frame.child_stipend);
frame.contribution = 0;
+ frame.child_stipend = 0;
}
debug_assert_eq!(self.frames.len(), depth + 1, "one entry per frame that runs");
}
- /// The frame at `depth`, whose gas is `gas`, suspended to start a child.
- fn on_frame_suspend(&mut self, gas: &Gas, depth: usize) {
+ /// The frame at `depth`, whose gas is `gas`, suspended to start a child that revm gives a
+ /// value call's `stipend` on top of what the frame forwarded.
+ fn on_frame_suspend(&mut self, gas: &Gas, depth: usize, stipend: u64) {
if let Some(frame) = self.frames.get_mut(depth) {
- frame.at_suspension = regular_spent(gas);
+ frame.at_suspension = regular_spent(gas.tracker());
+ frame.child_stipend = stipend;
}
}
@@ -93,28 +98,12 @@ impl FrameFigures {
}
/// What the caller of a frame at `depth` with `gas_limit` adds to the transaction's compute
- /// while the frame runs: its regular gas spent at suspension, less the frame's gas limit. The
- /// transaction's own frame has no caller.
+ /// while the frame runs: its regular gas spent at suspension, less what it forwarded — the
+ /// frame's gas limit without a value call's stipend. The transaction's own frame has no caller.
fn caller_contribution(&self, depth: usize, gas_limit: u64) -> u64 {
- depth
- .checked_sub(1)
- .and_then(|i| self.frames.get(i))
- .map_or(0, |caller| caller.at_suspension.saturating_sub(gas_limit))
- }
-
- /// Asserts that `kept`, the figures detention keeps, are these, kept from the transaction's
- /// first frame on: the same entries, but for the running frame's regular gas spent at its last
- /// suspension, which these keep stale until the frame suspends again and nothing reads before.
- #[cfg(debug_assertions)]
- fn assert_kept(&self, kept: &Self) {
- assert_eq!(kept.suspended, self.suspended, "the compute of the suspended frames");
- assert_eq!(kept.frames.len(), self.frames.len(), "one entry per frame that runs");
- if let Some(((last, below), (eager_last, eager_below))) =
- kept.frames.split_last().zip(self.frames.split_last())
- {
- assert_eq!(below, eager_below, "the frames the running one runs under");
- assert_eq!(last.contribution, eager_last.contribution, "the running frame's");
- }
+ depth.checked_sub(1).and_then(|i| self.frames.get(i)).map_or(0, |caller| {
+ caller.at_suspension.saturating_sub(gas_limit.saturating_sub(caller.child_stipend))
+ })
}
}
@@ -125,32 +114,32 @@ impl FrameFigures {
///
/// # Compute
///
-/// Compute is the regular gas the transaction spends on what it runs. A frame's regular gas spent
-/// is read off its [`Gas`]: its limit, less what it has left, less the state and history gas that
-/// spilled onto its regular gas, which are not compute. What it has left is the whole of its
-/// regular gas, the part withheld from regular charges included, so withheld gas is never spent,
-/// and every other reader of the frame's gas sees the same figure.
+/// Compute is the regular gas the transaction's frames spend on what they run, whoever funds it. A
+/// frame's regular gas spent is read off its [`Gas`]: its limit, less what it has left, less the
+/// state and history gas that spilled onto its regular gas, which are not compute. What it has
+/// left is the whole of its regular gas, the part withheld from regular charges included, so
+/// withheld gas is never spent, and every other reader of the frame's gas sees the same figure.
///
/// The transaction's compute is its frames' compute: the frame that runs, and every frame
-/// suspended on a child that runs, as it stood when it suspended, less the child's gas limit. A
-/// value call's stipend is part of that limit and gas nobody paid, so taking the whole limit off
-/// takes the stipend off too, as the caller's regular gas spent does once the child returned. So
-/// the figure follows the regular ledger of the transaction's frames at every moment, before,
-/// during and after each child:
+/// suspended on a child that runs, as it stood when it suspended, less the gas it forwarded the
+/// child. A value call's stipend is not forwarded gas: revm adds it to the child's gas limit on
+/// top of the forward, and what the child runs on it is compute like the rest of what it runs.
+/// When the child returns, what it left of its gas comes back to the caller, the stipend's part
+/// included, so the caller's regular gas spent is short of what it and the child computed by the
+/// whole stipend, which is counted apart once the child returned. So the figure is the same
+/// before, during and after each child:
///
/// ```text
-/// compute = Σ suspended callers (spent at suspension − child's gas limit)
+/// compute = Σ suspended callers (spent at suspension − gas forwarded)
/// + regular_spent(running frame)
+/// + Σ stipends of the value calls that returned
/// − burned
/// ```
///
-/// The stipend stays outside compute on purpose: compute is regular gas drawn from the
-/// transaction's own pools. A callee may run up to 2,300 gas on each value call's stipend beyond
-/// the compute counted. A value call costs its caller 9,100 of compute — the 11,300 of the value
-/// transfer less the 2,300 stipend it carries, and a warm access of 100 — and a callee that leaves
-/// the stipend unspent returns it, which lowers the caller's spent regular gas: a warm value call
-/// to an empty account counts 9,100 − 2,300 = 6,800. So the gas run after a read is at most about
-/// 34% (2,300 / 6,800) more than the cap.
+/// Every regular charge an instruction makes counts, the ones a callee pays out of a stipend
+/// included, and nothing else does, so the gas run after a read is at most the cap. The regular
+/// ledger bills the transaction its compute less the stipends, which no pool of the transaction's
+/// gas paid.
///
/// A keyless deployment's call is the transaction's own frame, and runs no code: it charges its
/// own work — the overhead of decoding the signed transaction and recovering its signer, and the
@@ -160,29 +149,19 @@ impl FrameFigures {
///
/// The one part of the regular ledger that is not compute is what a halt burns (`burned`): a
/// frame that halts consumes the gas it had left, and its spill, without running anything with
-/// it. A frame answered without running that halts burns its whole gas limit. An out-of-gas zeroes
-/// what the frame had before the frame returns; the wrapper of the opcode whose charge failed
-/// notes it first, `EXP`'s and the unbounded charges of `KECCAK256` and the copies into memory
-/// included.
-///
-/// The one charge no wrapper sees is an opcode's static gas, which the interpreter's step loop
-/// makes before the opcode runs. When it fails, what the halting frame had left counts as
-/// compute: per halting frame, less than the failed charge's price, so at most 4,999, on
-/// `SELFDESTRUCT`. Burned gas is counted as compute, so the stop comes earlier, never later. A
-/// frame whose leftover takes the compute past the limit does so without a crossing, so the stop
-/// is its caller's next charge, and the regular ledger at the stop holds that leftover's part
-/// past the limit beside the limit.
+/// it. A frame answered without running that halts burns its whole gas limit: a precompile that
+/// runs out of gas counts nothing of its forward, nor of a value call's stipend, as compute. An
+/// out-of-gas zeroes what the frame had before the frame returns; the revm fork records it first,
+/// before every deduction that fails — an opcode's static gas, which the interpreter's step loop
+/// charges before the opcode runs, included — and before a halt on a cold access the frame cannot
+/// pay, and the frame's end reads the record. A frame whose opcode cannot pay the records of the
+/// frame it was starting gets the forward back, and records what it has then, before it halts.
///
/// # Keeping the figure
///
-/// Only a read that sets a limit, and what follows it, needs the transaction's compute, so the
-/// frames' figures are kept only from the first such read on. Before it, what a halt burns and the
-/// switch are kept as every frame starts and ends, and nothing else but one record per frame revm
-/// builds a child of: its regular gas spent and its own gas limit then, which is what it stands at
-/// while that child runs. At the first read, the frames the reading frame runs under are exactly
-/// the frames suspended on a running child, and what each adds is rebuilt from its record: its
-/// regular gas spent less the gas limit of the frame above it, the reading frame's own for the
-/// last. From there every frame is kept as it starts, suspends, resumes and ends.
+/// The frames' figures are kept for every transaction detention holds, from its first frame on,
+/// as each frame starts, suspends, resumes and ends, so a read at any depth finds the compute of
+/// the frames it runs under already summed.
///
/// # Refused reads
///
@@ -191,12 +170,24 @@ impl FrameFigures {
/// `VolatileDataAccessDisabled`. The switch is scoped to the frame that turned it off and the
/// frames below it, and turns back on when that frame returns. `MegaAccessControl`'s interceptor
/// steers it for the frame that calls the contract.
+///
+/// # What is a read
+///
+/// The Host refuses and marks a load only while the wrapper of an opcode that reads volatile data
+/// runs ([`begin_read`](Self::begin_read)). A load made anywhere else is no volatile read: it is
+/// neither refused nor marked. That is `CREATE`'s and `CREATE2`'s loads of their creator and of
+/// the created address, which revm makes through the Host to check the creator's balance and
+/// nonce and to price the created account — a value call's check of its caller's balance is no
+/// read either — and an inspector's load through the Host.
#[derive(Clone, Debug, Default)]
pub struct Detention {
/// What the Host loaded for the running opcode, waiting for its wrapper.
observed: Cell,
/// What the Host refused to load for the running opcode, waiting for its wrapper.
refused: Cell,
+ /// Whether the wrapper of an opcode that reads volatile data runs it: the Host refuses and
+ /// marks a load only then.
+ reading: bool,
/// Whether the transaction's reads are held to a cap. A system-originated transaction's are
/// not, and neither are a transaction's whose caps are both unlimited.
detains: bool,
@@ -221,18 +212,8 @@ pub struct Detention {
limit: Option,
/// The regular gas the frames that halted burned without running anything with it.
burned: u64,
- /// What the running frame had left when a charge failed on an out-of-gas whose halt zeroes it.
- left_at_halt: Option,
- /// The frames' figures, once a read set a limit.
+ /// The frames' figures, for a transaction detention holds.
figures: FrameFigures,
- /// While no read has set a limit: at each depth, the record of the frame there when revm last
- /// built a child of it in the transaction ([`on_child_build`](Self::on_child_build)). An entry
- /// below the running frame's depth is its caller's, made when revm built the frame above it.
- callers: Vec,
- /// The frames' figures kept from the transaction's first frame on, in debug builds, to hold
- /// the ones rebuilt at the first read, and every one kept after it, to them.
- #[cfg(debug_assertions)]
- eager: FrameFigures,
}
impl Detention {
@@ -244,6 +225,7 @@ impl Detention {
pub(crate) fn reset(&mut self, detains: bool, block_env_cap: u64, oracle_cap: u64) {
self.observed.set(VolatileDataAccess::empty());
self.refused.set(VolatileDataAccess::empty());
+ self.reading = false;
self.detains = detains && (block_env_cap != u64::MAX || oracle_cap != u64::MAX);
self.block_env_cap = block_env_cap;
self.oracle_cap = oracle_cap;
@@ -260,11 +242,7 @@ impl Detention {
self.accessed = VolatileDataAccess::empty();
self.limit = None;
self.burned = 0;
- self.left_at_halt = None;
self.figures.clear();
- self.callers.clear();
- #[cfg(debug_assertions)]
- self.eager.clear();
}
/// Starts every transaction with volatile-data access switched off from `depth` down, as if
@@ -298,23 +276,23 @@ impl Detention {
/* The Host */
- /// Whether the Host refuses a load of `access`: the running frame is in a subtree where
- /// volatile-data access is switched off. A refusal is recorded for the running opcode's
- /// wrapper, which reverts the frame.
+ /// Whether the Host refuses a load of `access`: a read wrapper's opcode makes it, in a frame
+ /// in a subtree where volatile-data access is switched off. A refusal is recorded for the
+ /// wrapper, which reverts the frame. A load outside a wrapper is never refused.
#[inline]
pub(crate) fn refuses(&self, access: VolatileDataAccess) -> bool {
- if !self.refusing {
+ if !(self.refusing && self.reading) {
return false;
}
self.refused.set(access);
true
}
- /// Records that the Host loaded `access` for the running opcode. Its wrapper commits the read
- /// once the opcode completed.
+ /// Records that the Host loaded `access` for the running read wrapper's opcode. The wrapper
+ /// commits the read once the opcode completed. A load outside a wrapper marks nothing.
#[inline]
pub(crate) fn observe(&self, access: VolatileDataAccess) {
- if self.detains {
+ if self.detains && self.reading {
self.observed.set(self.observed.get() | access);
}
}
@@ -328,12 +306,21 @@ impl Detention {
self.refusing
}
- /// Forgets what the Host observed or refused outside an opcode's wrapper, so it is not
- /// committed for the wrong opcode.
+ /// A read wrapper starts its opcode: the Host's loads are reads until [`end_read`]. Nothing is
+ /// observed or refused before, since only a wrapper's opcode observes or refuses, and its
+ /// wrapper takes what it did.
+ ///
+ /// [`end_read`]: Self::end_read
#[inline]
- pub(crate) fn discard_stale_reads(&self) {
- self.observed.set(VolatileDataAccess::empty());
- self.refused.set(VolatileDataAccess::empty());
+ pub(crate) fn begin_read(&mut self) {
+ debug_assert!(!self.has_reads(), "a read left over from before the opcode");
+ self.reading = true;
+ }
+
+ /// The read wrapper's opcode returned: the Host's loads are no reads again.
+ #[inline]
+ pub(crate) const fn end_read(&mut self) {
+ self.reading = false;
}
/// Whether the Host observed or refused anything for the running opcode.
@@ -362,11 +349,10 @@ impl Detention {
self.observed.replace(VolatileDataAccess::empty())
}
- /// Commits the reads `observed` of the opcode the running frame, at `depth` and whose gas is
- /// `gas`, completed: the transaction's limit becomes its compute now plus the reads' cap,
+ /// Commits the reads `observed` of the opcode the running frame, whose gas is `gas`,
+ /// completed: the transaction's limit becomes its compute now plus the reads' cap,
/// unless it is already lower, and the frame's spendable gas is held to what the limit leaves
- /// it. The first read that sets a limit starts keeping the frames' figures
- /// ([`track`](Self::track)).
+ /// it.
///
/// `forwarded` is the regular gas the opcode forwarded to a frame it is about to start, which
/// the frame's regular gas spent includes and its compute does not.
@@ -374,7 +360,6 @@ impl Detention {
&mut self,
observed: VolatileDataAccess,
gas: &mut Gas,
- depth: usize,
forwarded: u64,
) {
self.accessed |= observed;
@@ -382,10 +367,7 @@ impl Detention {
if cap == u64::MAX {
return;
}
- if self.limit.is_none() {
- self.track(gas, depth);
- }
- let compute = self.compute(gas).saturating_sub(forwarded);
+ let compute = self.compute(gas.tracker()).saturating_sub(forwarded);
let limit = self.lower_limit(compute.saturating_add(cap));
gas.limit_spendable(limit.saturating_sub(compute));
}
@@ -411,140 +393,69 @@ impl Detention {
/// it resumes on the gas a child handed back, and after a storage write, whose restore of a
/// slot to its original value refills the state and history gas that spilled onto regular gas.
#[inline]
- pub(crate) fn hold(&self, gas: &mut Gas) {
+ pub(crate) fn hold(&self, gas: &mut GasTracker) {
if let Some(limit) = self.limit {
gas.limit_spendable(limit.saturating_sub(self.compute(gas)));
}
}
- /// Notes what the running frame has left, `left`, when an opcode's charge failed on an
- /// out-of-gas the halt after it zeroes: what the halt burns rather than what the frame ran.
- #[inline]
- pub(crate) const fn note_halt(&mut self, left: u64) {
- self.left_at_halt = Some(left);
- }
-
/* The frame lifecycle */
/// The frame at `depth`, whose gas is `gas`, is about to run: for the first time, or again
/// after a child returned into it.
///
- /// The switch is read for the frame. Once a read set a limit, a frame's first run adds its
- /// caller's compute to the transaction's, now that the frame's gas limit is known — what the
- /// caller forwarded, and a value call's stipend; a resumed frame takes it back out, because
- /// its own regular gas spent now accounts for the child. Then the frame is held to the limit.
+ /// The switch is read for the frame. For a transaction detention holds, a frame's first run
+ /// adds its caller's compute to the transaction's, now that the frame's gas limit is known —
+ /// what the caller forwarded, and a value call's stipend; a resumed frame takes it back out,
+ /// because its own regular gas spent now accounts for the child. Then the frame is held to the
+ /// limit, once a read set one.
#[inline]
pub(crate) fn on_frame_run(&mut self, gas: &mut Gas, depth: usize) {
self.refusing = self.disabled_from.is_some_and(|from| depth >= from);
- #[cfg(debug_assertions)]
- if self.detains {
- self.eager.on_frame_run(gas.limit(), depth);
- }
- // Only a read of a transaction detention holds sets a limit.
- if self.limit.is_none() {
+ if !self.detains {
+ debug_assert!(self.limit.is_none(), "a limit on a transaction detention does not hold");
return;
}
- debug_assert!(self.detains, "a limit on a transaction detention does not hold");
self.figures.on_frame_run(gas.limit(), depth);
- #[cfg(debug_assertions)]
- self.eager.assert_kept(&self.figures);
- self.hold(gas);
+ self.hold(gas.tracker_mut());
}
- /// The frame at `depth`, whose gas is `gas`, suspended to start a child. Its compute stands
- /// still until the child returns.
+ /// The frame at `depth`, whose gas is `gas`, suspended to start a child, to which revm gives
+ /// a value call's `stipend` on top of the gas the frame forwarded. Its compute stands still
+ /// until the child returns.
#[inline]
- pub(crate) fn on_frame_suspend(&mut self, gas: &Gas, depth: usize) {
- #[cfg(debug_assertions)]
+ pub(crate) fn on_frame_suspend(&mut self, gas: &Gas, depth: usize, stipend: u64) {
if self.detains {
- self.eager.on_frame_suspend(gas, depth);
- }
- if self.limit.is_none() {
- return;
- }
- self.figures.on_frame_suspend(gas, depth);
- }
-
- /// Whether revm building a frame's child is to be recorded ([`on_child_build`]): the
- /// transaction is detained, and no read has set a limit.
- ///
- /// [`on_child_build`]: Self::on_child_build
- #[inline]
- pub(crate) const fn records_callers(&self) -> bool {
- self.detains && self.limit.is_none()
- }
-
- /// Records the frame at `depth − 1`, whose gas is `caller`, as revm is about to build a child
- /// of it at `depth`, while no read has set a limit ([`records_callers`]): its regular gas
- /// spent and its gas limit. Until the child returns, that is what the frame stands at, so a
- /// read below it rebuilds what the frame adds to the transaction's compute from it
- /// ([`track`](Self::track)).
- ///
- /// A frame answered without running records its caller too, which the caller's next child
- /// overwrites; a read is only ever made in a frame revm built.
- ///
- /// [`records_callers`]: Self::records_callers
- #[inline]
- pub(crate) fn on_child_build(&mut self, depth: usize, caller: &Gas) {
- debug_assert!(self.records_callers() && depth > 0, "a caller recorded while untracked");
- let index = depth - 1;
- if index >= self.callers.len() {
- self.callers.resize(index + 1, CallerRecord::default());
+ self.figures.on_frame_suspend(gas, depth, stipend);
}
- self.callers[index] = CallerRecord { spent: regular_spent(caller), limit: caller.limit() };
}
- /// Starts keeping the frames' figures at the first read that sets a limit, made by the frame
- /// that runs, at `depth` and whose gas is `gas`.
- ///
- /// The frames it runs under are those suspended on a running child, and each one's record is
- /// the one made when revm built that child: what the frame adds to the transaction's compute is
- /// its regular gas spent then less the child's gas limit — the next record's, or the reading
- /// frame's own for the last. They are added in the order the frames started, as they would
- /// have been when each child first ran.
- #[cold]
- #[inline(never)]
- fn track(&mut self, gas: &Gas, depth: usize) {
- // Every frame below the reading one was built in the transaction while no read had set a
- // limit, so revm building it recorded its caller.
- let records = &self.callers[..depth];
- let reading_limit = gas.limit();
- let figures = &mut self.figures;
- figures.clear();
- for (index, record) in records.iter().enumerate() {
- let child_limit = records.get(index + 1).map_or(reading_limit, |child| child.limit);
- let contribution = record.spent.saturating_sub(child_limit);
- figures.suspended = figures.suspended.saturating_add(contribution);
- figures.frames.push(DetainedFrame { at_suspension: record.spent, contribution });
- }
- figures.frames.push(DetainedFrame::default());
- #[cfg(debug_assertions)]
- self.eager.assert_kept(&self.figures);
- }
-
- /// Records a read of `access` the running frame, at `depth` and whose gas is `gas`, makes
- /// itself rather than through an opcode — a keyless deployment's call reading its signer's
- /// account — and holds the frame to the limit it sets, as an opcode's read is committed
+ /// Records a read of `access` the running frame, whose gas is `gas`, makes itself rather than
+ /// through an opcode — a keyless deployment's call reading its signer's account — and holds
+ /// the frame to the limit it sets, as an opcode's read is committed
/// ([`commit_reads`](Self::commit_reads)). A transaction detention does not hold records
/// nothing, as the Host observes nothing for it.
- pub(crate) fn read_by_frame(
- &mut self,
- access: VolatileDataAccess,
- gas: &mut Gas,
- depth: usize,
- ) {
+ pub(crate) fn read_by_frame(&mut self, access: VolatileDataAccess, gas: &mut Gas) {
if self.detains {
- self.commit_reads(access, gas, depth, 0);
+ self.commit_reads(access, gas, 0);
}
}
/// The frame at `depth` returns `result` with `gas`, after it ran. The switch turns back on if
- /// the frame, or a frame below it, turned it off. A frame that halts burns what it had left.
+ /// the frame, or a frame below it, turned it off. A frame that halts burns what it had left:
+ /// for an out-of-gas, whose halt zeroed the frame's gas, the regular gas the revm fork
+ /// recorded before the failed charge, or before the halt when no charge failed
+ /// (`failed_charge_remaining`); for any other halt, which zeroes nothing, the gas the frame
+ /// returns.
///
- /// Returns the stop when the frame ran out of gas on a charge the withheld part of its gas
+ /// Returns the stop when the frame halted out of gas on a charge the withheld part of its gas
/// would have paid ([`stop`](Self::stop)): the frame crossed the limit, and must revert with
/// the stop rather than halt. The stop's compute is the transaction's with the frame's gas
- /// put back.
+ /// put back. A crossing only ever ends a frame on an out-of-gas, so a frame that returns with
+ /// any other result crossed nothing, whatever record its gas carries: the record of a charge
+ /// an inspector's callback failed stops no frame that ran on and ended otherwise. The frame's
+ /// result is read as its run left it, before an inspector sees it, so what an inspector makes
+ /// of it afterwards is taken as given.
#[inline]
pub(crate) fn on_frame_end(
&mut self,
@@ -552,28 +463,24 @@ impl Detention {
gas: &mut Gas,
depth: usize,
) -> Option {
- let left_at_halt = self.left_at_halt.take();
if self.disabled_from.is_some_and(|from| from >= depth) {
self.disabled_from = None;
}
if !self.detains {
return None;
}
- #[cfg(debug_assertions)]
- self.eager.on_frame_end(depth);
- if self.limit.is_some() {
- self.figures.on_frame_end(depth);
- #[cfg(debug_assertions)]
- self.eager.assert_kept(&self.figures);
- }
- if let Some(limit) = self.stop(gas) {
- return Some(ComputeStop { limit, used: self.compute(gas) });
+ self.figures.on_frame_end(depth);
+ if !result.is_halt() {
+ return None;
}
- if result.is_halt() {
- // The settlement rolls the spill back into regular gas and burns it all.
- let left = left_at_halt.unwrap_or_else(|| gas.remaining());
- self.burned = self.burned.saturating_add(left).saturating_add(gas.state_gas_spilled());
+ if is_out_of_gas(result) {
+ if let Some(limit) = self.stop(gas) {
+ return Some(ComputeStop { limit, used: self.compute(gas.tracker()) });
+ }
}
+ // The settlement rolls the spill back into regular gas and burns it all.
+ let left = gas.failed_charge_remaining().unwrap_or_else(|| gas.remaining());
+ self.burned = self.burned.saturating_add(left).saturating_add(gas.state_gas_spilled());
None
}
@@ -587,7 +494,8 @@ impl Detention {
/// The frame at `depth`, whose gas limit was `gas_limit`, was answered without running —
/// `result` is the answer: a precompile's, an interceptor's, a `keylessDeploy` call's that
- /// carries value, an inspector's, or revm's for a call it did not start.
+ /// carries value, or revm's for a call it did not start. An inspector's answer never reaches
+ /// the engine's frame start, and is taken as given.
///
/// An answer marked as a crossing — a precompile whose price crosses the limit
/// ([`cross_at_price`](Self::cross_at_price)), or one the engine cannot price that ran out of
@@ -671,9 +579,8 @@ impl Detention {
// The answer spent more than the allowance, and no more than the gas limit, so the
// gas limit is above the allowance and the frame would have had the rest withheld. The
// one answer of the engine's own that spends regular gas is that of a `keylessDeploy`
- // call carrying value; the limit is set to the forward all the same, so
- // an inspector's answer built on another limit is settled on what the frame was
- // forwarded.
+ // call carrying value, which is built on the forward; the limit is set to the forward,
+ // so the stop settles on what the frame was forwarded.
//
// The record holds the regular gas the frame had before the charge: the gas limit,
// less the state and history gas that spilled onto it, which the revert that settles
@@ -689,7 +596,7 @@ impl Detention {
// had before the charge: the forward less the spill here, the forward for a precompile's,
// which spills nothing. Put back, it leaves the answer no regular gas spent, so the stop's
// compute is the transaction's when the frame started.
- debug_assert_eq!(regular_spent(&result.gas), 0, "a stopped answer spent nothing");
+ debug_assert_eq!(regular_spent(result.gas.tracker()), 0, "a stopped answer spent nothing");
Some(ComputeStop { limit, used: self.compute_at_start(depth, gas_limit) })
}
@@ -729,12 +636,12 @@ impl Detention {
///
/// The frame's regular gas is put back to what it had before the charge that crossed, the
/// record's [`remaining`](WithheldCrossing::remaining): the charge is not made, so the
- /// transaction is billed its compute at the crossing, less than one charge short of the limit,
- /// and all the frame had left, its spendable and withheld parts together, goes back to its
- /// caller. Whether the halt already zeroed the frame's gas (`OutOfGas`) or not (`MemoryOOG`,
- /// or `return_create`'s own out-of-gas on a deposit charge), the settlement is the same. A
- /// crossing only ever ends a frame on an out-of-gas, and only a frame detention held carries
- /// one.
+ /// transaction's compute at the crossing is less than one charge short of the limit, and it is
+ /// billed that compute less the stipends of its value calls, and all the frame had left, its
+ /// spendable and withheld parts together, goes back to its caller. Whether the halt already
+ /// zeroed the frame's gas (`OutOfGas`) or not (`MemoryOOG`, or `return_create`'s own
+ /// out-of-gas on a deposit charge), the settlement is the same. A crossing only ever ends a
+ /// frame on an out-of-gas, and only a frame detention held carries one.
fn stop(&self, gas: &mut Gas) -> Option {
let crossing = gas.withheld_crossing()?;
gas.set_remaining(crossing.remaining());
@@ -781,16 +688,23 @@ impl Detention {
/* Helpers */
/// The transaction's compute while the running frame has `gas`.
- fn compute(&self, gas: &Gas) -> u64 {
- self.figures.suspended.saturating_add(regular_spent(gas)).saturating_sub(self.burned)
+ fn compute(&self, gas: &GasTracker) -> u64 {
+ let figures = &self.figures;
+ figures
+ .suspended
+ .saturating_add(regular_spent(gas))
+ .saturating_add(figures.stipends)
+ .saturating_sub(self.burned)
}
/// The transaction's compute when a frame at `depth` with `gas_limit` starts, before it runs
/// anything: every suspended caller's, the frame's own caller's included.
fn compute_at_start(&self, depth: usize, gas_limit: u64) -> u64 {
- self.figures
+ let figures = &self.figures;
+ figures
.suspended
- .saturating_add(self.figures.caller_contribution(depth, gas_limit))
+ .saturating_add(figures.caller_contribution(depth, gas_limit))
+ .saturating_add(figures.stipends)
.saturating_sub(self.burned)
}
@@ -846,10 +760,23 @@ pub fn decode_volatile_data_access_disabled(revert_data: &[u8]) -> Option bool {
+ matches!(
+ result,
+ InstructionResult::OutOfGas |
+ InstructionResult::MemoryOOG |
+ InstructionResult::MemoryLimitOOG |
+ InstructionResult::PrecompileOOG |
+ InstructionResult::InvalidOperandOOG |
+ InstructionResult::ReentrancySentryOOG
+ )
+}
+
/// The regular gas a frame spent: its limit, less what it has left — the withheld part included —
/// less the state and history gas that spilled onto its regular gas.
#[inline]
-pub(crate) const fn regular_spent(gas: &Gas) -> u64 {
+pub(crate) const fn regular_spent(gas: &GasTracker) -> u64 {
gas.limit().saturating_sub(gas.remaining()).saturating_sub(gas.state_gas_spilled())
}
@@ -890,7 +817,7 @@ mod tests {
let mut frame = gas(100_000_000, 7);
detention.on_frame_run(&mut frame, 0);
assert!(frame.record_regular_cost(1_000));
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0);
assert_eq!(detention.compute_limit(), Some(1_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS));
assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS);
@@ -906,9 +833,9 @@ mod tests {
let mut detention = detaining();
let mut frame = gas(100_000_000, 0);
detention.on_frame_run(&mut frame, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0);
assert!(frame.record_regular_cost(5_000));
- detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0, 0);
+ detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0);
assert_eq!(detention.compute_limit(), Some(BLOCK_ENV_ACCESS_COMPUTE_GAS));
assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 5_000);
}
@@ -920,10 +847,10 @@ mod tests {
let mut detention = detaining();
let mut frame = gas(100_000_000, 0);
detention.on_frame_run(&mut frame, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0);
assert!(frame.record_state_cost(1_000_000));
- detention.hold(&mut frame);
- assert_eq!(detention.compute(&frame), 0);
+ detention.hold(frame.tracker_mut());
+ assert_eq!(detention.compute(frame.tracker()), 0);
assert_eq!(frame.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS);
}
@@ -938,7 +865,7 @@ mod tests {
let mut detention = detaining();
let mut frame = gas(100_000_000, 0);
detention.on_frame_run(&mut frame, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0);
assert!(frame.record_regular_cost(10));
assert!(!frame.record_regular_cost(BLOCK_ENV_ACCESS_COMPUTE_GAS));
if zeroed {
@@ -949,7 +876,39 @@ mod tests {
assert_eq!(stop, Some(ComputeStop { limit, used: 10 }), "{result:?}");
assert_eq!(frame.remaining(), 100_000_000 - 10);
assert_eq!(frame.withheld_crossing(), None);
- assert_eq!(regular_spent(&frame), 10, "the charge that crossed is not made");
+ assert_eq!(regular_spent(frame.tracker()), 10, "the charge that crossed is not made");
+ }
+ }
+
+ /// A frame that ends with anything but an out-of-gas crossed nothing, whatever record of a
+ /// crossing its gas carries — a charge an inspector's callback failed, left on a frame that
+ /// ran on and ended otherwise: it is no stop, its gas is left as it ended, and a halt burns
+ /// what its failed charge recorded.
+ #[test]
+ fn test_only_an_out_of_gas_is_a_crossings_end() {
+ for result in [
+ InstructionResult::Return,
+ InstructionResult::Revert,
+ InstructionResult::InvalidFEOpcode,
+ InstructionResult::OutOfGas,
+ ] {
+ let mut detention = detaining();
+ let mut frame = gas(100_000_000, 0);
+ detention.on_frame_run(&mut frame, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0);
+ assert!(frame.record_regular_cost(10));
+ assert!(!frame.record_regular_cost(BLOCK_ENV_ACCESS_COMPUTE_GAS));
+ let stop = detention.on_frame_end(result, &mut frame, 0);
+ if result == InstructionResult::OutOfGas {
+ let limit = BLOCK_ENV_ACCESS_COMPUTE_GAS;
+ assert_eq!(stop, Some(ComputeStop { limit, used: 10 }), "{result:?}");
+ continue;
+ }
+ assert_eq!(stop, None, "{result:?}: no stop");
+ assert!(frame.withheld_crossing().is_some(), "{result:?}: the record is left as it is");
+ assert_eq!(frame.remaining(), 100_000_000 - 10, "{result:?}: the gas as it ended");
+ let burned = if result.is_halt() { 100_000_000 - 10 } else { 0 };
+ assert_eq!(detention.burned, burned, "{result:?}: a halt burns what it had");
}
}
@@ -960,10 +919,10 @@ mod tests {
let mut detention = detaining();
let mut caller = gas(100_000_000, 0);
detention.on_frame_run(&mut caller, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0);
assert!(caller.record_regular_cost(7_000));
assert!(caller.record_withheld_first_cost(50_000_000));
- detention.on_frame_suspend(&caller, 0);
+ detention.on_frame_suspend(&caller, 0, 0);
let mut child = gas(50_000_000, 0);
detention.on_frame_run(&mut child, 1);
assert_eq!(child.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 7_000);
@@ -983,9 +942,8 @@ mod tests {
let mut detention = detaining();
let mut frame = gas(100_000_000, 0);
detention.on_frame_run(&mut frame, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0);
assert!(!frame.record_regular_cost(100_000_001));
- detention.note_halt(frame.remaining());
frame.spend_all();
assert_eq!(detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0), None);
assert_eq!(detention.burned, 100_000_000);
@@ -994,44 +952,49 @@ mod tests {
let mut detention = detaining();
let mut frame = gas(1_000_000, 0);
detention.on_frame_run(&mut frame, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0);
assert_eq!(frame.withheld(), 0, "nothing to withhold");
assert!(!frame.record_regular_cost(1_000_001));
frame.spend_all();
assert_eq!(detention.on_frame_end(InstructionResult::OutOfGas, &mut frame, 0), None);
}
- /// A child's compute adds to its caller's; the caller's forwarded gas and the child's stipend
- /// do not, and after the child returns the caller's own gas accounts for it the same way.
+ /// A child's compute adds to its caller's, what it runs on a value call's stipend included;
+ /// the gas the caller forwarded does not. After the child returns, the caller's own gas holds
+ /// what the child ran but for the stipend, which it got back on top of its forward, and the
+ /// stipend is counted apart: the figure is the same.
#[test]
fn test_compute_spans_frames() {
- let mut detention = detaining();
- detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE);
- let mut caller = gas(100_000, 0);
- detention.on_frame_run(&mut caller, 0);
- assert!(caller.record_regular_cost(9_000 + 60_000));
- detention.on_frame_suspend(&caller, 0);
- assert_eq!(detention.compute_at_start(1, 60_000 + 2_300), 9_000 - 2_300);
+ for spent in [4_000, 61_000] {
+ let mut detention = detaining();
+ detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE);
+ let mut caller = gas(100_000, 0);
+ detention.on_frame_run(&mut caller, 0);
+ assert!(caller.record_regular_cost(9_000 + 60_000));
+ detention.on_frame_suspend(&caller, 0, 2_300);
+ assert_eq!(detention.compute_at_start(1, 60_000 + 2_300), 9_000);
- let mut child = gas(60_000 + 2_300, 0);
- detention.on_frame_run(&mut child, 1);
- assert_eq!(detention.compute(&child), 9_000 - 2_300);
- assert!(child.record_regular_cost(4_000));
- assert_eq!(detention.compute(&child), 9_000 + 4_000 - 2_300);
- detention.on_frame_end(InstructionResult::Stop, &mut child, 1);
+ let mut child = gas(60_000 + 2_300, 0);
+ detention.on_frame_run(&mut child, 1);
+ assert_eq!(detention.compute(child.tracker()), 9_000);
+ assert!(child.record_regular_cost(spent));
+ assert_eq!(detention.compute(child.tracker()), 9_000 + spent, "{spent}");
+ detention.on_frame_end(InstructionResult::Stop, &mut child, 1);
- caller.erase_cost(child.remaining());
- detention.on_frame_run(&mut caller, 0);
- assert_eq!(detention.compute(&caller), 9_000 + 4_000 - 2_300);
- assert_eq!(detention.figures.suspended, 0);
+ caller.erase_cost(child.remaining());
+ assert_eq!(regular_spent(caller.tracker()), 9_000 + spent - 2_300, "{spent}");
+ detention.on_frame_run(&mut caller, 0);
+ assert_eq!(detention.compute(caller.tracker()), 9_000 + spent, "{spent}");
+ assert_eq!(detention.figures.suspended, 0);
+ }
}
- /// Nothing is kept of the frames before a read sets a limit but what a halt burns and one
- /// record per frame revm builds a child of. The first read rebuilds what the frames it runs
- /// under add to the transaction's compute from those records: each one's regular gas spent less
- /// its child's gas limit, a stipend included, and a halted child's burn taken off.
+ /// The frames' figures are kept from the transaction's first frame on, before any read: a
+ /// first read below them sets its limit from what the frames it runs under add to the
+ /// transaction's compute — each one's regular gas spent less the gas it forwarded its child,
+ /// which a value call's stipend is no part of — and a halted child's burn taken off.
#[test]
- fn test_the_first_read_rebuilds_the_compute_of_the_frames_it_runs_under() {
+ fn test_a_first_read_below_frames_counts_what_they_computed() {
const CAP: u64 = 1_000;
let mut detention = Detention::default();
detention.reset(true, CAP, CAP);
@@ -1041,8 +1004,7 @@ mod tests {
// A child that halts after running 1,000 of the 10,000 it was forwarded.
assert!(caller.record_withheld_first_cost(10_000));
- detention.on_frame_suspend(&caller, 0);
- detention.on_child_build(1, &caller);
+ detention.on_frame_suspend(&caller, 0, 0);
let mut halting = gas(10_000, 0);
detention.on_frame_run(&mut halting, 1);
assert!(halting.record_regular_cost(1_000));
@@ -1055,26 +1017,25 @@ mod tests {
// A value call: 9,000 of its own, 60,000 forwarded and a stipend of 2,300.
assert!(caller.record_regular_cost(9_000));
assert!(caller.record_withheld_first_cost(60_000));
- detention.on_frame_suspend(&caller, 0);
- detention.on_child_build(1, &caller);
+ detention.on_frame_suspend(&caller, 0, 2_300);
let mut child = gas(60_000 + 2_300, 0);
detention.on_frame_run(&mut child, 1);
assert!(child.record_regular_cost(4_000));
assert!(child.record_withheld_first_cost(30_000));
- detention.on_frame_suspend(&child, 1);
- detention.on_child_build(2, &child);
+ detention.on_frame_suspend(&child, 1, 0);
let mut grandchild = gas(30_000, 0);
detention.on_frame_run(&mut grandchild, 2);
assert!(grandchild.record_regular_cost(500));
- assert!(detention.figures.frames.is_empty(), "nothing kept before a read");
+ assert_eq!(detention.compute_limit(), None, "no read yet");
+ assert_eq!(detention.figures.frames.len(), 3, "kept before any read");
assert_eq!(detention.burned, 9_000);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut grandchild, 2, 0);
- let caller_adds = 2_000 + 10_000 + 9_000 + 60_000 - (60_000 + 2_300);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut grandchild, 0);
+ let caller_adds = 2_000 + 10_000 + 9_000 + 60_000 - 60_000;
let child_adds = 4_000 + 30_000 - 30_000;
assert_eq!(detention.figures.suspended, caller_adds + child_adds);
- let compute = 2_000 + 1_000 + 9_000 - 2_300 + 4_000 + 500;
- assert_eq!(detention.compute(&grandchild), compute);
+ let compute = 2_000 + 1_000 + 9_000 + 4_000 + 500;
+ assert_eq!(detention.compute(grandchild.tracker()), compute);
assert_eq!(detention.compute_limit(), Some(compute + CAP));
assert_eq!(grandchild.spendable(), CAP);
@@ -1084,41 +1045,21 @@ mod tests {
child.erase_cost(grandchild.remaining());
detention.on_frame_run(&mut child, 1);
assert_eq!(detention.figures.suspended, caller_adds);
- assert_eq!(detention.compute(&child), compute + 600);
+ assert_eq!(detention.compute(child.tracker()), compute + 600);
assert_eq!(child.spendable(), CAP - 600);
}
- /// A caller is recorded only while it may be needed: the transaction is detained and no read
- /// has set a limit yet. From the first read on, the frames are kept as they run.
- #[test]
- fn test_callers_are_recorded_only_until_the_first_read() {
- let mut free = Detention::default();
- free.reset(false, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS);
- assert!(!free.records_callers(), "a transaction detention does not hold");
-
- let mut detention = detaining();
- assert!(detention.records_callers());
- let mut frame = gas(1_000_000, 0);
- detention.on_frame_run(&mut frame, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0);
- assert!(!detention.records_callers(), "a read set a limit");
-
- detention.reset(true, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS);
- detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE);
- assert!(!detention.records_callers(), "a read before any frame set a limit");
- }
-
/// A transaction can end with frames still running — an error stops it mid-frame — and the
- /// next one starts from nothing: a read in its child rebuilds from its own records alone.
+ /// next one starts from nothing: a read in its child counts its own frames alone.
#[test]
fn test_a_reset_forgets_the_frames_a_transaction_left_running() {
let mut detention = detaining();
let mut caller = gas(1_000_000, 0);
detention.on_frame_run(&mut caller, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0);
assert!(caller.record_regular_cost(7_000));
assert!(caller.record_withheld_first_cost(500_000));
- detention.on_frame_suspend(&caller, 0);
+ detention.on_frame_suspend(&caller, 0, 0);
let mut child = gas(500_000, 0);
detention.on_frame_run(&mut child, 1);
assert_eq!(detention.figures.suspended, 7_000);
@@ -1128,45 +1069,18 @@ mod tests {
detention.on_frame_run(&mut caller, 0);
assert!(caller.record_regular_cost(3_000));
assert!(caller.record_withheld_first_cost(500_000));
- detention.on_frame_suspend(&caller, 0);
- detention.on_child_build(1, &caller);
+ detention.on_frame_suspend(&caller, 0, 0);
let mut child = gas(500_000, 0);
detention.on_frame_run(&mut child, 1);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut child, 1, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut child, 0);
assert_eq!(detention.figures.suspended, 3_000);
assert_eq!(detention.figures.frames.len(), 2);
assert_eq!(detention.compute_limit(), Some(3_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS));
}
- /// A reset forgets the callers a transaction recorded: the next one reads only its own.
- #[test]
- fn test_a_reset_forgets_the_callers_a_transaction_recorded() {
- let mut detention = detaining();
- let caller = gas(1_000_000, 0);
- detention.on_child_build(1, &caller);
- detention.on_child_build(2, &caller);
- assert_eq!(detention.callers.len(), 2);
-
- detention.reset(true, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS);
- assert!(detention.callers.is_empty());
- }
-
- /// The eager figures debug builds keep catch a kept figure that parts from them.
- #[cfg(debug_assertions)]
- #[test]
- #[should_panic(expected = "the compute of the suspended frames")]
- fn test_the_eager_figures_catch_a_kept_one_that_parts_from_them() {
- let mut eager = FrameFigures::default();
- eager.on_frame_run(1_000_000, 0);
- let mut kept = eager.clone();
- eager.assert_kept(&kept);
- kept.suspended = 1;
- eager.assert_kept(&kept);
- }
-
/// What a halting child burns is not compute: its caller's compute after it returns is what
/// the child ran, not the gas the child was given — whether the halt left the gas in place or
- /// zeroed it after the child's wrapper noted it.
+ /// zeroed it after the failed charge recorded what the child had.
#[test]
fn test_what_a_halt_burns_is_not_compute() {
for zeroed in [false, true] {
@@ -1174,13 +1088,13 @@ mod tests {
let mut caller = gas(1_000_000, 0);
detention.on_frame_run(&mut caller, 0);
assert!(caller.record_regular_cost(500_000));
- detention.on_frame_suspend(&caller, 0);
+ detention.on_frame_suspend(&caller, 0, 0);
let mut child = gas(500_000, 0);
detention.on_frame_run(&mut child, 1);
assert!(child.record_regular_cost(1_000));
assert!(child.record_state_cost(3_000));
let result = if zeroed {
- detention.note_halt(child.remaining());
+ assert!(!child.record_regular_cost(u64::MAX));
child.spend_all();
InstructionResult::OutOfGas
} else {
@@ -1190,7 +1104,7 @@ mod tests {
// The caller's regular gas spent now holds everything it forwarded.
detention.on_frame_run(&mut caller, 0);
- assert_eq!(detention.compute(&caller), 1_000, "zeroed: {zeroed}");
+ assert_eq!(detention.compute(caller.tracker()), 1_000, "zeroed: {zeroed}");
assert_eq!(detention.burned, 500_000 - 1_000);
}
}
@@ -1203,9 +1117,9 @@ mod tests {
let mut detention = detaining();
let mut caller = gas(100_000_000, 0);
detention.on_frame_run(&mut caller, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0);
assert!(caller.record_withheld_first_cost(90_000_000));
- detention.on_frame_suspend(&caller, 0);
+ detention.on_frame_suspend(&caller, 0, 0);
let answer = |spent: u64, result| {
let mut gas = gas(90_000_000, 0);
@@ -1240,7 +1154,7 @@ mod tests {
);
assert_eq!(beyond.result, InstructionResult::OutOfGas);
assert_eq!(beyond.gas.remaining(), 90_000_000 - spill);
- assert_eq!(regular_spent(&beyond.gas), 0);
+ assert_eq!(regular_spent(beyond.gas.tracker()), 0);
}
}
@@ -1253,9 +1167,9 @@ mod tests {
let mut detention = detaining();
let mut caller = gas(100_000_000, 0);
detention.on_frame_run(&mut caller, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0);
assert!(caller.record_withheld_first_cost(90_000_000));
- detention.on_frame_suspend(&caller, 0);
+ detention.on_frame_suspend(&caller, 0, 0);
let answer = |spent: u64| {
let mut gas = gas(90_000_000, 0);
assert!(gas.record_regular_cost(spent));
@@ -1291,9 +1205,9 @@ mod tests {
let mut detention = detaining();
let mut caller = gas(100_000_000, 0);
detention.on_frame_run(&mut caller, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut caller, 0);
assert!(caller.record_withheld_first_cost(90_000_000));
- detention.on_frame_suspend(&caller, 0);
+ detention.on_frame_suspend(&caller, 0, 0);
let allowance = detention.allowance(1, 90_000_000).unwrap();
assert_eq!(allowance, BLOCK_ENV_ACCESS_COMPUTE_GAS);
let withheld = NonZeroU64::new(90_000_000 - allowance).unwrap();
@@ -1348,10 +1262,10 @@ mod tests {
assert!(call.record_regular_cost(112_000));
assert!(call.record_withheld_first_cost(50_000_000));
- detention.on_frame_suspend(&call, 0);
+ detention.on_frame_suspend(&call, 0, 0);
let mut creation = gas(50_000_000, 0);
detention.on_frame_run(&mut creation, 1);
- assert_eq!(detention.compute(&creation), 112_000, "the charges, not the forward");
+ assert_eq!(detention.compute(creation.tracker()), 112_000, "the charges, not the forward");
assert_eq!(creation.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS - 112_000);
assert_eq!(detention.allowance(2, 0), Some(BLOCK_ENV_ACCESS_COMPUTE_GAS - 112_000));
}
@@ -1364,14 +1278,14 @@ mod tests {
let mut call = gas(100_000_000, 0);
detention.on_frame_run(&mut call, 0);
assert!(call.record_regular_cost(100_000));
- detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call, 0);
+ detention.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call);
assert_eq!(detention.compute_limit(), Some(100_000 + BLOCK_ENV_ACCESS_COMPUTE_GAS));
assert_eq!(detention.accessed(), VolatileDataAccess::BENEFICIARY_BALANCE);
assert_eq!(call.spendable(), BLOCK_ENV_ACCESS_COMPUTE_GAS);
let mut free = Detention::default();
free.reset(false, BLOCK_ENV_ACCESS_COMPUTE_GAS, ORACLE_ACCESS_COMPUTE_GAS);
- free.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call, 0);
+ free.read_by_frame(VolatileDataAccess::BENEFICIARY_BALANCE, &mut call);
assert_eq!((free.compute_limit(), free.accessed()), (None, VolatileDataAccess::empty()));
}
@@ -1382,7 +1296,7 @@ mod tests {
let mut detention = detaining();
let mut frame = gas(1_000_000, 0);
detention.on_frame_run(&mut frame, 0);
- detention.on_frame_suspend(&frame, 0);
+ detention.on_frame_suspend(&frame, 0, 0);
let mut child = gas(100_000, 0);
detention.on_frame_run(&mut child, 1);
detention.disable_access(2);
@@ -1396,8 +1310,10 @@ mod tests {
detention.disable_access(2);
assert!(detention.is_access_disabled(1), "a deeper frame keeps the shallower switch");
assert!(!detention.enable_access(2), "a frame below cannot switch it back on");
+ detention.begin_read();
assert!(detention.refuses(VolatileDataAccess::BLOCK_NUMBER));
detention.name_refusal(VolatileDataAccess::BLOCK_HASH);
+ detention.end_read();
assert_eq!(detention.take_refused(), Some(VolatileDataAccess::BLOCK_HASH));
detention.name_refusal(VolatileDataAccess::BLOCK_HASH);
assert_eq!(detention.take_refused(), None, "nothing refused, nothing named");
@@ -1409,10 +1325,42 @@ mod tests {
detention.disable_access(0);
detention.on_frame_run(&mut frame, 0);
+ detention.begin_read();
assert!(detention.refuses(VolatileDataAccess::TIMESTAMP));
+ detention.end_read();
+ assert_eq!(detention.take_refused(), Some(VolatileDataAccess::TIMESTAMP));
assert!(detention.enable_access(0), "the frame that switched it off switches it on");
detention.on_frame_run(&mut frame, 0);
+ detention.begin_read();
assert!(!detention.refuses(VolatileDataAccess::TIMESTAMP));
+ detention.end_read();
+ }
+
+ /// The Host refuses and marks a load only while a read wrapper runs its opcode: a load outside
+ /// one — a creation's of its creator or created address, an inspector's — is neither refused
+ /// nor marked, whether the frame's access is on or off.
+ #[test]
+ fn test_only_a_read_wrappers_load_is_refused_or_marked() {
+ let beneficiary = VolatileDataAccess::BENEFICIARY_BALANCE;
+ let mut detention = detaining();
+ let mut frame = gas(1_000_000, 0);
+ detention.on_frame_run(&mut frame, 0);
+ detention.observe(beneficiary);
+ assert!(!detention.has_reads(), "a load outside a read marks nothing");
+ detention.begin_read();
+ detention.observe(beneficiary);
+ detention.end_read();
+ assert_eq!(detention.take_observed(), beneficiary);
+
+ detention.disable_access(0);
+ detention.on_frame_run(&mut frame, 0);
+ assert!(detention.is_refusing());
+ assert!(!detention.refuses(beneficiary), "a load outside a read is not refused");
+ assert!(!detention.has_reads());
+ detention.begin_read();
+ assert!(detention.refuses(beneficiary));
+ detention.end_read();
+ assert_eq!(detention.take_refused(), Some(beneficiary));
}
/// A refusal's revert data decodes back to the kind it names, for every kind the engine
@@ -1505,11 +1453,11 @@ mod tests {
assert!(detention.detains());
let mut frame = gas(100_000_000, 0);
detention.on_frame_run(&mut frame, 0);
- detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0, 0);
+ detention.commit_reads(VolatileDataAccess::TIMESTAMP, &mut frame, 0);
detention.mark_before_execution(VolatileDataAccess::BENEFICIARY_BALANCE);
assert_eq!(detention.compute_limit(), None, "an unlimited cap sets no limit");
assert_eq!(frame.withheld(), 0);
- detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0, 0);
+ detention.commit_reads(VolatileDataAccess::ORACLE, &mut frame, 0);
assert_eq!(detention.compute_limit(), Some(5));
}
}
diff --git a/crates/mega-evm/src/access/mod.rs b/crates/mega-evm/src/access/mod.rs
index d02593039..613c9161a 100644
--- a/crates/mega-evm/src/access/mod.rs
+++ b/crates/mega-evm/src/access/mod.rs
@@ -37,22 +37,27 @@
//! (which every account opcode and every call goes through, the EIP-7702 delegate's included), its
//! storage load and its `SELFDESTRUCT`. A load that fails — a cold account the frame cannot pay
//! for, a database error — marks nothing, and neither does an opcode that fails after the load:
-//! the Host only observes, and the opcode's wrapper commits the read once the opcode completed,
-//! as it does with a write record.
+//! the Host only marks the read, and the opcode's wrapper commits it once the opcode completed, as
+//! a write record is counted only once its opcode completed.
+//!
+//! A load is a read only when one of those opcodes makes it, inside its wrapper. `CREATE` and
+//! `CREATE2` load their creator's account and the created address's through the same Host load,
+//! to check the creator's balance and nonce and to price the created account; those loads are the
+//! creation's own checks, as a value call's check of its caller's balance is the call's, and are
+//! neither marked nor refused, whichever of the two accounts is the beneficiary's.
//!
//! # The cap
//!
//! Compute is the regular gas the transaction spends on what it runs, read off revm's `Gas`: state
//! and history gas that spilled onto regular gas are not compute, gas withheld from regular
-//! charges is never spent, and what a halting frame burns is not compute either ([`Detention`]).
-//! The one burn counted as compute is what a frame has left when an opcode's static gas fails,
-//! which no wrapper sees: per halting frame, under the failed charge's price (at most 4,999, on
-//! `SELFDESTRUCT`). Burned gas is counted as compute, so the stop comes earlier, never later.
-//! A value call's stipend is not compute either: compute is regular gas drawn from the
-//! transaction's own pools, and the stipend is gas nobody paid. A callee may run up to 2,300 gas
-//! on each value call's stipend, and a warm value call to an empty account counts 6,800 of compute
-//! (9,100, less the 2,300 stipend the callee leaves unspent and returns to its caller), so the
-//! gas run after a read is at most about 34% (2,300 / 6,800) more than the cap.
+//! charges is never spent, and what a halting frame burns is not compute either ([`Detention`]),
+//! whatever charge it failed on, an opcode's static gas included: the revm fork records what the
+//! frame had before the halt zeroed it. What a callee runs on a value call's stipend is compute, as
+//! everything a frame runs is: compute counts every regular charge an instruction makes, whoever
+//! funds it, and nothing else, so the gas run after a read is at most the cap. The stipend itself
+//! is gas nobody paid, so the regular ledger bills the transaction its compute less the stipends of
+//! its value calls. A precompile that runs out of gas counts nothing of its forward: it burns it,
+//! as a halting frame burns what it has left.
//!
//! A read sets a limit: the transaction's compute at the read plus the read's cap. The limit only
//! goes down, so the most restrictive of several reads is the one that binds, whatever their
@@ -64,7 +69,7 @@
//! the frame runs out of regular gas. So the cap is enforced through the frame's gas, with the
//! revm fork's two parts of a frame's regular gas: a spendable part, the only one a regular charge
//! draws, and a withheld part. Every other reader of the frame's gas sees the two together — `GAS`,
-//! the 63/64 forward and the clamp on an explicit call gas, the `SSTORE` sentry, the skip-cold
+//! the 98/100 forward and the clamp on an explicit call gas, the `SSTORE` sentry, the skip-cold
//! checks, the gas a child returns, the reimbursement — and a forward or a state or history spill
//! draws the withheld part first.
//!
diff --git a/crates/mega-evm/src/block/eips.rs b/crates/mega-evm/src/block/eips.rs
index 54531548f..62e245c28 100644
--- a/crates/mega-evm/src/block/eips.rs
+++ b/crates/mega-evm/src/block/eips.rs
@@ -5,7 +5,8 @@
//! sequence of committed states, read and write sets whole, is what a node's witness generator
//! collects through a commit hook on the block's state.
//!
-//! A pre-block call is a system call on [`pre_block_call_gas_limit`], and a block whose
+//! A pre-block call is a system call on
+//! [`PRE_BLOCK_CALL_GAS_LIMIT`](crate::constants::PRE_BLOCK_CALL_GAS_LIMIT), and a block whose
//! pre-block call does not succeed is refused: the state the protocol maintains before the
//! block's transactions is not optional, and a block that could not write it is not one the
//! chain can build on. A database error the database calls fatal is not a verdict on the block:
@@ -30,12 +31,9 @@ use alloy_evm::block::{BlockExecutionError, BlockValidationError};
use alloy_hardforks::EthereumHardforks;
use alloy_primitives::{Address, Bytes, B256};
use op_revm::OpHaltReason;
-use revm::{
- context::{
- result::{EVMError, ResultAndState},
- Block, ContextTr, DBErrorMarker,
- },
- handler::SYSTEM_CALL_REGULAR_GAS_LIMIT,
+use revm::context::{
+ result::{EVMError, ResultAndState},
+ Block, ContextTr, DBErrorMarker,
};
use crate::{ExternalEnvTypes, MegaEvm};
@@ -43,24 +41,10 @@ use crate::{ExternalEnvTypes, MegaEvm};
/// The caller every pre-block system call runs as.
pub use alloy_eips::eip4788::SYSTEM_ADDRESS;
-/// The gas limit of every pre-block system call in a block whose gas limit is `block_gas_limit`:
-/// the block's gas limit, and never less than 30,000,000.
-///
-/// It is the legacy engine's budget, kept as it was rather than replaced by a number nobody
-/// chose. The legacy engine sized it to absorb the storage gas a crowded SALT bucket multiplies,
-/// which could take a pre-block write past revm's 30M default. On Satin neither half of that
-/// holds: a system call prices its state at the minimum bucket, and it runs on at most
-/// 30,000,000 of regular gas, the rest of its gas limit being its state-gas reservoir. So what
-/// this budget adds above 30M is reservoir, which the call's writes draw first and which nobody
-/// pays for when they do not, and the regular budget is 30M whatever the block. In a block whose
-/// gas limit is 30M or less the call has no reservoir, and its writes are paid out of the
-/// regular budget, which holds them many times over.
-pub fn pre_block_call_gas_limit(block_gas_limit: u64) -> u64 {
- block_gas_limit.max(SYSTEM_CALL_REGULAR_GAS_LIMIT)
-}
-
/// Runs the pre-block call `name`: a system call from [`SYSTEM_ADDRESS`] to `target` with `data`,
-/// on the pre-block budget of the block `evm` is set up for ([`pre_block_call_gas_limit`]).
+/// on the pre-block budget
+/// ([`PRE_BLOCK_CALL_GAS_LIMIT`](crate::constants::PRE_BLOCK_CALL_GAS_LIMIT)), whatever the
+/// block's gas limit.
/// Answers its result and state; nothing is committed.
///
/// One rule holds for every pre-block call, and it is the rule alloy-evm's block executor holds a
@@ -85,15 +69,13 @@ where
DB: alloy_evm::Database,
ExtEnvs: ExternalEnvTypes,
{
- let gas_limit = pre_block_call_gas_limit(evm.ctx().block().gas_limit());
- let outcome =
- match evm.transact_system_call_with_gas_limit(SYSTEM_ADDRESS, target, data, gas_limit) {
- Ok(outcome) => outcome,
- Err(EVMError::Database(error)) if error.is_fatal() => {
- return Err(BlockExecutionError::other(error))
- }
- Err(error) => return Err(refused(error.to_string())),
- };
+ let outcome = match evm.transact_pre_block_system_call(SYSTEM_ADDRESS, target, data) {
+ Ok(outcome) => outcome,
+ Err(EVMError::Database(error)) if error.is_fatal() => {
+ return Err(BlockExecutionError::other(error))
+ }
+ Err(error) => return Err(refused(error.to_string())),
+ };
if !outcome.result.is_success() {
let message = format!("the {name} pre-block call did not succeed: {:?}", outcome.result);
return Err(refused(message));
diff --git a/crates/mega-evm/src/block/executor.rs b/crates/mega-evm/src/block/executor.rs
index 39ae6ab14..92e174a38 100644
--- a/crates/mega-evm/src/block/executor.rs
+++ b/crates/mega-evm/src/block/executor.rs
@@ -30,18 +30,6 @@
//! block contract reads as zeroes, not as an error, and a caller that placed its own info for
//! this block keeps it. alloy-op-evm's executor pre-loads no info either.
//!
-//! # The admission gate
-//!
-//! Block execution refuses an inspector that may rewrite what execution produces
-//! ([`MegaEvm::has_rewriting_inspector`]). alloy-evm's `BlockExecutorFactory` asks for an executor
-//! for every `I: Inspector`, so the refusal cannot be a bound on the type: it is checked at every
-//! entry point that runs code or moves the block on — the pre-block changes, the execution of a
-//! transaction, the commit of an outcome and the end of the block — before anything changes. The
-//! trusted route
-//! ([`create_executor_with_trusted_inspector`](crate::MegaBlockExecutorFactory::create_executor_with_trusted_inspector))
-//! is the compile-time proof that an inspector observes and writes nothing back; the generic route
-//! is the checked one.
-//!
//! # Committing an outcome
//!
//! alloy-evm's [`commit_transaction`](BlockExecutor::commit_transaction) cannot fail. Its contract
@@ -90,8 +78,9 @@
//! and EIP-4788 calls, in the block in which Satin activates checks that the system contracts and
//! the EIP-7997 factory hold the code Satin expects, then applies a role change the
//! `SequencerRegistry` has due in this block. Every call is a system call
-//! on the pre-block budget ([`pre_block_call_gas_limit`](crate::pre_block_call_gas_limit)), and
-//! one that does not succeed refuses the block.
+//! on the pre-block budget
+//! ([`PRE_BLOCK_CALL_GAS_LIMIT`](crate::constants::PRE_BLOCK_CALL_GAS_LIMIT)), and one that does
+//! not succeed refuses the block.
//!
//! The pre-block step does not read the live system address, but it is what leaves the registry
//! naming this block's address. The executor reads the address off the block's state before every
@@ -225,11 +214,6 @@ pub enum MegaBlockExecutionError {
/// The footprint the block has left.
available_block_da_footprint: u64,
},
- /// The EVM runs an inspector that may rewrite what execution produces, which block execution
- /// does not admit.
- ///
- /// The inspector is the node's own choice, not a verdict on the block: an internal error.
- RewritingInspector,
/// In the block in which Satin activates, a predeploy's address does not hold the code Satin
/// expects: it holds other code, an older version of the contract, no code, or no account.
///
@@ -277,9 +261,6 @@ impl fmt::Display for MegaBlockExecutionError {
transaction_da_footprint: {transaction_da_footprint}, \
available_block_da_footprint: {available_block_da_footprint}"
),
- Self::RewritingInspector => f.write_str(
- "block execution does not admit an inspector that may rewrite execution",
- ),
Self::UnexpectedSystemContractCode { address, expected, found } => {
write_unexpected_code(f, *address, *expected, *found)
}
@@ -298,13 +279,12 @@ impl fmt::Display for MegaBlockExecutionError {
impl core::error::Error for MegaBlockExecutionError {}
impl From for BlockExecutionError {
- /// A block refused for what the node itself does is an internal error: an inspector the node
- /// runs that may rewrite execution, or an outcome the builder let go stale, says nothing about
- /// the block, and a node must not mark a block invalid because of its own choices. Every other
+ /// A block refused for what the node itself does is an internal error: an outcome the builder
+ /// let go stale says nothing about the block, and a node must not mark a block invalid because
+ /// of its own choices. Every other
/// refusal is a verdict on the block, a validation error.
fn from(error: MegaBlockExecutionError) -> Self {
match error {
- MegaBlockExecutionError::RewritingInspector |
MegaBlockExecutionError::StaleOutcome { .. } => Self::other(error),
MegaBlockExecutionError::UnexpectedNonDepositTxInActivationBlock |
MegaBlockExecutionError::TransactionDaFootprintAboveGasLimit { .. } |
@@ -405,14 +385,16 @@ where
/// test's, which a node executing the chain never runs.
///
/// Their per-transaction half is installed on the EVM and before every transaction from now
- /// on, and the block's data-size budget is theirs, lowered to the building policy where that
- /// is lower. What the block counted so far stays counted. Behind the `test-utils` feature, so
- /// a node build cannot reach it.
+ /// on, and the block's packing budgets are theirs, each lowered to the building policy where
+ /// that is lower. What the block counted so far stays counted. Behind the `test-utils` feature,
+ /// so a node build cannot reach it.
#[cfg(any(test, feature = "test-utils"))]
pub fn with_protocol_limits(mut self, limits: ProtocolLimits) -> Self {
self.evm.set_tx_runtime_limits(limits.tx_runtime_limits);
- self.limiter.limits.block_txs_data_limit =
- self.ctx.block_limits.within(&limits).block_txs_data_limit;
+ let held = self.ctx.block_limits.within(&limits);
+ self.limiter.limits.block_txs_data_limit = held.block_txs_data_limit;
+ self.limiter.limits.block_kv_update_limit = held.block_kv_update_limit;
+ self.limiter.limits.block_state_growth_limit = held.block_state_growth_limit;
self.protocol_limits = limits;
self
}
@@ -532,19 +514,6 @@ where
.map_err(BlockExecutionError::other)?;
Ok(classify_system_transaction(tx, system_address).unwrap_or(false))
}
-
- /// Refuses an EVM that runs an inspector which may rewrite what execution produces.
- ///
- /// Checked at every entry point rather than once, because the inspector can be enabled after
- /// the block was set up ([`Evm::set_inspector_enabled`] through
- /// [`evm_mut`](BlockExecutor::evm_mut)) and because a caller may run transactions without
- /// calling [`apply_pre_execution_changes`](BlockExecutor::apply_pre_execution_changes) at all.
- fn check_admission(&self) -> Result<(), BlockExecutionError> {
- if self.evm.has_rewriting_inspector() {
- return Err(MegaBlockExecutionError::RewritingInspector.into());
- }
- Ok(())
- }
}
impl MegaBlockExecutor, R, Spec>
@@ -625,7 +594,7 @@ where
/// Runs what a block does before its transactions.
///
- /// In order: the admission gate, the reset of the block-hash and bucket records, the EIP-2935
+ /// In order: the reset of the block-hash and bucket records, the EIP-2935
/// and EIP-4788 pre-block calls, in the block in which Satin activates the check of the
/// predeploys, the `SequencerRegistry`'s due role changes and the read of the L1 block info.
/// Each step's state is committed here, on its own and read-only entries included, rather
@@ -643,8 +612,8 @@ where
/// parent beacon root into their own contracts (`0x0…2935` and `0x0…4788`), which are not
/// `MegaETH` system contracts and do not read them, so their outcome does not depend on the
/// check that follows. Each runs on the pre-block budget
- /// ([`pre_block_call_gas_limit`](eips::pre_block_call_gas_limit)), and one that does not
- /// succeed refuses the block before its state is committed.
+ /// ([`PRE_BLOCK_CALL_GAS_LIMIT`](crate::constants::PRE_BLOCK_CALL_GAS_LIMIT)), and one that
+ /// does not succeed refuses the block before its state is committed.
///
/// The check is made once, in the block in which Satin activates
/// ([`MegaBlockExecutionCtx::satin_activation_block`]): each of the seven predeploys must hold
@@ -661,8 +630,6 @@ where
/// it is validated, after these steps are committed, and nothing inside the block can
/// change it again.
fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> {
- self.check_admission()?;
-
// The block starts with empty block-hash and bucket records, so what they hold at the end
// is what this block read.
self.evm.clear_accessed_block_hashes();
@@ -892,7 +859,7 @@ where
self.execute(tx, Some(reported))
}
- /// Re-checks the block's admission and commits `output`.
+ /// Re-checks the block's limits and commits `output`.
///
/// This is the commit for a builder that executes several candidates and then chooses among
/// them: the block's counters may have moved between a candidate executing and its commit, so
@@ -911,7 +878,6 @@ where
&mut self,
output: MegaBlockTxResult<::TxType>,
) -> Result {
- self.check_admission()?;
self.check_room(&output)?;
self.check_sender_unchanged(&output)?;
Ok(self.commit_transaction(output))
@@ -927,8 +893,6 @@ where
MegaBlockTxResult<::TxType>,
BlockExecutionError,
> {
- self.check_admission()?;
-
let (tx_env, tx) = tx.into_parts();
let inner = tx.tx();
let is_deposit = inner.ty() == DEPOSIT_TRANSACTION_TYPE;
@@ -1035,8 +999,6 @@ where
pub fn finish_with_counters(
mut self,
) -> Result, BlockExecutionError> {
- self.check_admission()?;
-
let balance_increments =
post_block_balance_increments::(&self.spec, self.evm.block(), &[], None);
self.evm
@@ -1093,6 +1055,14 @@ mod tests {
executor.limiter().limits.block_txs_data_limit,
crate::constants::BLOCK_DATA_LIMIT
);
+ assert_eq!(
+ (
+ executor.limiter().limits.block_kv_update_limit,
+ executor.limiter().limits.block_state_growth_limit
+ ),
+ (crate::constants::BLOCK_KV_UPDATE_LIMIT, crate::constants::BLOCK_STATE_GROWTH_LIMIT),
+ "and the spec's KV and state-growth budgets"
+ );
executor.evm_mut().set_inspector_enabled(true);
assert!(executor.into_evm().is_inspecting());
}
@@ -1117,11 +1087,16 @@ mod tests {
assert_eq!(*executor.evm().tx_runtime_limits(), satin.tx_runtime_limits);
assert_eq!(executor.limiter().limits.block_txs_data_limit, 13_107_200);
- let counterfactual = ProtocolLimits::no_limits().with_block_txs_data_limit(7);
+ let counterfactual = ProtocolLimits::no_limits()
+ .with_block_txs_data_limit(7)
+ .with_block_kv_update_limit(8)
+ .with_block_state_growth_limit(9);
let executor = executor.with_protocol_limits(counterfactual);
assert_eq!(executor.protocol_limits(), &counterfactual);
assert_eq!(*executor.evm().tx_runtime_limits(), counterfactual.tx_runtime_limits);
assert_eq!(executor.limiter().limits.block_txs_data_limit, 7);
+ assert_eq!(executor.limiter().limits.block_kv_update_limit, 8);
+ assert_eq!(executor.limiter().limits.block_state_growth_limit, 9);
let tighter = MegaBlockExecutor::new(
MegaEvm::new(MegaContext::new(MemoryDatabase::default(), MegaSpecId::SATIN)),
@@ -1146,9 +1121,9 @@ mod tests {
.unwrap_or_else(|| panic!("not an internal refusal of this engine: {error:?}"))
}
- /// Every refusal but those for what the node itself does — an inspector it runs, here — is a
- /// verdict on the block: a validation error. A predeploy that does not hold Satin's code when
- /// Satin activates is one.
+ /// Every refusal but those for what the node itself does — an outcome it let go stale, here —
+ /// is a verdict on the block: a validation error. A predeploy that does not hold Satin's code
+ /// when Satin activates is one.
#[test]
fn test_a_refusal_of_the_block_is_a_validation_error() {
let address = alloy_primitives::Address::repeat_byte(1);
@@ -1172,7 +1147,7 @@ mod tests {
};
assert_eq!(inner.downcast_ref::(), Some(&refusal));
}
- let inspector = MegaBlockExecutionError::RewritingInspector;
- assert_eq!(internal(&BlockExecutionError::from(inspector.clone())), &inspector);
+ let stale = MegaBlockExecutionError::StaleOutcome { tx_hash: B256::ZERO, sender: address };
+ assert_eq!(internal(&BlockExecutionError::from(stale.clone())), &stale);
}
}
diff --git a/crates/mega-evm/src/block/factory.rs b/crates/mega-evm/src/block/factory.rs
index 3e4e7bc55..4f3339975 100644
--- a/crates/mega-evm/src/block/factory.rs
+++ b/crates/mega-evm/src/block/factory.rs
@@ -4,14 +4,14 @@ use alloy_consensus::{Transaction, TxReceipt};
use alloy_eips::Encodable2718;
use alloy_evm::{
block::{BlockExecutorFactory, StateDB},
- EvmEnv, EvmFactory, FromRecoveredTx, FromTxWithEncoded,
+ FromRecoveredTx, FromTxWithEncoded,
};
use alloy_op_evm::block::receipt_builder::OpReceiptBuilder;
use revm::Inspector;
use crate::{
ExternalEnvFactory, MegaBlockExecutionCtx, MegaBlockExecutor, MegaBlockTxResult, MegaContext,
- MegaEvm, MegaEvmFactory, MegaHardforks, MegaSpecId, MegaTransaction, TrustedObserver,
+ MegaEvm, MegaEvmFactory, MegaHardforks, MegaTransaction,
};
/// Creates the block executors a node drives.
@@ -51,36 +51,6 @@ impl MegaBlockExecutorFactory {
}
}
-impl MegaBlockExecutorFactory>
-where
- ExtEnvFactory: ExternalEnvFactory,
- Spec: MegaHardforks,
- R: OpReceiptBuilder,
-{
- /// Creates an executor over an EVM that runs a declared observer.
- ///
- /// This is the one way an inspected transaction reaches a block: the inspector's type
- /// declares that it writes nothing back ([`TrustedObserver`]), so what the block executes is
- /// what the chain executes, and this bound is the compile-time proof of it. An inspector
- /// that arrives through [`create_executor`](BlockExecutorFactory::create_executor) carries no
- /// such proof, so block execution checks it at every entry point instead and refuses it with
- /// `RewritingInspector`.
- pub fn create_executor_with_trusted_inspector(
- &self,
- db: DB,
- evm_env: EvmEnv,
- ctx: MegaBlockExecutionCtx,
- inspector: I,
- ) -> MegaBlockExecutor, &R, &Spec>
- where
- DB: StateDB,
- I: TrustedObserver + Inspector>,
- {
- let evm = self.evm_factory.create_evm(db, evm_env).with_trusted_inspector(inspector);
- MegaBlockExecutor::new(evm, ctx, &self.spec, &self.receipt_builder)
- }
-}
-
impl BlockExecutorFactory
for MegaBlockExecutorFactory>
where
@@ -108,10 +78,8 @@ where
/// The spec's limits are installed by [`MegaBlockExecutor::new`], so an EVM the caller built
/// with others still runs the block's transactions under them.
///
- /// alloy-evm asks for an executor for every `I: Inspector`, so this route cannot refuse a
- /// rewriting inspector by its type; the executor checks the EVM at every entry point instead.
- /// [`create_executor_with_trusted_inspector`](Self::create_executor_with_trusted_inspector) is
- /// the route whose bound proves the inspector observes only.
+ /// The EVM may carry any inspector: the engine does not refuse one, and a node decides which
+ /// inspectors run on block production.
fn create_executor<'a, DB, I>(
&'a self,
evm: MegaEvm,
diff --git a/crates/mega-evm/src/block/genesis.rs b/crates/mega-evm/src/block/genesis.rs
index 3fe4ce493..c50facd36 100644
--- a/crates/mega-evm/src/block/genesis.rs
+++ b/crates/mega-evm/src/block/genesis.rs
@@ -65,11 +65,10 @@ const ARBITRARY_PRECISION_NUMBER: &str = "$serde_json::private::Number";
/// key cannot stand in for the one it meant, and a file written against an earlier version of the
/// format — one that named the registry's roles (`satinInitialSequencer`, ...) or the limits —
/// does not load. Every other key is another fork's and is not read.
-/// - A key given twice is refused only where the deserializer still shows both copies, as the
-/// object's text through a `serde_json::Deserializer` does. A `serde_json::Value` has already
-/// kept the last copy, so a reader that parses the file into one first — `mega-evme --genesis`
-/// does, and so does a node that serializes its chain-config type — reads the last value and
-/// refuses nothing.
+/// - A key given twice is read as its last copy, as `serde_json` reads an object into a
+/// `serde_json::Value`: a reader handed the object's text, which still shows both copies, and a
+/// reader that parses the file into a `Value` first — `mega-evme --genesis` does, and so does a
+/// node that serializes its chain-config type — read the same value.
/// - A value of the wrong type is refused, naming its key, and so is a schedule
/// [`validate_schedule`](MegaHardforks::validate_schedule) refuses. One object is read as an
/// integer: `{"$serde_json::private::Number": ""}`, the form `serde_json` hands a number
@@ -113,12 +112,9 @@ impl SatinChainConfig {
pub fn from_genesis_config<'de, D: Deserializer<'de>>(
config: D,
) -> Result